: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(notebooks): isolate behind facade and contracts (#65290)
Arthur Moreira de Deus12d4f9639178
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.pyindex 935626ef81a0..4b4133454edd 100644--- a/ee/clickhouse/views/groups.py+++ b/ee/clickhouse/views/groups.py@@ -4,7 +4,7 @@ from collections import defaultdictfrom typing import Any, Literal, Optional, cast, overloadfrom urllib.parse import urlencode-from django.db import IntegrityError, transaction+from django.db import IntegrityErrorfrom django.utils import timezoneimport structlog@@ -48,8 +48,8 @@ from posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.utils import str_to_boolfrom products.event_definitions.backend.models.property_definition import PropertyType-from products.notebooks.backend.models import Notebook, ResourceNotebook-from products.notebooks.backend.util import (+from products.notebooks.backend.facade import api as notebooks+from products.notebooks.backend.facade.content import (create_bullet_list,create_empty_paragraph,create_heading_with_text,@@ -258,8 +258,7 @@ class FindGroupSerializer(GroupSerializer):fields = [*GroupSerializer.Meta.fields, "notebook"]def get_notebook(self, obj: Group) -> str | None:- notebooks = ResourceNotebook.objects.filter(group=obj.id).first()- return notebooks.notebook.short_id if notebooks else None+ return notebooks.get_group_notebook_short_id(obj.id)class CreateGroupSerializer(serializers.ModelSerializer):@@ -532,7 +531,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Createif (not skip_create_notebookand self._is_crm_enabled(cast(User, request.user))- and not ResourceNotebook.objects.filter(group=group.id).exists()+ and not notebooks.group_has_notebook(group.id)):try:self._create_notebook_for_group(group=group)@@ -872,7 +871,6 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Createsend_feature_flag_events=False,)- @transaction.atomicdef _create_notebook_for_group(self, group: Group):group_name = group.group_properties.get("name", "")notebook_title = f"{group_name} Notes" if group_name else "Notes"@@ -890,13 +888,7 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Createcreate_heading_with_text(text="Last interaction", level=2),create_bullet_list(items=["Date: ", "Context: ", "Next steps: "]),]- notebook = Notebook.objects.create(- team=self.team,- title=notebook_title,- content=notebook_content,- visibility=Notebook.Visibility.INTERNAL,- )- ResourceNotebook.objects.create(notebook=notebook, group=group.id)+ notebooks.create_group_notebook(self.team.id, group.id, title=notebook_title, content=notebook_content)_DW_FILTER_REQUIRED_FIELDS = ("table_name", "timestamp_field", "key_field")diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.pyindex 3c7e54844859..bbebc69ca459 100644--- a/ee/clickhouse/views/test/test_clickhouse_groups.py+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py@@ -294,7 +294,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):)@freeze_time("2021-05-02")- @patch(f"{PATH}.ResourceNotebook.objects.create", side_effect=IntegrityError)+ @patch("products.notebooks.backend.logic.ResourceNotebook.objects.create", side_effect=IntegrityError)@patch(f"{PATH}.posthoganalytics.feature_enabled", return_value=True)def test_retrieve_group_notebook_transaction_rollback(self, _, mock_relationship_create):index: GroupTypeIndex = 0diff --git a/ee/hogai/artifacts/handlers/notebook.py b/ee/hogai/artifacts/handlers/notebook.pyindex f39163d28f5f..16471dff5927 100644--- a/ee/hogai/artifacts/handlers/notebook.py+++ b/ee/hogai/artifacts/handlers/notebook.py@@ -9,7 +9,7 @@ from posthog.schema import ArtifactContentType, ErrorBlock, NotebookArtifactContfrom posthog.models import Team-from products.notebooks.backend.models import Notebook+from products.notebooks.backend.facade import api as notebooksfrom products.posthog_ai.backend.models.assistant import AgentArtifactfrom ee.hogai.artifacts.handlers.base import (@@ -125,7 +125,7 @@ class NotebookHandler(ArtifactHandler[StoredNotebookArtifactContent, NotebookArtis_saved = Falseif context.artifact_id:- is_saved = await Notebook.objects.filter(team=context.team, short_id=context.artifact_id).aexists()+ is_saved = await notebooks.anotebook_exists(context.team.id, context.artifact_id)return NotebookArtifactContent(blocks=enriched_blocks,diff --git a/ee/hogai/tools/create_notebook/helpers.py b/ee/hogai/tools/create_notebook/helpers.pyindex 5c3b98cbe08e..d63e5765fee4 100644--- a/ee/hogai/tools/create_notebook/helpers.py+++ b/ee/hogai/tools/create_notebook/helpers.py@@ -2,16 +2,14 @@ from collections.abc import Sequencefrom enum import Enumfrom typing import Any-from django.db.models import F-from django.utils import timezone--from asgiref.sync import sync_to_async-from posthog.models import Team, Userfrom posthog.rbac.user_access_control import UserAccessControl-from products.notebooks.backend import markdown_collab-from products.notebooks.backend.models import Notebook+from products.notebooks.backend.facade import (+ api as notebooks,+ collab,+)+from products.notebooks.backend.facade.contracts import NotebookDatafrom products.posthog_ai.backend.models.assistant import AgentArtifactfrom ee.hogai.artifacts.handlers.visualization import VisualizationHandler@@ -112,7 +110,7 @@ async def save_notebook_to_db(title: str,state_messages: Sequence[AssistantMessageUnion],markdown_content: str | None = None,-) -> Notebook:+) -> NotebookData:"""Save or update a real Notebook record with the same short_id as the artifact.@@ -123,33 +121,36 @@ async def save_notebook_to_db(have editor access to it — Max acts on the user's behalf and must not overwritenotebooks the user couldn't edit themselves."""- existing_notebook = await Notebook.objects.filter(team=team, short_id=artifact.short_id).afirst()- if existing_notebook and not await _acan_user_edit_notebook(team, user, existing_notebook):- raise NotebookEditNotAllowedError(- f"User {user.id} does not have editor access to notebook {existing_notebook.short_id}"- )+ existing_notebook = await notebooks.aget_notebook(team.id, artifact.short_id, include_deleted=True)+ if existing_notebook is not None:+ access_control = UserAccessControl(user=user, team=team)+ if not await notebooks.acan_user_edit_notebook(team.id, artifact.short_id, user_access_control=access_control):+ raise NotebookEditNotAllowedError(+ f"User {user.id} does not have editor access to notebook {existing_notebook.short_id}"+ )if existing_notebook and markdown_content is not None and _get_markdown_notebook_node(existing_notebook.content):previous_content = existing_notebook.contentnext_content = _build_markdown_notebook_doc(markdown_content, previous_content)- await Notebook.objects.filter(pk=existing_notebook.pk).aupdate(+ updated_notebook = await notebooks.aupdate_notebook_content(+ team.id,+ artifact.short_id,content=next_content,title=title,text_content=markdown_content,- version=F("version") + 1,- last_modified_by=user,- last_modified_at=timezone.now(),+ last_modified_by_id=user.id,)- await existing_notebook.arefresh_from_db()+ if updated_notebook is None:+ raise RuntimeError(f"Notebook {artifact.short_id} disappeared during content update")# The base_crc inside the diff lets receivers detect a racing concurrent edit# (this path has no version CAS) and fall back to a reload instead of misapplying.- await markdown_collab.apublish_notebook_update(+ await collab.apublish_notebook_update(team.id,- str(existing_notebook.short_id),- existing_notebook.version,- diff=markdown_collab.build_markdown_update_diff(previous_content, next_content),+ str(updated_notebook.short_id),+ updated_notebook.version,+ diff=collab.build_markdown_update_diff(previous_content, next_content),)- return existing_notebook+ return updated_notebook# Resolve viz refs through the unified handler (state → AgentArtifact → Insight),# matching the chat preview. A direct AgentArtifact query misses state-only charts.@@ -177,34 +178,19 @@ async def save_notebook_to_db(tiptap_doc = blocks_to_tiptap_doc(blocks, title=title, resolve_visualization=resolve_visualization)- notebook, created = await Notebook.objects.aget_or_create(- team=team,- short_id=artifact.short_id,- defaults={- "created_by": user,- "last_modified_by": user,- "title": title,- "content": tiptap_doc,- },+ notebook, created = await notebooks.aupsert_notebook(+ team.id,+ artifact.short_id,+ created_by_id=user.id,+ last_modified_by_id=user.id,+ title=title,+ content=tiptap_doc,)if not created:- notebook.content = tiptap_doc- notebook.title = title- notebook.version += 1- notebook.last_modified_by = user- await notebook.asave(update_fields=["content", "title", "version", "last_modified_by", "last_modified_at"])- await markdown_collab.apublish_notebook_update(team.id, str(notebook.short_id), notebook.version)+ await collab.apublish_notebook_update(team.id, str(notebook.short_id), notebook.version)return notebookasync def notebook_exists_for_artifact(team: Team, short_id: str) -> bool:- return await Notebook.objects.filter(team=team, short_id=short_id).aexists()---async def _acan_user_edit_notebook(team: Team, user: User, notebook: Notebook) -> bool:- def check() -> bool:- access_control = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))- return bool(access_control.check_access_level_for_object(notebook, "editor"))-- return await sync_to_async(check)()+ return await notebooks.anotebook_exists(team.id, short_id)diff --git a/ee/hogai/tools/create_notebook/test/test_helpers.py b/ee/hogai/tools/create_notebook/test/test_helpers.pyindex 69fcaf39e6b1..7944f77c5eac 100644--- a/ee/hogai/tools/create_notebook/test/test_helpers.py+++ b/ee/hogai/tools/create_notebook/test/test_helpers.py@@ -6,7 +6,7 @@ from parameterized import parameterizedfrom posthog.schema import TrendsQuery, VisualizationMessage-from products.notebooks.backend.markdown_collab import apply_utf16_text_changes, markdown_crc+from products.notebooks.backend.facade.collab import apply_utf16_text_changes, markdown_crcfrom products.notebooks.backend.models import Notebookfrom products.posthog_ai.backend.models.assistant import AgentArtifact, Conversation@@ -178,7 +178,7 @@ class TestSaveNotebookToDb(BaseTest):original_version = notebook.versionoriginal_last_modified_at = notebook.last_modified_at- with patch("ee.hogai.tools.create_notebook.helpers.markdown_collab.apublish_notebook_update") as mock_publish:+ with patch("ee.hogai.tools.create_notebook.helpers.collab.apublish_notebook_update") as mock_publish:async_to_sync(save_notebook_to_db)(team=self.team,user=self.user,@@ -230,7 +230,7 @@ class TestSaveNotebookToDb(BaseTest):)original_version = notebook.version- with patch("ee.hogai.tools.create_notebook.helpers.markdown_collab.apublish_notebook_update") as mock_publish:+ with patch("ee.hogai.tools.create_notebook.helpers.collab.apublish_notebook_update") as mock_publish:async_to_sync(save_notebook_to_db)(team=self.team,user=self.user,diff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.pyindex d39c8467700b..a9e0e9d17951 100644--- a/posthog/api/my_notifications.py+++ b/posthog/api/my_notifications.py@@ -18,7 +18,7 @@ from posthog.models.comment import Commentfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cohorts.backend.models.cohort import Cohortfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.notebooks.backend.models import Notebook+from products.notebooks.backend.facade import api as notebooksfrom products.product_analytics.backend.models.insight import Insight@@ -77,11 +77,7 @@ class MyNotificationsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):created_by=user, team__project_id=self.team.project_id).values_list("id", flat=True))- my_notebooks = list(- Notebook.objects.filter(created_by=user, team__project_id=self.team.project_id).values_list(- "short_id", flat=True- )- )+ my_notebooks = notebooks.get_notebook_short_ids_for_creator(self.team.project_id, user.id)my_comments = list(Comment.objects.filter(created_by=user, team__project_id=self.team.project_id).values_list("id", flat=Truediff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex b53dd000cba1..f93a5687e99b 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -58,9 +58,9 @@ from products.exports.backend.models.exported_asset import (asset_for_token,get_content_response,)-from products.notebooks.backend.api.notebook import NotebookSerializer+from products.notebooks.backend.facade.content import extract_inline_query_nodes, filter_notebook_content_for_sharingfrom products.notebooks.backend.models import Notebook-from products.notebooks.backend.util import extract_inline_query_nodes, filter_notebook_content_for_sharing+from products.notebooks.backend.presentation.views.notebook import NotebookSerializerfrom products.product_analytics.backend.api.insight import InsightSerializerfrom products.product_analytics.backend.models.insight import Insight, InsightViewedfrom products.product_analytics.backend.models.insight_variable import InsightVariablediff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.pyindex bd2925309ce4..b3e4154d3300 100644--- a/posthog/models/sharing_configuration.py+++ b/posthog/models/sharing_configuration.py@@ -282,7 +282,7 @@ class SharingConfiguration(models.Model):elif self.notebook:# Recompute on every call so that edits to the notebook automatically grant/revoke access# to the insights it embeds. Mirrors dashboard semantics.- from products.notebooks.backend.util import extract_referenced_insight_short_ids+ from products.notebooks.backend.facade.content import extract_referenced_insight_short_idsif self.notebook.deleted:return []diff --git a/posthog/temporal/ai/anomaly_investigation/notebook.py b/posthog/temporal/ai/anomaly_investigation/notebook.pyindex 3100f7bfdfab..40fa2237ece3 100644--- a/posthog/temporal/ai/anomaly_investigation/notebook.py+++ b/posthog/temporal/ai/anomaly_investigation/notebook.py@@ -6,7 +6,7 @@ from typing import Anyfrom posthog.temporal.ai.anomaly_investigation.report import InvestigationReportfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration-from products.notebooks.backend.util import (+from products.notebooks.backend.facade.content import (TipTapContent,TipTapNode,create_bullet_list,diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.pyindex 77331555ad23..5208eac543e7 100644--- a/posthog/temporal/ai/anomaly_investigation/workflow.py+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py@@ -33,7 +33,7 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.utils import absolute_urifrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus-from products.notebooks.backend.models import Notebook+from products.notebooks.backend.facade import api as notebookslogger = structlog.get_logger(__name__)@@ -146,14 +146,13 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput))- notebook = await sync_to_async(Notebook.objects.create, thread_sensitive=False)(- team=team,+ notebook = await sync_to_async(notebooks.create_notebook, thread_sensitive=False)(+ team.id,title=f"Investigation — {alert.name or 'anomaly alert'}",content=notebook_content,text_content=result.report.summary,- created_by=user,- last_modified_by=user,- visibility=Notebook.Visibility.DEFAULT,+ created_by_id=user.id,+ last_modified_by_id=user.id,)summary_for_list = _truncate_summary(result.report.summary)diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.pyindex c10128671c03..bdfed1872b10 100644--- a/posthog/test/test_permissions.py+++ b/posthog/test/test_permissions.py@@ -78,7 +78,7 @@ class TestAccessControlPermission(BaseTest):def _create_real_view(self, action="list", pk=None):"""Helper to create a real NotebookViewSet instance"""- from products.notebooks.backend.api.notebook import NotebookViewSet+ from products.notebooks.backend.presentation.views.notebook import NotebookViewSetview = NotebookViewSet()view.action = actiondiff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 26401ba3b080..7e4c507ed99b 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -37,7 +37,15 @@ from products.customer_analytics.backend.logic.usage_spike_notifications import)from products.customer_analytics.backend.models import Account, CustomerJourney, CustomerProfileConfigfrom products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties-from products.notebooks.backend.models import Notebook, ResourceNotebook+from products.notebooks.backend.facade import (+ api as notebooks,+ contracts as notebook_contracts,+)++# ResourceNotebook stays a direct import for the account-list Prefetch only — prefetching the+# account -> ResourceNotebook -> notebook relation can't cross a data facade. All account-notebook+# CRUD goes through `notebooks` (the facade). Tracked by the notebooks legacy-leak interface block.+from products.notebooks.backend.models import ResourceNotebookfrom . import contracts@@ -76,16 +84,10 @@ def _account_tags(account: Account) -> list[str]: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]+ return [+ contracts.AccountNote(title=note.title, short_id=note.short_id)+ for note in notebooks.list_account_internal_notes(account.id)+ ]def get_account_context_data(@@ -972,7 +974,25 @@ def _to_user_basic_info(user: "User | None") -> contracts.UserBasicInfo | None:)-def _to_account_notebook_view(notebook: Notebook) -> contracts.AccountNotebookView:+def _notebook_user_to_basic_info(+ user: "notebook_contracts.NotebookUserInfo | None",+) -> contracts.UserBasicInfo | None:+ if user is None:+ return None+ return contracts.UserBasicInfo(+ id=user.id,+ uuid=user.uuid,+ distinct_id=user.distinct_id,+ first_name=user.first_name,+ last_name=user.last_name,+ email=user.email,+ is_email_verified=user.is_email_verified,+ hedgehog_config=user.hedgehog_config,+ role_at_organization=user.role_at_organization,+ )+++def _to_account_notebook_view(notebook: "notebook_contracts.AccountNotebook") -> contracts.AccountNotebookView:return contracts.AccountNotebookView(id=notebook.id,short_id=notebook.short_id,@@ -980,9 +1000,9 @@ def _to_account_notebook_view(notebook: Notebook) -> contracts.AccountNotebookVicontent=notebook.content,text_content=notebook.text_content,created_at=notebook.created_at,- created_by=_to_user_basic_info(notebook.created_by),+ created_by=_notebook_user_to_basic_info(notebook.created_by),last_modified_at=notebook.last_modified_at,- last_modified_by=_to_user_basic_info(notebook.last_modified_by),+ last_modified_by=_notebook_user_to_basic_info(notebook.last_modified_by),)@@ -1005,16 +1025,7 @@ def list_account_notebooks(parent account isn't accessible (→ 404)."""if get_accessible_account_id(team_id, account_id, user_access_control) is None:return None- notebooks = (- Notebook.objects.filter(- deleted=False,- visibility=Notebook.Visibility.INTERNAL,- resources__account_id=account_id,- )- .select_related("created_by", "last_modified_by")- .order_by("-last_modified_at")- )- return [_to_account_notebook_view(n) for n in notebooks]+ return [_to_account_notebook_view(n) for n in notebooks.list_account_notebooks(account_id)]def get_account_notebook(@@ -1024,16 +1035,7 @@ def get_account_notebook(accessible or no such linked notebook exists (→ 404)."""if get_accessible_account_id(team_id, account_id, user_access_control) is None:return None- notebook = (- Notebook.objects.filter(- deleted=False,- visibility=Notebook.Visibility.INTERNAL,- resources__account_id=account_id,- short_id=short_id,- )- .select_related("created_by", "last_modified_by")- .first()- )+ notebook = notebooks.get_account_notebook(account_id, short_id)return _to_account_notebook_view(notebook) if notebook is not None else None@@ -1051,22 +1053,30 @@ def create_account_notebook((markdown→tiptap) so the ``ee.hogai`` helper stays off the facade import path."""if get_accessible_account_id(team_id, account_id, user_access_control) is None:return None- save_kwargs: dict[str, Any] = {- "team": team,- "created_by": user,- "last_modified_by": user,- "visibility": Notebook.Visibility.INTERNAL,- "title": input.title,- "text_content": input.text_content,- }- if input.synthesized_content is not None:- save_kwargs["content"] = input.synthesized_content- elif input.content is not None:- save_kwargs["content"] = input.content- with transaction.atomic():- notebook = Notebook.objects.create(**save_kwargs)- ResourceNotebook.objects.create(notebook=notebook, account_id=account_id)- return _to_account_notebook_view(notebook)+ content = input.synthesized_content if input.synthesized_content is not None else input.content+ created = notebooks.create_account_notebook(+ team_id,+ account_id,+ title=input.title,+ content=content,+ text_content=input.text_content,+ created_by_id=user.id,+ last_modified_by_id=user.id,+ )+ # The creator is also the (only) modifier of a just-created notebook, so the user the+ # caller already holds is both `created_by` and `last_modified_by` — no extra fetch.+ author = _to_user_basic_info(user)+ return contracts.AccountNotebookView(+ id=created.id,+ short_id=created.short_id,+ title=created.title,+ content=created.content,+ text_content=created.text_content,+ created_at=created.created_at,+ created_by=author,+ last_modified_at=created.last_modified_at,+ last_modified_by=author,+ )def delete_account_notebook(@@ -1076,17 +1086,7 @@ def delete_account_notebook(isn't accessible or no such notebook exists (→ 404)."""if get_accessible_account_id(team_id, account_id, user_access_control) is None:return False- notebook = Notebook.objects.filter(- deleted=False,- visibility=Notebook.Visibility.INTERNAL,- resources__account_id=account_id,- short_id=short_id,- ).first()- if notebook is None:- return False- with transaction.atomic():- notebook.delete()- return True+ return notebooks.delete_account_notebook(account_id, short_id)# --- shared resolution / access helpers for the CRUD paths ---diff --git a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.pyindex 4dd48e94a21e..c17baeaeef55 100644--- a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py+++ b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py@@ -29,7 +29,7 @@ from posthog.models.scoping import team_scopefrom products.customer_analytics.backend.models.account import Account, AccountAssignment, AccountPropertiesfrom products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfig-from products.notebooks.backend.models import Notebook, ResourceNotebook+from products.notebooks.backend.facade import api as notebooksACCOUNT_GROUP_TYPE_INDEX = 0@@ -205,16 +205,15 @@ class Command(BaseCommand):continuefor note_index in range(notes_per_account):title, body = NOTE_TEMPLATES[note_index % len(NOTE_TEMPLATES)]- notebook = Notebook.objects.create(- team=team,+ notebooks.create_account_notebook(+ team.id,+ account.id,title=f"{account.name} — {title}",content=_paragraph_doc(body),text_content=body,- created_by=author,- last_modified_by=author,- visibility=Notebook.Visibility.INTERNAL,+ created_by_id=author.id if author else None,+ last_modified_by_id=author.id if author else None,)- ResourceNotebook.objects.create(notebook=notebook, account=account)created += 1self.stdout.write(f"Created {created} note(s) across up to {len(selected)} account(s).")diff --git a/products/notebooks/backend/api/__init__.py b/products/notebooks/backend/__init__.pysimilarity index 100%rename from products/notebooks/backend/api/__init__.pyrename to products/notebooks/backend/__init__.pydiff --git a/products/notebooks/backend/facade/__init__.py b/products/notebooks/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.pynew file mode 100644index 000000000000..fad32b87607d--- /dev/null+++ b/products/notebooks/backend/facade/api.py@@ -0,0 +1,239 @@+"""+Facade API for notebooks.++This is the ONLY data-capability module other apps are allowed to import. It+accepts ids and primitives, calls domain logic (``logic.py``), and converts ORM+instances into framework-free contracts before returning.++Do NOT implement business logic here (use ``logic.py``), import DRF or HTTP+concerns, or return ORM instances or QuerySets.++Content-tree helpers live in ``facade.content``; collaborative-edit publishing+lives in ``facade.collab``.+"""++from typing import TYPE_CHECKING, Any+from uuid import UUID++from .. import logic+from ..models import Notebook+from . import contracts++if TYPE_CHECKING:+ from posthog.rbac.user_access_control import UserAccessControl+++def _to_notebook_data(notebook: Notebook) -> contracts.NotebookData:+ return contracts.NotebookData(+ id=notebook.id,+ short_id=notebook.short_id,+ title=notebook.title,+ content=notebook.content,+ text_content=notebook.text_content,+ deleted=notebook.deleted,+ visibility=notebook.visibility,+ version=notebook.version,+ created_at=notebook.created_at,+ last_modified_at=notebook.last_modified_at,+ created_by_id=notebook.created_by_id,+ last_modified_by_id=notebook.last_modified_by_id,+ )+++# --- Reads ---+++def notebook_exists(team_id: int, short_id: str, *, include_deleted: bool = True) -> bool:+ return logic.notebook_exists(team_id, short_id, include_deleted=include_deleted)+++async def anotebook_exists(team_id: int, short_id: str, *, include_deleted: bool = True) -> bool:+ return await logic.anotebook_exists(team_id, short_id, include_deleted=include_deleted)+++def get_notebook(team_id: int, short_id: str, *, include_deleted: bool = False) -> contracts.NotebookData | None:+ notebook = logic.get_notebook(team_id, short_id, include_deleted=include_deleted)+ return _to_notebook_data(notebook) if notebook is not None else None+++async def aget_notebook(team_id: int, short_id: str, *, include_deleted: bool = False) -> contracts.NotebookData | None:+ notebook = await logic.aget_notebook(team_id, short_id, include_deleted=include_deleted)+ return _to_notebook_data(notebook) if notebook is not None else None+++def get_notebook_short_ids_for_creator(project_id: int, user_id: int) -> list[str]:+ return logic.get_notebook_short_ids_for_creator(project_id, user_id)+++def get_notebook_activity_summary(team_id: int, limit: int) -> contracts.NotebookActivitySummary:+ total, recent = logic.get_notebook_activity_summary(team_id, limit)+ return contracts.NotebookActivitySummary(+ total_count=total,+ recent=[+ contracts.NotebookRecent(+ short_id=row["short_id"],+ title=row["title"],+ last_modified_at=row["last_modified_at"],+ )+ for row in recent+ ],+ )+++# --- Access control ---+++async def acan_user_edit_notebook(team_id: int, short_id: str, *, user_access_control: "UserAccessControl") -> bool:+ return await logic.acan_user_edit_notebook(team_id, short_id, user_access_control)+++# --- Writes ---+++async def aupdate_notebook_content(+ team_id: int,+ short_id: str,+ *,+ content: dict[str, Any],+ title: str,+ text_content: str | None,+ last_modified_by_id: int | None,+) -> contracts.NotebookData | None:+ notebook = await logic.aupdate_notebook_content(+ team_id,+ short_id,+ content=content,+ title=title,+ text_content=text_content,+ last_modified_by_id=last_modified_by_id,+ )+ return _to_notebook_data(notebook) if notebook is not None else None+++async def aupsert_notebook(+ team_id: int,+ short_id: str,+ *,+ created_by_id: int | None,+ last_modified_by_id: int | None,+ title: str,+ content: dict[str, Any],+) -> tuple[contracts.NotebookData, bool]:+ notebook, created = await logic.aupsert_notebook(+ team_id,+ short_id,+ created_by_id=created_by_id,+ last_modified_by_id=last_modified_by_id,+ title=title,+ content=content,+ )+ return _to_notebook_data(notebook), created+++def create_notebook(+ team_id: int,+ *,+ title: str | None,+ content: Any,+ text_content: str | None = None,+ created_by_id: int | None = None,+ last_modified_by_id: int | None = None,+ visibility: str = Notebook.Visibility.DEFAULT,+) -> contracts.NotebookData:+ notebook = logic.create_notebook(+ team_id,+ title=title,+ content=content,+ text_content=text_content,+ created_by_id=created_by_id,+ last_modified_by_id=last_modified_by_id,+ visibility=visibility,+ )+ return _to_notebook_data(notebook)+++# --- Resource links (groups, accounts) ---+++def get_group_notebook_short_id(group_id: int) -> str | None:+ return logic.get_group_notebook_short_id(group_id)+++def group_has_notebook(group_id: int) -> bool:+ return logic.group_has_notebook(group_id)+++def create_group_notebook(team_id: int, group_id: int, *, title: str | None, content: Any) -> contracts.NotebookData:+ return _to_notebook_data(logic.create_group_notebook(team_id, group_id, title=title, content=content))+++def create_account_notebook(+ team_id: int,+ account_id: str | UUID,+ *,+ title: str | None,+ content: Any,+ text_content: str | None = None,+ created_by_id: int | None = None,+ last_modified_by_id: int | None = None,+) -> contracts.NotebookData:+ notebook = logic.create_account_notebook(+ team_id,+ account_id,+ title=title,+ content=content,+ text_content=text_content,+ created_by_id=created_by_id,+ last_modified_by_id=last_modified_by_id,+ )+ return _to_notebook_data(notebook)+++def list_account_internal_notes(account_id: str | UUID) -> list[contracts.AccountNote]:+ return [+ contracts.AccountNote(title=link.notebook.title, short_id=link.notebook.short_id)+ for link in logic.list_account_internal_notes(account_id)+ ]+++def _to_notebook_user(user) -> contracts.NotebookUserInfo | None:+ if user is None:+ return None+ return contracts.NotebookUserInfo(+ id=user.id,+ uuid=user.uuid,+ distinct_id=user.distinct_id,+ first_name=user.first_name,+ last_name=user.last_name,+ email=user.email,+ is_email_verified=user.is_email_verified,+ hedgehog_config=user.hedgehog_config,+ role_at_organization=user.role_at_organization,+ )+++def _to_account_notebook(notebook: Notebook) -> contracts.AccountNotebook:+ return contracts.AccountNotebook(+ id=notebook.id,+ short_id=notebook.short_id,+ title=notebook.title,+ content=notebook.content,+ text_content=notebook.text_content,+ created_at=notebook.created_at,+ last_modified_at=notebook.last_modified_at,+ created_by=_to_notebook_user(notebook.created_by),+ last_modified_by=_to_notebook_user(notebook.last_modified_by),+ )+++def list_account_notebooks(account_id: str | UUID) -> list[contracts.AccountNotebook]:+ return [_to_account_notebook(notebook) for notebook in logic.list_account_notebooks(account_id)]+++def get_account_notebook(account_id: str | UUID, short_id: str) -> contracts.AccountNotebook | None:+ notebook = logic.get_account_notebook(account_id, short_id)+ return _to_account_notebook(notebook) if notebook is not None else None+++def delete_account_notebook(account_id: str | UUID, short_id: str) -> bool:+ return logic.delete_account_notebook(account_id, short_id)diff --git a/products/notebooks/backend/facade/collab.py b/products/notebooks/backend/facade/collab.pynew file mode 100644index 000000000000..70ebb77ec760--- /dev/null+++ b/products/notebooks/backend/facade/collab.py@@ -0,0 +1,16 @@+"""+Facade re-exports for collaborative-edit publishing.++Callers that persist notebook edits outside the notebooks views (e.g. agent+tooling) publish the resulting update to the collab stream through these+re-exports rather than importing ``backend.markdown_collab`` directly.+"""++from ..markdown_collab import (+ MarkdownDiff as MarkdownDiff,+ apply_utf16_text_changes as apply_utf16_text_changes,+ apublish_notebook_update as apublish_notebook_update,+ build_markdown_update_diff as build_markdown_update_diff,+ markdown_crc as markdown_crc,+ publish_notebook_update as publish_notebook_update,+)diff --git a/products/notebooks/backend/facade/content.py b/products/notebooks/backend/facade/content.pynew file mode 100644index 000000000000..c68b9b2afe2b--- /dev/null+++ b/products/notebooks/backend/facade/content.py@@ -0,0 +1,27 @@+"""+Facade re-exports for notebook content-tree helpers.++These functions operate on plain ProseMirror/TipTap dicts — no Django, no ORM —+so cross-product callers that build or sanitize notebook content import them from+here rather than reaching into ``backend.util``.+"""++from ..util import (+ QUERY_NODE_TYPE as QUERY_NODE_TYPE,+ SAVED_INSIGHT_NODE_KIND as SAVED_INSIGHT_NODE_KIND,+ SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES as SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES,+ TipTapContent as TipTapContent,+ TipTapNode as TipTapNode,+ create_bullet_list as create_bullet_list,+ create_empty_paragraph as create_empty_paragraph,+ create_heading_with_text as create_heading_with_text,+ create_paragraph_with_content as create_paragraph_with_content,+ create_paragraph_with_text as create_paragraph_with_text,+ create_task_list as create_task_list,+ create_text_content as create_text_content,+ extract_inline_query_nodes as extract_inline_query_nodes,+ extract_referenced_insight_short_ids as extract_referenced_insight_short_ids,+ filter_notebook_content_for_sharing as filter_notebook_content_for_sharing,+ iter_prosemirror_nodes as iter_prosemirror_nodes,+ sanitize_text_content as sanitize_text_content,+)diff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.pynew file mode 100644index 000000000000..f81bb19da404--- /dev/null+++ b/products/notebooks/backend/facade/contracts.py@@ -0,0 +1,98 @@+"""+Contract types for notebooks.++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, same ``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 further down the call stack.+"""++from dataclasses import field+from datetime import datetime+from typing import Any+from uuid import UUID++from pydantic.dataclasses import dataclass+++@dataclass(frozen=True)+class NotebookData:+ """A notebook's persisted state, as other products read it."""++ id: UUID+ short_id: str+ title: str | None+ # ProseMirror/TipTap content: usually a `{type: "doc", content: [...]}` dict, but some+ # notebooks (e.g. group/account templates) persist a bare list of nodes. JSONField allows+ # either, so the contract must too.+ content: dict[str, Any] | list[Any] | None+ text_content: str | None+ deleted: bool+ visibility: str+ version: int+ created_at: datetime+ last_modified_at: datetime+ created_by_id: int | None = None+ last_modified_by_id: int | None = None+++@dataclass(frozen=True)+class NotebookRecent:+ """A single entry in a team's recently-modified notebooks list."""++ short_id: str+ title: str | None+ last_modified_at: datetime | None+++@dataclass(frozen=True)+class NotebookActivitySummary:+ """Aggregate notebook activity for a team — total count plus the most recent few."""++ total_count: int+ recent: list[NotebookRecent] = field(default_factory=list)+++@dataclass(frozen=True)+class AccountNote:+ """An internal notebook linked to a customer-analytics account, for context rendering."""++ title: str | None+ short_id: str+++@dataclass(frozen=True)+class NotebookUserInfo:+ """The creator/modifier of a notebook — raw user values, mirroring UserBasicSerializer's input."""++ id: int+ uuid: UUID+ distinct_id: str | None+ first_name: str+ last_name: str+ email: str+ is_email_verified: bool | None+ hedgehog_config: Any+ role_at_organization: str | None+++@dataclass(frozen=True)+class AccountNotebook:+ """A full internal notebook linked to an account, with creator/modifier info.++ The richer counterpart to :class:`AccountNote` — backs the account-notebooks CRUD+ endpoints, where consumers render who created/edited each notebook.+ """++ id: UUID+ short_id: str+ title: str | None+ content: dict[str, Any] | list[Any] | None+ text_content: str | None+ created_at: datetime+ last_modified_at: datetime+ created_by: NotebookUserInfo | None = None+ last_modified_by: NotebookUserInfo | None = Nonediff --git a/products/notebooks/backend/logic.py b/products/notebooks/backend/logic.pynew file mode 100644index 000000000000..27feab0f0926--- /dev/null+++ b/products/notebooks/backend/logic.py@@ -0,0 +1,221 @@+"""+Domain logic for notebooks.++Owns ORM access and business rules. Returns ORM instances and primitives to the+facade, which maps them to framework-free contracts. Nothing outside the product+should import this module — cross-product callers go through ``facade.api``.+"""++from typing import Any+from uuid import UUID++from django.db import transaction+from django.db.models import F+from django.utils import timezone++from asgiref.sync import sync_to_async++from posthog.rbac.user_access_control import UserAccessControl++from .models import Notebook, ResourceNotebook+++def _base_queryset(team_id: int, *, include_deleted: bool = False) -> Any:+ qs = Notebook.objects.filter(team_id=team_id)+ if not include_deleted:+ qs = qs.filter(deleted=False)+ return qs+++def notebook_exists(team_id: int, short_id: str, *, include_deleted: bool = True) -> bool:+ return _base_queryset(team_id, include_deleted=include_deleted).filter(short_id=short_id).exists()+++async def anotebook_exists(team_id: int, short_id: str, *, include_deleted: bool = True) -> bool:+ return await _base_queryset(team_id, include_deleted=include_deleted).filter(short_id=short_id).aexists()+++def get_notebook(team_id: int, short_id: str, *, include_deleted: bool = False) -> Notebook | None:+ return _base_queryset(team_id, include_deleted=include_deleted).filter(short_id=short_id).first()+++async def aget_notebook(team_id: int, short_id: str, *, include_deleted: bool = False) -> Notebook | None:+ return await _base_queryset(team_id, include_deleted=include_deleted).filter(short_id=short_id).afirst()+++async def acan_user_edit_notebook(team_id: int, short_id: str, user_access_control: UserAccessControl) -> bool:+ notebook = await aget_notebook(team_id, short_id, include_deleted=True)+ if notebook is None:+ return False++ def check() -> bool:+ return bool(user_access_control.check_access_level_for_object(notebook, "editor"))++ return await sync_to_async(check)()+++async def aupdate_notebook_content(+ team_id: int,+ short_id: str,+ *,+ content: dict[str, Any],+ title: str,+ text_content: str | None,+ last_modified_by_id: int | None,+) -> Notebook | None:+ notebook = await aget_notebook(team_id, short_id, include_deleted=True)+ if notebook is None:+ return None+ await Notebook.objects.filter(pk=notebook.pk).aupdate(+ content=content,+ title=title,+ text_content=text_content,+ version=F("version") + 1,+ last_modified_by_id=last_modified_by_id,+ last_modified_at=timezone.now(),+ )+ await notebook.arefresh_from_db()+ return notebook+++async def aupsert_notebook(+ team_id: int,+ short_id: str,+ *,+ created_by_id: int | None,+ last_modified_by_id: int | None,+ title: str,+ content: dict[str, Any],+) -> tuple[Notebook, bool]:+ notebook, created = await Notebook.objects.aget_or_create(+ team_id=team_id,+ short_id=short_id,+ defaults={+ "created_by_id": created_by_id,+ "last_modified_by_id": last_modified_by_id,+ "title": title,+ "content": content,+ },+ )+ if not created:+ notebook.content = content+ notebook.title = title+ notebook.version += 1+ notebook.last_modified_by_id = last_modified_by_id+ await notebook.asave(update_fields=["content", "title", "version", "last_modified_by", "last_modified_at"])+ return notebook, created+++def get_notebook_short_ids_for_creator(project_id: int, user_id: int) -> list[str]:+ return list(+ Notebook.objects.filter(created_by_id=user_id, team__project_id=project_id).values_list("short_id", flat=True)+ )+++def get_notebook_activity_summary(team_id: int, limit: int) -> tuple[int, list[dict[str, Any]]]:+ qs = Notebook.objects.filter(team_id=team_id, deleted=False)+ total = qs.count()+ recent = list(qs.order_by("-last_modified_at")[:limit].values("short_id", "title", "last_modified_at"))+ return total, recent+++def create_notebook(+ team_id: int,+ *,+ title: str | None,+ content: Any,+ text_content: str | None = None,+ created_by_id: int | None = None,+ last_modified_by_id: int | None = None,+ visibility: str = Notebook.Visibility.DEFAULT,+) -> Notebook:+ return Notebook.objects.create(+ team_id=team_id,+ title=title,+ content=content,+ text_content=text_content,+ created_by_id=created_by_id,+ last_modified_by_id=last_modified_by_id,+ visibility=visibility,+ )+++def get_group_notebook_short_id(group_id: int) -> str | None:+ link = ResourceNotebook.objects.filter(group=group_id).select_related("notebook").first()+ return link.notebook.short_id if link else None+++def group_has_notebook(group_id: int) -> bool:+ return ResourceNotebook.objects.filter(group=group_id).exists()+++def create_group_notebook(team_id: int, group_id: int, *, title: str | None, content: Any) -> Notebook:+ with transaction.atomic():+ notebook = Notebook.objects.create(+ team_id=team_id,+ title=title,+ content=content,+ visibility=Notebook.Visibility.INTERNAL,+ )+ ResourceNotebook.objects.create(notebook=notebook, group=group_id)+ return notebook+++def create_account_notebook(+ team_id: int,+ account_id: str | UUID,+ *,+ title: str | None,+ content: Any,+ text_content: str | None = None,+ created_by_id: int | None = None,+ last_modified_by_id: int | None = None,+) -> Notebook:+ with transaction.atomic():+ notebook = Notebook.objects.create(+ team_id=team_id,+ title=title,+ content=content,+ text_content=text_content,+ created_by_id=created_by_id,+ last_modified_by_id=last_modified_by_id,+ visibility=Notebook.Visibility.INTERNAL,+ )+ ResourceNotebook.objects.create(notebook=notebook, account_id=account_id)+ return notebook+++def list_account_internal_notes(account_id: str | UUID) -> list[ResourceNotebook]:+ return list(+ ResourceNotebook.objects.filter(+ account_id=account_id,+ notebook__deleted=False,+ notebook__visibility=Notebook.Visibility.INTERNAL,+ )+ .select_related("notebook")+ .order_by("-notebook__last_modified_at")+ )+++def _account_notebook_queryset(account_id: str | UUID) -> Any:+ return Notebook.objects.filter(+ deleted=False,+ visibility=Notebook.Visibility.INTERNAL,+ resources__account_id=account_id,+ ).select_related("created_by", "last_modified_by")+++def list_account_notebooks(account_id: str | UUID) -> list[Notebook]:+ return list(_account_notebook_queryset(account_id).order_by("-last_modified_at"))+++def get_account_notebook(account_id: str | UUID, short_id: str) -> Notebook | None:+ return _account_notebook_queryset(account_id).filter(short_id=short_id).first()+++def delete_account_notebook(account_id: str | UUID, short_id: str) -> bool:+ notebook = _account_notebook_queryset(account_id).filter(short_id=short_id).first()+ if notebook is None:+ return False+ notebook.delete()+ return Truediff --git a/products/notebooks/backend/presentation/__init__.py b/products/notebooks/backend/presentation/__init__.pynew file mode 100644index 000000000000..7e8f5b00c677--- /dev/null+++ b/products/notebooks/backend/presentation/__init__.py@@ -0,0 +1 @@+"""HTTP presentation layer of the notebooks product (DRF viewsets and serializers)."""diff --git a/products/notebooks/backend/presentation/views/__init__.py b/products/notebooks/backend/presentation/views/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/notebooks/backend/api/notebook.py b/products/notebooks/backend/presentation/views/notebook.pysimilarity index 100%rename from products/notebooks/backend/api/notebook.pyrename to products/notebooks/backend/presentation/views/notebook.pydiff --git a/products/notebooks/backend/routes.py b/products/notebooks/backend/routes.pyindex ebf868ca22a4..b764c3554ff6 100644--- a/products/notebooks/backend/routes.py+++ b/products/notebooks/backend/routes.py@@ -1,7 +1,7 @@from posthog.api import sharingfrom posthog.api.routing import RouterRegistry-from products.notebooks.backend.api.notebook import NotebookViewSet+from products.notebooks.backend.presentation.views.notebook import NotebookViewSetdef register_routes(routers: RouterRegistry) -> None:diff --git a/products/notebooks/backend/test/test_collab_api.py b/products/notebooks/backend/test/test_collab_api.pyindex b29e85a12ebb..114e3a0b365e 100644--- a/products/notebooks/backend/test/test_collab_api.py+++ b/products/notebooks/backend/test/test_collab_api.py@@ -183,7 +183,7 @@ class TestNotebookCollabSaveAPI(APIBaseTest):)assert response.status_code == status.HTTP_400_BAD_REQUEST- @patch("products.notebooks.backend.api.notebook.submit_steps")+ @patch("products.notebooks.backend.presentation.views.notebook.submit_steps")def test_collab_save_returns_410_when_steps_expired(self, mock_submit):notebook = self._create_notebook(SAMPLE_DOC)@@ -236,7 +236,7 @@ class TestNotebookCollabSaveAPI(APIBaseTest):def test_collab_save_rejected_stale_logs_attempted_content(self):notebook = self._create_notebook(SAMPLE_DOC)- with patch("products.notebooks.backend.api.notebook.submit_steps") as mock_submit:+ with patch("products.notebooks.backend.presentation.views.notebook.submit_steps") as mock_submit:mock_submit.return_value = SubmitResult(status="stale", version=5, steps_since=None)self._collab_save(notebook,@@ -395,7 +395,10 @@ class TestNotebookCollabStreamAPI(APIBaseTest):assert "event: step" not in bodyassert ": keepalive" in body- @patch("products.notebooks.backend.api.notebook.transaction.on_commit", side_effect=lambda callback: callback())+ @patch(+ "products.notebooks.backend.presentation.views.notebook.transaction.on_commit",+ side_effect=lambda callback: callback(),+ )def test_stream_delivers_update_event_after_full_doc_patch(self, _mock_on_commit):notebook = self._create_notebook()response = self.client.patch(@@ -653,7 +656,10 @@ class TestNotebookMarkdownSaveAPI(APIBaseTest):assert nb.version == version + 1assert nb.content == _markdown_doc("base text plus A")- @patch("products.notebooks.backend.api.notebook.transaction.on_commit", side_effect=lambda callback: callback())+ @patch(+ "products.notebooks.backend.presentation.views.notebook.transaction.on_commit",+ side_effect=lambda callback: callback(),+ )def test_markdown_save_conflict_replays_legacy_patch_diff(self, _mock_on_commit):from products.notebooks.backend.markdown_collab import apply_utf16_text_changesdiff --git a/products/notebooks/backend/test/test_facade.py b/products/notebooks/backend/test/test_facade.pynew file mode 100644index 000000000000..258677b42a73--- /dev/null+++ b/products/notebooks/backend/test/test_facade.py@@ -0,0 +1,200 @@+import pytest+from posthog.test.base import BaseTest++from django.apps import apps++from posthog.rbac.user_access_control import UserAccessControl++from products.notebooks.backend import logic+from products.notebooks.backend.facade import api, content+from products.notebooks.backend.models import Notebook, ResourceNotebook+++def _create_account(team):+ # apps.get_model avoids a notebooks -> customer_analytics import edge (the FK is a string ref).+ Account = apps.get_model("customer_analytics", "Account")+ return Account.objects.unscoped().create(team=team, name="Acme")+++class TestNotebooksFacade(BaseTest):+ def _doc(self, text: str = "hello") -> dict:+ return {"type": "doc", "content": [content.create_paragraph_with_text(text)]}++ def test_create_notebook_returns_contract(self):+ data = api.create_notebook(+ self.team.id,+ title="My notebook",+ content=self._doc(),+ created_by_id=self.user.id,+ last_modified_by_id=self.user.id,+ )+ self.assertEqual(data.title, "My notebook")+ self.assertEqual(data.visibility, Notebook.Visibility.DEFAULT)+ self.assertEqual(data.created_by_id, self.user.id)+ stored = Notebook.objects.get(id=data.id)+ self.assertEqual(stored.team_id, self.team.id)+ self.assertFalse(stored.deleted)++ def test_get_notebook_round_trips_fields(self):+ notebook = Notebook.objects.create(team=self.team, title="T", content=self._doc("body"), text_content="body")+ data = api.get_notebook(self.team.id, notebook.short_id)+ assert data is not None+ self.assertEqual(data.short_id, notebook.short_id)+ self.assertEqual(data.title, "T")+ self.assertEqual(data.text_content, "body")+ self.assertEqual(data.content, self._doc("body"))++ def test_get_notebook_excludes_deleted_by_default(self):+ notebook = Notebook.objects.create(team=self.team, title="gone", deleted=True)+ self.assertIsNone(api.get_notebook(self.team.id, notebook.short_id))+ self.assertIsNotNone(api.get_notebook(self.team.id, notebook.short_id, include_deleted=True))++ def test_notebook_exists_is_team_scoped(self):+ from posthog.models import Team++ notebook = Notebook.objects.create(team=self.team, title="t")+ other_team = Team.objects.create(organization=self.organization, name="other")+ self.assertTrue(api.notebook_exists(self.team.id, notebook.short_id))+ self.assertFalse(api.notebook_exists(other_team.id, notebook.short_id))++ def test_get_notebook_short_ids_for_creator(self):+ mine = Notebook.objects.create(team=self.team, title="mine", created_by=self.user)+ Notebook.objects.create(team=self.team, title="theirs")+ short_ids = api.get_notebook_short_ids_for_creator(self.team.project_id, self.user.id)+ self.assertEqual(short_ids, [mine.short_id])++ def test_activity_summary_orders_by_recency(self):+ Notebook.objects.create(team=self.team, title="old")+ newer = Notebook.objects.create(team=self.team, title="new")+ summary = api.get_notebook_activity_summary(self.team.id, limit=1)+ self.assertEqual(summary.total_count, 2)+ self.assertEqual(len(summary.recent), 1)+ self.assertEqual(summary.recent[0].short_id, newer.short_id)++ def test_create_group_notebook_links_internal_notebook(self):+ data = api.create_group_notebook(self.team.id, group_id=42, title="Notes", content=self._doc())+ self.assertEqual(data.visibility, Notebook.Visibility.INTERNAL)+ self.assertTrue(api.group_has_notebook(42))+ self.assertEqual(api.get_group_notebook_short_id(42), data.short_id)+ self.assertFalse(api.group_has_notebook(43))++ def test_create_account_notebook_and_list_notes(self):+ account = _create_account(self.team)+ data = api.create_account_notebook(+ self.team.id, account.id, title="Recap", content=self._doc(), created_by_id=self.user.id+ )+ self.assertEqual(data.visibility, Notebook.Visibility.INTERNAL)+ self.assertTrue(ResourceNotebook.objects.filter(account=account, notebook_id=data.id).exists())+ notes = api.list_account_internal_notes(account.id)+ self.assertEqual([n.short_id for n in notes], [data.short_id])+ self.assertEqual(notes[0].title, "Recap")++ def test_list_account_notes_excludes_deleted_and_non_internal(self):+ account = _create_account(self.team)+ deleted = Notebook.objects.create(+ team=self.team, title="d", deleted=True, visibility=Notebook.Visibility.INTERNAL+ )+ external = Notebook.objects.create(team=self.team, title="e", visibility=Notebook.Visibility.DEFAULT)+ ResourceNotebook.objects.create(notebook=deleted, account=account)+ ResourceNotebook.objects.create(notebook=external, account=account)+ self.assertEqual(api.list_account_internal_notes(account.id), [])++ def test_account_notebook_crud_surface(self):+ account = _create_account(self.team)+ created = api.create_account_notebook(+ self.team.id, str(account.id), title="Q3", content=self._doc(), created_by_id=self.user.id+ )++ listed = api.list_account_notebooks(str(account.id))+ self.assertEqual([n.short_id for n in listed], [created.short_id])+ self.assertEqual(listed[0].title, "Q3")+ assert listed[0].created_by is not None+ self.assertEqual(listed[0].created_by.id, self.user.id)+ self.assertEqual(listed[0].created_by.email, self.user.email)++ fetched = api.get_account_notebook(str(account.id), created.short_id)+ assert fetched is not None+ self.assertEqual(fetched.short_id, created.short_id)++ self.assertTrue(api.delete_account_notebook(str(account.id), created.short_id))+ self.assertIsNone(api.get_account_notebook(str(account.id), created.short_id))+ self.assertFalse(api.delete_account_notebook(str(account.id), "missing"))++ def test_get_account_notebook_excludes_non_internal(self):+ account = _create_account(self.team)+ external = Notebook.objects.create(team=self.team, title="e", visibility=Notebook.Visibility.DEFAULT)+ ResourceNotebook.objects.create(notebook=external, account=account)+ self.assertEqual(api.list_account_notebooks(str(account.id)), [])+ self.assertIsNone(api.get_account_notebook(str(account.id), external.short_id))+++class TestNotebooksFacadeAsync(BaseTest):+ def _doc(self, text: str = "hi") -> dict:+ return {"type": "doc", "content": [content.create_paragraph_with_text(text)]}++ @pytest.mark.asyncio+ async def test_anotebook_exists_and_aget(self):+ notebook = await Notebook.objects.acreate(team=self.team, title="async", content=self._doc())+ self.assertTrue(await api.anotebook_exists(self.team.id, notebook.short_id))+ data = await api.aget_notebook(self.team.id, notebook.short_id)+ assert data is not None+ self.assertEqual(data.short_id, notebook.short_id)++ @pytest.mark.asyncio+ async def test_aupsert_creates_then_overwrites_and_bumps_version(self):+ data, created = await api.aupsert_notebook(+ self.team.id,+ "abc123",+ created_by_id=self.user.id,+ last_modified_by_id=self.user.id,+ title="first",+ content=self._doc("first"),+ )+ self.assertTrue(created)+ self.assertEqual(data.version, 0)++ data2, created2 = await api.aupsert_notebook(+ self.team.id,+ "abc123",+ created_by_id=self.user.id,+ last_modified_by_id=self.user.id,+ title="second",+ content=self._doc("second"),+ )+ self.assertFalse(created2)+ self.assertEqual(data2.id, data.id)+ self.assertEqual(data2.title, "second")+ self.assertEqual(data2.version, 1)++ @pytest.mark.asyncio+ async def test_aupdate_notebook_content_bumps_version(self):+ notebook = await Notebook.objects.acreate(team=self.team, short_id="upd123", title="t", content=self._doc())+ data = await api.aupdate_notebook_content(+ self.team.id,+ "upd123",+ content=self._doc("updated"),+ title="t2",+ text_content="updated",+ last_modified_by_id=self.user.id,+ )+ assert data is not None+ self.assertEqual(data.title, "t2")+ self.assertEqual(data.text_content, "updated")+ self.assertEqual(data.version, notebook.version + 1)++ @pytest.mark.asyncio+ async def test_acan_user_edit_notebook_creator(self):+ notebook = await Notebook.objects.acreate(team=self.team, title="t", created_by=self.user)+ uac = UserAccessControl(user=self.user, team=self.team)+ self.assertTrue(await api.acan_user_edit_notebook(self.team.id, notebook.short_id, user_access_control=uac))++ @pytest.mark.asyncio+ async def test_acan_user_edit_missing_notebook(self):+ uac = UserAccessControl(user=self.user, team=self.team)+ self.assertFalse(await api.acan_user_edit_notebook(self.team.id, "missing", user_access_control=uac))+++def test_logic_is_internal_only():+ """The facade is the public surface; logic stays an implementation detail."""+ assert hasattr(logic, "create_notebook")+ assert hasattr(api, "create_notebook")diff --git a/products/notebooks/backend/test/test_notebook_api_serializers.py b/products/notebooks/backend/test/test_notebook_api_serializers.pyindex a097948d54fc..2a7b27684a19 100644--- a/products/notebooks/backend/test/test_notebook_api_serializers.py+++ b/products/notebooks/backend/test/test_notebook_api_serializers.py@@ -1,6 +1,6 @@import pytest-from products.notebooks.backend.api.notebook import NotebookCollabSaveSerializer+from products.notebooks.backend.presentation.views.notebook import NotebookCollabSaveSerializer@pytest.mark.parametrize(diff --git a/products/notebooks/tsconfig.json b/products/notebooks/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/notebooks/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.pyindex dca6b1040f40..21e9d5e3f497 100644--- a/products/signals/backend/scout_harness/profile/builders.py+++ b/products/signals/backend/scout_harness/profile/builders.py@@ -56,7 +56,7 @@ from products.dashboards.backend.models.dashboard import Dashboard# enforced, migrate this to a facade `list_recent_experiments(team, limit)` helper.from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.notebooks.backend.models import Notebook+from products.notebooks.backend.facade import api as notebooksfrom products.signals.backend.models import SignalReport, SignalSourceConfigfrom products.signals.backend.scout_harness.profile.schema import Inventoryfrom products.surveys.backend.models import Survey@@ -501,18 +501,16 @@ def _recent_notebooks(team: Team) -> dict[str, Any]:scope (405 edits in 14d), so this section is high-signal even at small recent-list size."""- qs = Notebook.objects.filter(team=team, deleted=False)- total = qs.count()- recent = qs.order_by("-last_modified_at")[:RECENT_ENTITY_LIMIT].values("short_id", "title", "last_modified_at")+ summary = notebooks.get_notebook_activity_summary(team.id, RECENT_ENTITY_LIMIT)return {- "total_count": total,+ "total_count": summary.total_count,"recent": [{- "short_id": row["short_id"],- "title": (row["title"] or "").strip(),- "last_modified_at": row["last_modified_at"].isoformat() if row["last_modified_at"] else None,+ "short_id": entry.short_id,+ "title": (entry.title or "").strip(),+ "last_modified_at": entry.last_modified_at.isoformat() if entry.last_modified_at else None,}- for row in recent+ for entry in summary.recent],}diff --git a/pyproject.toml b/pyproject.tomlindex c2f6f9fbd5c0..28ee2bbb7bd1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -557,6 +557,19 @@ 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: notebooks presentation wave — the moved NotebookViewSet still reaches in-product+ # internals (collab, kernel runtime, query validation, models) and the tasks sandbox+ # directly. Thin it to parse -> facade -> serialize and delete each entry.+ # backend:contract-check stays off until this list is empty.+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.activity_logging",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.collab",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.collab_stream",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.kernel_runtime",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.markdown_collab",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.models",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.presence",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.python_analysis",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.query_validation",][tool.ty.rules]diff --git a/tach.toml b/tach.tomlindex 1050a5e91d6a..69f2a498b195 100644--- a/tach.toml+++ b/tach.toml@@ -696,7 +696,7 @@ expose = ["backend\\.routes.*",]from = [- "products\\.(customer_analytics|error_tracking|experiments|mcp_analytics|mcp_store|metrics|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review)",+ "products\\.(customer_analytics|error_tracking|experiments|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review)",]# TODO: Experiments-specific temporary interface@@ -858,6 +858,21 @@ from = ["products.access_control",]+# Legacy leaks — core (posthog/ee), customer_analytics, reminders and signals still+# import the Notebook ORM directly: file-system / search / reminders registries dispatch+# on the model class, middleware returns a raw queryset, the read_data and notebook-context+# Max tools need the instance for access-control checks, sharing re-fetches it for the+# shared-export serializer, and customer_analytics owns a CRUD-over-Notebook surface that+# moves in its own presentation wave. Shrinks as those migrate behind the facade; keeps+# backend:contract-check off until empty.+[[interfaces]]+expose = [+ "backend\\.models.*",+]+from = [+ "products.notebooks",+]+[[modules]]path = "products.business_knowledge"depends_on = ["posthog", "ee"]