:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): drop legacy account role properties (#76700)
Arthur Moreira de Deusd14f93fb3ff0
diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.mdindex 2aa5908fe1ba..5b99f5ce6227 100644--- a/products/customer_analytics/backend/COMPROMISES.md+++ b/products/customer_analytics/backend/COMPROMISES.md@@ -47,32 +47,17 @@ Shortcuts taken to ship the first version. Revisit when they bite.- **v2 materialization only.** v1 `run_workflow.py` is frozen and does not dispatch the sync; v1teams get it after migrating to v2.-## Account relationships — transitional JSON forward-sync--The relationship tables (`AccountRelationshipDefinition` + `AccountRelationship`) exist, but the-legacy JSON role keys (`csm`, `account_executive`, `account_owner`) in `Account._properties` are-still the **source of truth** for account roles. Every JSON role write forward-syncs into the-table via `logic/relationships.sync_from_account_properties` (called from `create_account_for_view`,-`update_account_for_view`, `_apply_external_role_assignments`, and the Max upsert tool), so the-table shadows the JSON and accrues assignment history. Rules while the sync is alive:--- **Nothing may write the relationship table directly** — the next JSON write reconciles direct- table writes away. That's why the facade deliberately exposes no assign/end functions yet.-- The three seeded definitions are matched **by name** (`SEEDED_DEFINITIONS` maps JSON key →- definition name). Renaming a seeded definition silently unlinks it from its JSON key.-- Definitions are not auto-created; on teams without them the sync is a silent no-op. They're- created ad-hoc (or by the future definitions UI).--Cutover checklist — when done, the sync and this section are deleted:--- [ ] Relationship read path in HogQL/query runner replaces the JSON `ExpressionField`s (PR 2)-- [ ] Writers route through `logic/relationships.assign`/`end` instead of JSON keys, facade grows- assign/end functions (PR 3)-- [ ] Ad-hoc backfill run per environment (create seeded definitions, sync existing accounts)-- [ ] JSON readers migrated (Max context, usage-spike notifications, external API shape, CDP- "update account" template, Workflows result paths)-- [ ] Delete `sync_from_account_properties` + call sites; strip the three role keys from- `AccountProperties`+## Account relationships — leftover JSON role keys in stored rows++The relationship tables are the only source of truth for account roles; the JSON role keys+(`csm`, `account_executive`, `account_owner`) are gone from `AccountProperties`.+Stored `Account._properties` rows may still carry them until+`manage.py backfill_account_relationships` has run in the environment+(it assigns any not-yet-migrated JSON holders as relationships, then strips the keys).+Until then `Account.properties` silently ignores unknown stored keys, and the raw keys remain+visible through the HogQL `system.accounts.properties` JSON column.+Delete this section (and the getter's key filter can revert to a plain `model_validate`)+once the command has run everywhere.## External account `custom_properties` payload@@ -154,11 +139,10 @@ Cutover checklist — when done, the sync and this section are deleted:## Tech debt-- **Account property writes have no single choke point.** `Account._properties` is mutated from four- independent paths: `create_account_for_view` / `update_account_for_view` (via the manager),- `_apply_external_role_assignments` (raw `account.save`, bypassing the manager), and the Max tool's- `_create_account` / `_update_account`. Anything that must happen on every properties write — like the- transitional relationship forward-sync — has to be repeated per call site, and a new writer can- silently forget it. Funneling every properties write through `AccountManager` (and hooking- cross-cutting behavior there) is the fix if account properties grow more derived behavior; not done- now because the sync call sites are deleted at relationship cutover anyway.+- **Account property writes have no single choke point.** `Account._properties` is mutated from+ independent paths: `create_account_for_view` / `update_account_for_view` (via the manager)+ and the Max tool's `_create_account` / `_update_account`.+ Anything that must happen on every properties write has to be repeated per call site,+ and a new writer can silently forget it.+ Funneling every properties write through `AccountManager` (and hooking cross-cutting behavior+ there) is the fix if account properties grow more derived behavior.diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.pyindex 2534cf8aaf3f..f6d43ab3d1e8 100644--- a/products/customer_analytics/backend/constants.py+++ b/products/customer_analytics/backend/constants.py@@ -13,10 +13,6 @@ CUSTOMER_ANALYTICS_CSP_FLAG = "customer-analytics-csp"# syncs, and the post-sync upsert workflow.WAREHOUSE_PERSON_PROPERTIES_FLAG = "warehouse-person-properties"-# Account assignment roles, each assignable to a user. Shared by the external account API's-# request validation and the facade write path so the set is defined once.-ACCOUNT_ASSIGNMENT_ROLE_FIELDS = ("csm", "account_executive", "account_owner")-# Mirrors frontend `BILLING_INSIGHT_SHORT_IDS` in accountBillingLogic.ts. These saved insights read# warehouse-synced billing data to report an account's PostHog consumption (events ingested, rows# synced, recordings, etc.) and spend (MRR, per-product cost). PostHog-internal: they only resolvediff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 22ffabb00f8e..779366e71380 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -46,7 +46,6 @@ from products.conversations.backend.facade.api import (list_account_tickets,)from products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplink-from products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDSfrom products.customer_analytics.backend.events import emit_account_tags_addedfrom products.customer_analytics.backend.facade.contracts import (InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,@@ -93,7 +92,10 @@ from products.customer_analytics.backend.models import (SyncStatus,TargetType,)-from products.customer_analytics.backend.models.account import AccountProperties as _ModelAccountProperties+from products.customer_analytics.backend.models.account import (+ RETIRED_ROLE_KEYS,+ AccountProperties as _ModelAccountProperties,+)from products.customer_analytics.backend.tasks.tasks import send_announcementfrom products.notebooks.backend.facade import (api as notebooks,@@ -124,17 +126,8 @@ if TYPE_CHECKING:from products.customer_analytics.backend.models import CustomPropertyValue-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,@@ -1971,8 +1964,10 @@ def _to_account_view(account: Account) -> contracts.AccountView:name=account.name,external_id=account.external_id,# Raw stored JSON (already ``exclude_unset`` from the manager), so an account with- # no assignments serializes ``properties`` as ``{}`` exactly as before.- properties=account._properties or {},+ # no assignments serializes ``properties`` as ``{}`` exactly as before. Retired role+ # keys are dropped: rows not yet backfilled must not leak them into responses, or the+ # frontend's read-modify-write of ``properties`` sends them back and gets a 400.+ properties={k: v for k, v in (account._properties or {}).items() if k not in RETIRED_ROLE_KEYS},# Unsorted, matching the old ``TaggedItemSerializerMixin.to_representation`` output.tags=_account_view_tags(account),notebooks=_account_view_notebooks(account),@@ -1991,14 +1986,11 @@ def list_accounts_for_view(limit: int,search: str | None = None,tags: list[str] | None = None,- csm: str | None = None,- account_executive: str | None = None,- account_owner: str | None = None,all_roles_unassigned: bool = False,ordering: str | None = None,) -> tuple[list[contracts.AccountView], int]:"""The accounts list endpoint, behind the facade: team + object-level access filtering,- the search / tags / role / ordering query filters, notebook + tag prefetching, and+ the search / tags / unassigned / ordering query filters, notebook + tag prefetching, andpagination. Returns ``(page, total_count)``. ``tags``/``ordering`` are pre-validated bythe view; an empty ``tags`` list is treated as "no tag filter" (matches old behavior)."""queryset = _accounts_queryset(team_id, user_access_control).prefetch_related(@@ -2012,41 +2004,15 @@ def list_accounts_for_view(if tags:queryset = queryset.filter(tagged_items__tag__name__in=tags).distinct()- # An unset role serializes as JSON null, which ``_properties__role__isnull`` does not- # match; probing the nested ``id`` matches every unassigned shape (missing key, null- # value, or empty object).+ # "Unassigned" means nobody actively holds any relationship on the account, matching the+ # accounts list HogQL runner's allRolesUnassigned.if all_roles_unassigned:- queryset = queryset.filter(- _properties__csm__id__isnull=True,- _properties__account_executive__id__isnull=True,- _properties__account_owner__id__isnull=True,+ queryset = queryset.exclude(+ id__in=AccountRelationship.objects.for_team(team_id)+ .filter(ended_at__isnull=True, user__isnull=False)+ .values("account_id"))- if csm == "unassigned":- queryset = queryset.filter(_properties__csm__id__isnull=True)- elif csm:- try:- queryset = queryset.filter(_properties__csm__id=int(csm))- except ValueError:- # Malformed user id is a no-op (return all), not "match nothing" — old behavior.- pass-- if account_executive == "unassigned":- queryset = queryset.filter(_properties__account_executive__id__isnull=True)- elif account_executive:- try:- queryset = queryset.filter(_properties__account_executive__id=int(account_executive))- except ValueError:- pass-- if account_owner == "unassigned":- queryset = queryset.filter(_properties__account_owner__id__isnull=True)- elif account_owner:- try:- queryset = queryset.filter(_properties__account_owner__id=int(account_owner))- except ValueError:- pass-queryset = queryset.order_by(ordering) if ordering else queryset.order_by("-created_at")total_count = queryset.count()@@ -2117,9 +2083,9 @@ def create_account(was_impersonated: bool = False,trigger: Trigger | None = None,) -> Account:- """The single account-creation write path: validates properties, sets tags, shadows role- assignments into the relationships table, and logs activity. Product-internal — it returns- the model, so it must not be called across the product boundary.+ """The single account-creation write path: validates properties, sets tags, and logs+ activity. Product-internal — it returns the model, so it must not be called across the+ product boundary.Raises ``AccountPropertiesValidationError`` / ``AccountConflictError``."""try:with transaction.atomic():@@ -2133,8 +2099,6 @@ def create_account(slack_summary_cadence=slack_summary_cadence,)_set_tags(tags, account, actor=created_by)- if any(field in (account._properties or {}) for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS):- _relationships_logic.sync_from_account_properties(account, created_by=created_by)except PydanticValidationError as exc:raise AccountPropertiesValidationError(_format_pydantic_errors(exc))except IntegrityError:@@ -2202,8 +2166,6 @@ def update_account_for_view(with transaction.atomic():account = update_account(account, **update_kwargs)_set_tags(input.tags, account, actor=user)- if input.properties_provided:- _relationships_logic.sync_from_account_properties(account, created_by=user)if input.external_id_provided and account.external_id != previous.external_id:# The external_id is the account's group key — every stream filtering on# the old key must be rebuilt or it keeps streaming the stale key's events.@@ -2546,14 +2508,16 @@ def list_account_notes_for_view("""Team-wide account notes (internal notebooks linked to accounts), newest-modified first,restricted to accounts the caller can read. ``search`` matches note title/content (full-text)and account name (substring). ``account_id`` narrows to one account, ``created_by_ids`` to- notes authored by the given users, ``assigned_to_ids`` to notes on accounts whose CSM or- account executive is one of the given users. Returns ``(page, total_count)``."""+ notes authored by the given users, ``assigned_to_ids`` to notes on accounts where one of the+ given users actively holds a relationship. Returns ``(page, total_count)``."""accounts = _accounts_queryset(team_id, user_access_control)if assigned_to_ids:- # "Assigned to" means CSM or AE (account_owner excluded), matching the accounts list- # HogQL runner's ASSIGNED_ROLE_KEYS.+ # "Assigned to" means any active relationship, matching the accounts list HogQL+ # runner's assignedToUserIds.accounts = accounts.filter(- Q(_properties__csm__id__in=assigned_to_ids) | Q(_properties__account_executive__id__in=assigned_to_ids)+ id__in=AccountRelationship.objects.for_team(team_id)+ .filter(ended_at__isnull=True, user_id__in=assigned_to_ids)+ .values("account_id"))accessible_account_ids = accounts.values_list("id", flat=True)notes, count = notebooks.list_team_account_notes(diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.pyindex b8180479dba8..3161fc371f48 100644--- a/products/customer_analytics/backend/facade/constants.py+++ b/products/customer_analytics/backend/facade/constants.py@@ -6,7 +6,6 @@ stays as the source of truth."""from products.customer_analytics.backend.constants import (- ACCOUNT_ASSIGNMENT_ROLE_FIELDS,BILLING_SPEND_INSIGHT_SHORT_IDS,BILLING_USAGE_INSIGHT_SHORT_IDS,CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,@@ -19,7 +18,6 @@ from products.customer_analytics.backend.constants import ()__all__ = [- "ACCOUNT_ASSIGNMENT_ROLE_FIELDS","BILLING_SPEND_INSIGHT_SHORT_IDS","BILLING_USAGE_INSIGHT_SHORT_IDS","CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES",diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex e5e5a264d3b5..910c9855848e 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -32,7 +32,7 @@ class EventStreamTestMessageError(Exception):@dataclass(frozen=True)class AccountAssignment:- """A user assigned to an account role (CSM, account executive, account owner)."""+ """A user assigned to an account relationship (CSM, account executive, ...)."""id: intemail: str@@ -65,14 +65,11 @@ class AccountRelationship:@dataclass(frozen=True)class AccountProperties:- """Typed account properties — assignment roles and external-system identifiers.+ """Typed account properties — 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 = Nonestripe_customer_id: str | None = Nonehubspot_deal_id: str | None = Nonebilling_id: str | None = Nonediff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.pyindex 3cc9f31f1839..dc73d2a4dc87 100644--- a/products/customer_analytics/backend/logic/relationships.py+++ b/products/customer_analytics/backend/logic/relationships.py@@ -1,6 +1,6 @@"""-Assign/end transactions for account relationships, plus the transitional forward-sync from-the legacy JSON role keys. Called by the facade and product-internal account writers only.+Assign/end transactions for account relationships. Called by the facade and+product-internal account writers only."""from uuid import UUID@@ -12,14 +12,6 @@ from posthog.models.user import Userfrom products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition-# Legacy Account properties role key -> seeded definition name. Definitions carry no stable-# machine key, so the sync and backfill map role keys to seeded definitions by name.-SEEDED_DEFINITIONS: tuple[tuple[str, str], ...] = (- ("csm", "CSM"),- ("account_executive", "Account executive"),- ("account_owner", "Account owner"),-)-class AccountRelationshipNotFound(Exception):pass@@ -76,36 +68,3 @@ def end_relationship(*, team_id: int, account_id: str | UUID, relationship_id: srelationship.ended_at = timezone.now()relationship.save(update_fields=["ended_at"])return relationship---def sync_from_account_properties(account: Account, *, created_by: User | None = None) -> None:- """Forward-sync the legacy JSON role keys into the relationships table.-- Transitional: Account._properties is still the source of truth for roles, so every JSON- role write calls this to keep the table shadowing it — see backend/COMPROMISES.md.- Roles whose definition doesn't exist yet and unresolvable user ids are skipped; the JSON- stays authoritative. Only users who are members of the account's organization resolve —- the relationships endpoint returns real emails, so resolving arbitrary global user ids- would let editors enumerate emails of users outside their org.- """- definitions_by_name = {- definition.name: definition- for definition in AccountRelationshipDefinition.objects.for_team(account.team_id).filter(- name__in=[name for _, name in SEEDED_DEFINITIONS]- )- }- properties = account._properties or {}- for key, name in SEEDED_DEFINITIONS:- definition = definitions_by_name.get(name)- if definition is None:- continue- assignment = properties.get(key)- user_id = assignment.get("id") if isinstance(assignment, dict) else None- if user_id is None:- end_active(team_id=account.team_id, account=account, definition=definition)- elif (- user := User.objects.filter(- id=user_id, organization_membership__organization__team__id=account.team_id- ).first()- ) is not None:- assign(team_id=account.team_id, account=account, definition=definition, user=user, created_by=created_by)diff --git a/products/customer_analytics/backend/management/commands/backfill_account_relationships.py b/products/customer_analytics/backend/management/commands/backfill_account_relationships.pynew file mode 100644index 000000000000..725ca2082bf7--- /dev/null+++ b/products/customer_analytics/backend/management/commands/backfill_account_relationships.py@@ -0,0 +1,121 @@+"""Backfill account relationships from the retired JSON role keys.++One-time cutover companion. ``Account._properties`` used to carry ``csm``,+``account_executive``, and ``account_owner`` assignments, forward-synced into the+relationship tables on every write. Accounts last written before that sync existed never+made it into the table. Per team this command creates the three seeded definitions,+assigns each JSON role holder as an active relationship, then removes the retired keys+from the stored JSON.++Idempotent. Run once per environment, with --dry-run first:++ python manage.py backfill_account_relationships --dry-run+ python manage.py backfill_account_relationships+"""++from typing import Any++from django.core.management.base import BaseCommand+from django.db import transaction++from posthog.models import User++from products.customer_analytics.backend.logic import relationships as relationships_logic+from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition++ROLE_KEY_TO_DEFINITION_NAME = {+ "csm": "CSM",+ "account_executive": "Account executive",+ "account_owner": "Account owner",+}+++class Command(BaseCommand):+ help = "Backfill account relationships from the retired JSON role keys, then strip the keys."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("--dry-run", action="store_true", help="Report what would change without writing.")++ def handle(self, *args: Any, **options: Any) -> None:+ dry_run: bool = options["dry_run"]+ role_keys = list(ROLE_KEY_TO_DEFINITION_NAME)+ team_ids = (+ Account.objects.unscoped()+ .filter(_properties__has_any_keys=role_keys)+ .values_list("team_id", flat=True)+ .distinct()+ )+ assigned = stripped = 0+ for team_id in team_ids:+ definitions = self._definitions_for_team(team_id, dry_run)+ accounts = Account.objects.for_team(team_id).filter(_properties__has_any_keys=role_keys)+ for account in accounts:+ assigned += self._assign_from_json(team_id, account, definitions, dry_run)+ for key in role_keys:+ account._properties.pop(key, None)+ if not dry_run:+ account.save(update_fields=["_properties"])+ stripped += 1+ prefix = "[dry-run] would have " if dry_run else ""+ self.stdout.write(+ f"{prefix}assigned {assigned} relationship(s) and stripped role keys "+ f"from {stripped} account(s) across {len(team_ids)} team(s)."+ )++ @staticmethod+ def _definitions_for_team(team_id: int, dry_run: bool) -> dict[str, AccountRelationshipDefinition | None]:+ definitions: dict[str, AccountRelationshipDefinition | None] = {}+ for key, name in ROLE_KEY_TO_DEFINITION_NAME.items():+ if dry_run:+ definitions[key] = AccountRelationshipDefinition.objects.for_team(team_id).filter(name=name).first()+ else:+ definitions[key] = AccountRelationshipDefinition.objects.for_team(team_id).get_or_create(+ team_id=team_id, name=name+ )[0]+ return definitions++ @staticmethod+ def _assign_from_json(+ team_id: int,+ account: Account,+ definitions: dict[str, AccountRelationshipDefinition | None],+ dry_run: bool,+ ) -> int:+ assigned = 0+ for key, definition in definitions.items():+ assignment = (account._properties or {}).get(key)+ user_id = assignment.get("id") if isinstance(assignment, dict) else None+ if user_id is None:+ continue+ # Only org members resolve because the relationships endpoint returns real emails,+ # so assigning arbitrary global user ids would leak emails of users outside the org.+ user = User.objects.filter(id=user_id, organization_membership__organization__team__id=team_id).first()+ if user is None:+ continue+ if dry_run:+ if definition is None or not _has_active_holder(team_id, account, definition):+ assigned += 1+ continue+ if definition is None:+ continue+ # The relationships table has been authoritative since the cutover deploy, so only+ # fill gaps and never overwrite an assignment made after it. The check runs under+ # assign's definition lock, or a concurrent assign landing between check and assign+ # would be replaced by the stale JSON holder.+ with transaction.atomic():+ AccountRelationshipDefinition.objects.for_team(team_id).select_for_update().get(id=definition.id)+ if _has_active_holder(team_id, account, definition):+ continue+ relationships_logic.assign(+ team_id=team_id, account=account, definition=definition, user=user, created_by=None+ )+ assigned += 1+ return assigned+++def _has_active_holder(team_id: int, account: Account, definition: AccountRelationshipDefinition) -> bool:+ return (+ AccountRelationship.objects.for_team(team_id)+ .filter(account=account, definition=definition, ended_at__isnull=True)+ .exists()+ )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 1b1bfc146992..d76dc965da7d 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,9 @@ from posthog.models.scoping import team_scopefrom posthog.persons_db import persons_db_connectionfrom products.customer_analytics.backend.facade.api import create_account-from products.customer_analytics.backend.models.account import Account, AccountAssignment, AccountProperties+from products.customer_analytics.backend.logic import relationships as relationships_logic+from products.customer_analytics.backend.models.account import Account, AccountProperties+from products.customer_analytics.backend.models.relationship import AccountRelationshipDefinitionfrom products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfigfrom products.notebooks.backend.facade import api as notebooks@@ -153,10 +155,10 @@ class Command(BaseCommand):def _create_accounts(self, team: Team, groups: list[tuple[str, dict[str, Any]]], user_pool: list[User]) -> list[Account]:- assignments = [AccountAssignment(id=user.id, email=user.email) for user in user_pool]creator = team.organization.members.first()created = 0accounts: list[Account] = []+ definitions = self._ensure_role_definitions(team, creator)with team_scope(team.pk):existing = {account.external_id: account@@ -170,22 +172,42 @@ class Command(BaseCommand):name=props.get("name") or group_key,external_id=group_key,created_by=creator,- properties=self._account_roles(assignments, index, group_key),+ properties=AccountProperties(stripe_customer_id=f"cus_{group_key[:14]}"),)+ self._assign_roles(team, account, definitions, user_pool, index, creator)created += 1accounts.append(account)self.stdout.write(f"Created {created} account(s) ({len(groups) - created} already existed).")return accounts@staticmethod- def _account_roles(assignments: list[AccountAssignment], index: int, group_key: str) -> AccountProperties:- count = len(assignments)- return AccountProperties(- csm=assignments[index % count] if count else None,- account_executive=assignments[(index + 1) % count] if count else None,- account_owner=assignments[(index + 2) % count] if count else None,- stripe_customer_id=f"cus_{group_key[:14]}",- )+ def _ensure_role_definitions(team: Team, creator: User | None) -> list[AccountRelationshipDefinition]:+ return [+ AccountRelationshipDefinition.objects.for_team(team.pk).get_or_create(+ team_id=team.pk, name=name, defaults={"created_by": creator}+ )[0]+ for name in ("CSM", "Account executive", "Account owner")+ ]++ @staticmethod+ def _assign_roles(+ team: Team,+ account: Account,+ definitions: list[AccountRelationshipDefinition],+ user_pool: list[User],+ index: int,+ creator: User | None,+ ) -> None:+ if not user_pool:+ return+ for offset, definition in enumerate(definitions):+ relationships_logic.assign(+ team_id=team.pk,+ account=account,+ definition=definition,+ user=user_pool[(index + offset) % len(user_pool)],+ created_by=creator,+ )@transaction.atomicdef _create_notes(diff --git a/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.pyindex ed6e00d55bac..8cbf8dc03b87 100644--- a/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py+++ b/products/customer_analytics/backend/management/commands/test/test_seed_customer_analytics_accounts.py@@ -11,6 +11,7 @@ from posthog.persons_db import persons_db_connectionfrom posthog.persons_seed import insert_seed_groupfrom products.customer_analytics.backend.models.account import Account+from products.customer_analytics.backend.models.relationship import AccountRelationshipfrom products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfigfrom products.notebooks.backend.models import Notebook, ResourceNotebook@@ -66,11 +67,13 @@ class TestSeedCustomerAnalyticsAccounts(BaseTest):assert set(accounts) == {"acme-id", "globex-id", "initech-id"}assert accounts["acme-id"].name == "Acme"- # Users: a pool joined to the org, assigned as account roles.+ # Users: a pool joined to the org, assigned as account relationships.assert len(self._pool_emails()) == 4- owner = accounts["acme-id"].properties.account_owner- assert owner is not None- assert owner.email in self._pool_emails()+ holders = AccountRelationship.objects.for_team(self.team.pk).filter(+ account=accounts["acme-id"], ended_at__isnull=True+ )+ assert {rel.definition.name for rel in holders} == {"CSM", "Account executive", "Account owner"}+ assert all(rel.user is not None and rel.user.email in self._pool_emails() for rel in holders)# Notes: only the first two accounts (by group key) get two notes each.notebooks = Notebook.objects.filter(resources__account__team_id=self.team.pk)diff --git a/products/customer_analytics/backend/models/account.py b/products/customer_analytics/backend/models/account.pyindex dc6b3ceb8cc0..4ca03dcb1140 100644--- a/products/customer_analytics/backend/models/account.py+++ b/products/customer_analytics/backend/models/account.py@@ -12,20 +12,14 @@ from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModelfrom products.customer_analytics.backend.models.account_channel_summary import SlackSummaryCadence--class AccountAssignment(BaseModel):- id: int- email: str+# Role assignments moved to the relationship tables. Stored rows may carry these keys until+# `backfill_account_relationships` has run in the environment (see COMPROMISES.md).+RETIRED_ROLE_KEYS = ("csm", "account_executive", "account_owner")class AccountProperties(BaseModel):model_config = ConfigDict(extra="forbid")- # Key roles- csm: AccountAssignment | None = None- account_executive: AccountAssignment | None = None- account_owner: AccountAssignment | None = None-# External connectionsstripe_customer_id: str | None = Nonehubspot_deal_id: str | None = None@@ -63,7 +57,8 @@ class Account(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFiel@propertydef properties(self) -> AccountProperties:- return AccountProperties.model_validate(self._properties or {})+ stored = self._properties or {}+ return AccountProperties.model_validate({k: v for k, v in stored.items() if k not in RETIRED_ROLE_KEYS})@properties.setterdef properties(self, value: "dict | AccountProperties") -> None:diff --git a/products/customer_analytics/backend/models/account_test.py b/products/customer_analytics/backend/models/account_test.pyindex bd7a7c33518a..4e6e0cea3861 100644--- a/products/customer_analytics/backend/models/account_test.py+++ b/products/customer_analytics/backend/models/account_test.py@@ -11,7 +11,7 @@ from posthog.models import Team, Userfrom posthog.models.scoping import team_scopefrom products.customer_analytics.backend.models import Account, TeamCustomerAnalyticsConfig-from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties+from products.customer_analytics.backend.models.account import AccountPropertiesfrom products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixin@@ -28,17 +28,25 @@ class AccountPropertiesValidationTest(TeamScopedTestMixin, BaseTest):def test_typed_property_round_trip_through_setter(self):account = Account.objects.create(team=self.team, name="Round-trip")- account.properties = AccountProperties(- csm=AccountAssignment(id=self.user.id, email=self.user.email),- )+ account.properties = AccountProperties(stripe_customer_id="cus_1")account.save()account.refresh_from_db()props = account.propertiesassert isinstance(props, AccountProperties)- assert props.csm == AccountAssignment(id=self.user.id, email=self.user.email)- assert props.account_executive is None- assert props.account_owner is None+ assert props.stripe_customer_id == "cus_1"+ assert props.sfdc_id is None++ def test_getter_ignores_retired_role_keys_in_stored_rows(self):+ account = Account.objects.create(+ team=self.team,+ name="Legacy",+ _properties={"csm": {"id": self.user.id, "email": self.user.email}, "sfdc_id": "001xx"},+ )++ props = account.properties++ assert props.sfdc_id == "001xx"def test_setter_validates_dict_input(self):account = Account.objects.create(team=self.team, name="Bad input")diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex 519282f852d5..5839ddb4f09e 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -292,8 +292,8 @@ class ExternalAccountSerializer(serializers.Serializer):)name = serializers.CharField(help_text="Human-readable account name.")properties = serializers.DictField(- child=serializers.JSONField(help_text="Property value: a string, a role-assignment object, or null."),- help_text="Typed account properties: role assignments (csm, account_executive, account_owner) and external-system ids.",+ child=serializers.JSONField(help_text="Property value: a string or null."),+ help_text="Typed account properties: external-system ids. Role assignments live under `relationships`.",)tags = serializers.ListField(child=serializers.CharField(), help_text="Tag names on the account, sorted alphabetically."diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 57665fe8cbc1..2f9602deaf4b 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -63,25 +63,10 @@ _PROFILE_CONFIG_SCOPE_CHOICES = [("group_4", "Group 4"),]-# JSON schema for the account ``properties`` field. Kept verbatim from the pre-isolation-# serializer so the generated ``AccountApiProperties`` component is unchanged.-_ACCOUNT_ASSIGNMENT_SCHEMA = {- "type": "object",- "nullable": True,- "properties": {- "id": {"type": "integer"},- "email": {"type": "string"},- },- "required": ["id", "email"],-}-_ACCOUNT_PROPERTIES_SCHEMA = {"type": "object","additionalProperties": False,"properties": {- "csm": _ACCOUNT_ASSIGNMENT_SCHEMA,- "account_executive": _ACCOUNT_ASSIGNMENT_SCHEMA,- "account_owner": _ACCOUNT_ASSIGNMENT_SCHEMA,"stripe_customer_id": {"type": "string", "nullable": True},"hubspot_deal_id": {"type": "string", "nullable": True},"billing_id": {"type": "string", "nullable": True},@@ -174,10 +159,10 @@ class AccountSerializer(DataclassSerializer):required=False,allow_null=True,help_text=(- "Typed account properties: assignment fields (csm, account_executive, account_owner) "- "and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, "- "sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty "- "object. Unknown keys are rejected."+ "Typed account properties: external system identifiers (stripe_customer_id, "+ "hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, "+ "usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys "+ "are rejected. User assignments live on account relationships, not here."),)tags = serializers.ListField(diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 5add3022761a..d4f45e83dacf 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -897,35 +897,12 @@ class AccountViewSet("Malformed values (not a JSON-encoded list of strings) return a 400."),),- OpenApiParameter(- name="csm",- type=OpenApiTypes.STR,- location=OpenApiParameter.QUERY,- required=False,- description=("Filter by CSM. Use 'unassigned' for accounts with no CSM, or an integer user id."),- ),- OpenApiParameter(- name="account_executive",- type=OpenApiTypes.STR,- location=OpenApiParameter.QUERY,- required=False,- description="Filter by account executive. Use 'unassigned' or an integer user id.",- ),- OpenApiParameter(- name="account_owner",- type=OpenApiTypes.STR,- location=OpenApiParameter.QUERY,- required=False,- description="Filter by account owner. Use 'unassigned' or an integer user id.",- ),OpenApiParameter(name="all_roles_unassigned",type=OpenApiTypes.BOOL,location=OpenApiParameter.QUERY,required=False,- description=(- "When true, returns only accounts where CSM, account executive, and account owner are all unset."- ),+ description="When true, returns only accounts where no user actively holds any relationship.",),OpenApiParameter(name="ordering",@@ -950,9 +927,6 @@ class AccountViewSet(limit=limit,search=request.query_params.get("search", "").strip() or None,tags=tags,- csm=request.query_params.get("csm"),- account_executive=request.query_params.get("account_executive"),- account_owner=request.query_params.get("account_owner"),all_roles_unassigned=request.query_params.get("all_roles_unassigned", "").lower() == "true",ordering=ordering,),diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex 09841fb0a4ed..e3433dfa42b1 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -31,7 +31,7 @@ from products.customer_analytics.backend.models import (CustomPropertySource,CustomPropertyValue,)-from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties+from products.customer_analytics.backend.models.account import AccountPropertiesfrom products.customer_analytics.backend.models.team_scoped_test_base import TeamScopedTestMixinfrom products.customer_analytics.backend.test.factories import create_accountfrom products.notebooks.backend.models import Notebook, ResourceNotebook@@ -48,7 +48,6 @@ class TestCustomerAnalyticsFacade(BaseTest):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"),)@@ -60,7 +59,6 @@ class TestCustomerAnalyticsFacade(BaseTest):assert result.team_id == self.team.idassert 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):@@ -165,7 +163,7 @@ class TestCustomerAnalyticsFacade(BaseTest):name="Acme Corp",external_id="acme-1",_properties=AccountProperties(- csm=AccountAssignment(id=self.user.id, email=self.user.email),+ stripe_customer_id="cus_1",).model_dump(mode="json"),)tag = Tag.objects.create(name="enterprise", team_id=self.team.id)@@ -179,7 +177,7 @@ class TestCustomerAnalyticsFacade(BaseTest):assert result.name == "Acme Corp"assert result.tags == ["enterprise"]assert result.properties == account.properties.model_dump(mode="json")- assert result.properties["csm"] == {"id": self.user.id, "email": self.user.email}+ assert result.properties["stripe_customer_id"] == "cus_1"def test_get_external_account_missing_and_other_team(self):create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")@@ -252,7 +250,6 @@ class TestCustomerAnalyticsFacade(BaseTest):account.refresh_from_db()assert account.properties.stripe_customer_id == "cus_123"- assert account.properties.csm is Nonedef test_update_external_account_rejects_non_member(self):definition = self._create_csm_definition()@@ -818,11 +815,11 @@ class AccountUpdateWriteTest(TeamScopedTestMixin, BaseTest):team_id=self.team.pk,created_by=self.user,name="Acme",- _properties={"csm": {"id": self.user.id, "email": self.user.email}},+ _properties={"sfdc_id": "001xx"},)facade.update_account(account, properties={"stripe_customer_id": "cus_123"})account.refresh_from_db()- assert account.properties.csm is None+ assert account.properties.sfdc_id is Noneassert account.properties.stripe_customer_id == "cus_123"def test_update_account_leaves_properties_untouched_when_not_passed(self):diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.pyindex b59b81ee0e53..95350340323b 100644--- a/products/customer_analytics/backend/test/test_relationships.py+++ b/products/customer_analytics/backend/test/test_relationships.py@@ -1,14 +1,12 @@from posthog.test.base import BaseTest+from django.core.management import call_command+from posthog.models import Team, User-from posthog.rbac.user_access_control import UserAccessControl-from products.customer_analytics.backend.facade import (- api as facade,- contracts,-)+from products.customer_analytics.backend.facade import api as facadefrom products.customer_analytics.backend.logic import relationships-from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition+from products.customer_analytics.backend.models import AccountRelationship, AccountRelationshipDefinitionfrom products.customer_analytics.backend.test.factories import create_account@@ -88,77 +86,65 @@ class TestRelationshipLogic(BaseTest):assert ended.ended_at is not None-class TestSyncFromAccountProperties(BaseTest):+class TestBackfillAccountRelationshipsCommand(BaseTest):def setUp(self):super().setUp()- AccountRelationshipDefinition.objects.for_team(self.team.id).create(team_id=self.team.id, name="CSM")self.account = create_account(team_id=self.team.pk,name="Acme",_properties={"csm": {"id": self.user.id, "email": self.user.email}, "sfdc_id": "001xx"},)- def _get_active_rows_for_account(self):+ def _active_rows(self):return AccountRelationship.objects.for_team(self.team.id).filter(account=self.account, ended_at__isnull=True)- def test_sync_creates_rows_from_role_properties(self):- relationships.sync_from_account_properties(self.account, created_by=self.user)- rows = self._get_active_rows_for_account()+ def _refreshed_properties(self) -> dict:+ self.account.refresh_from_db()+ return self.account._properties++ def test_backfill_assigns_holders_and_strips_role_keys(self):+ call_command("backfill_account_relationships")+ rows = self._active_rows()assert rows.count() == 1row = rows.first()assert row is not Noneassert row.definition.name == "CSM"assert row.user_id == self.user.id+ assert self._refreshed_properties() == {"sfdc_id": "001xx"}- def test_sync_is_idempotent(self):- relationships.sync_from_account_properties(self.account)- relationships.sync_from_account_properties(self.account)+ def test_backfill_is_idempotent(self):+ call_command("backfill_account_relationships")+ call_command("backfill_account_relationships")assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 1- def test_sync_ends_relationship_when_key_cleared(self):- relationships.sync_from_account_properties(self.account)- facade.update_account(self.account, properties={"sfdc_id": "001xx"})- relationships.sync_from_account_properties(self.account)- assert self._get_active_rows_for_account().count() == 0- assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 1+ def test_backfill_skips_users_outside_the_organization_but_still_strips(self):+ outsider = User.objects.create_user(email="[email protected]", password=None, first_name="Out")+ self.account._properties["csm"] = {"id": outsider.id, "email": outsider.email}+ self.account.save(update_fields=["_properties"])+ call_command("backfill_account_relationships")+ assert self._active_rows().count() == 0+ assert "csm" not in self._refreshed_properties()- def test_sync_hands_off_single_holder_on_user_change(self):+ def test_backfill_does_not_overwrite_an_existing_active_holder(self):other_user = self._create_user("[email protected]")- relationships.sync_from_account_properties(self.account)- facade.update_account(self.account, properties={"csm": {"id": other_user.id, "email": other_user.email}})- relationships.sync_from_account_properties(self.account)- rows = self._get_active_rows_for_account()+ definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(+ team_id=self.team.id, name="CSM"+ )+ relationships.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=other_user, created_by=None+ )+ call_command("backfill_account_relationships")+ rows = self._active_rows()assert rows.count() == 1row = rows.first()assert row is not Noneassert row.user_id == other_user.id- assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 2+ assert "csm" not in self._refreshed_properties()- def test_sync_skips_unresolvable_users(self):- facade.update_account(self.account, properties={"csm": {"id": 99999999, "email": "[email protected]"}})- relationships.sync_from_account_properties(self.account)- assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 0-- def test_sync_skips_users_outside_the_organization(self):- outsider = User.objects.create_user(email="[email protected]", password=None, first_name="Out")- facade.update_account(self.account, properties={"csm": {"id": outsider.id, "email": outsider.email}})- relationships.sync_from_account_properties(self.account)- assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 0-- def test_sync_skips_roles_whose_definition_is_missing(self):- facade.update_account(- self.account,- properties={- "csm": {"id": self.user.id, "email": self.user.email},- "account_executive": {"id": self.user.id, "email": self.user.email},- },- )- relationships.sync_from_account_properties(self.account)- rows = self._get_active_rows_for_account()- assert rows.count() == 1- row = rows.first()- assert row is not None- assert row.definition.name == "CSM"+ def test_backfill_dry_run_changes_nothing(self):+ call_command("backfill_account_relationships", "--dry-run")+ assert self._active_rows().count() == 0+ assert "csm" in self._refreshed_properties()class TestRelationshipFacade(BaseTest):@@ -334,7 +320,7 @@ class TestRelationshipFacade(BaseTest):assert not facade.delete_account_relationship_definition(team_id=other_team.id, definition_id=definition.id)-class TestWritePathSync(BaseTest):+class TestExternalRelationshipAssignments(BaseTest):def setUp(self):super().setUp()self.csm_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(@@ -344,43 +330,7 @@ class TestWritePathSync(BaseTest):def _active_rows(self, account):return AccountRelationship.objects.for_team(self.team.id).filter(account=account, ended_at__isnull=True)- def _update_properties(self, account_id, properties):- return facade.update_account_for_view(- team_id=self.team.id,- account_id=str(account_id),- input=contracts.UpdateAccountInput(properties=properties, properties_provided=True),- user_access_control=UserAccessControl(user=self.user, team=self.team),- required_level="editor",- organization_id=self.organization.id,- user=self.user,- was_impersonated=False,- )-- def test_update_account_for_view_syncs_role_assign_and_clear(self):- account = create_account(team_id=self.team.pk, name="Acme")- self._update_properties(account.id, {"csm": {"id": self.user.id, "email": self.user.email}})- rows = self._active_rows(account)- assert rows.count() == 1- row = rows.first()- assert row is not None- assert row.user_id == self.user.id- self._update_properties(account.id, {})- assert self._active_rows(account).count() == 0-- def test_create_account_for_view_syncs_roles(self):- view = facade.create_account_for_view(- team=self.team,- input=contracts.CreateAccountInput(- name="Acme", properties={"csm": {"id": self.user.id, "email": self.user.email}}- ),- user=self.user,- was_impersonated=False,- )- assert view.id is not None- account = Account.objects.for_team(self.team.id).get(id=view.id)- assert self._active_rows(account).count() == 1-- def test_update_external_account_syncs_roles(self):+ def test_update_external_account_assigns_relationships(self):account = create_account(team_id=self.team.pk, name="Acme", external_id="acme-1")result = facade.update_external_account(self.team.id,diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex b13df7ee89b1..cc311d7e9c90 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -6,11 +6,11 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom django.apps import apps+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.api.tagged_item import set_tags_on_objectfrom posthog.constants import AvailableFeaturefrom posthog.models import Tag, TaggedItemfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -33,7 +33,6 @@ from products.customer_analytics.backend.models import (DisplayType,TargetType,)-from products.customer_analytics.backend.models.account import AccountAssignmentfrom products.customer_analytics.backend.test.factories import create_account, create_custom_property_definitionfrom products.notebooks.backend.models import Notebook, ResourceNotebookfrom products.product_analytics.backend.models.insight import Insight@@ -430,7 +429,7 @@ class TestAccountViewSet(APIBaseTest):{"name": "Acme Corp","external_id": "acme-123",- "properties": {"csm": {"id": self.user.id, "email": self.user.email}},+ "properties": {"stripe_customer_id": "cus_123"},},format="json",)@@ -440,14 +439,14 @@ class TestAccountViewSet(APIBaseTest):self.assertIn("id", data)self.assertEqual(data["name"], "Acme Corp")self.assertEqual(data["external_id"], "acme-123")- self.assertEqual(data["properties"]["csm"], {"id": self.user.id, "email": self.user.email})+ self.assertEqual(data["properties"]["stripe_customer_id"], "cus_123")self.assertIn("created_at", data)self.assertIn("updated_at", data)account = Account.objects.unscoped().get(id=data["id"]) # nosemgrep: idor-lookup-without-teamself.assertEqual(account.created_by, self.user)self.assertEqual(account.team, self.team)- self.assertEqual(account.properties.csm, AccountAssignment(id=self.user.id, email=self.user.email))+ self.assertEqual(account.properties.stripe_customer_id, "cus_123")def test_create_minimal_payload_uses_defaults(self):response = self.client.post(self.endpoint_base, {"name": "Bare Account"}, format="json")@@ -476,7 +475,7 @@ class TestAccountViewSet(APIBaseTest):def test_retrieve(self):account = self._create_account(external_id="ext-1",- properties={"csm": {"id": self.user.id, "email": self.user.email}},+ properties={"stripe_customer_id": "cus_123"},)response = self.client.get(f"{self.endpoint_base}{account.id}/")@@ -486,16 +485,27 @@ class TestAccountViewSet(APIBaseTest):self.assertEqual(data["id"], str(account.id))self.assertEqual(data["name"], "Acme Corp")self.assertEqual(data["external_id"], "ext-1")- self.assertEqual(data["properties"]["csm"], {"id": self.user.id, "email": self.user.email})+ self.assertEqual(data["properties"]["stripe_customer_id"], "cus_123")++ def test_retrieve_hides_retired_role_keys_in_stored_rows(self):+ # Rows not yet cleaned by backfill_account_relationships must not leak role keys:+ # the frontend read-modify-writes `properties`, and echoing them back would 400.+ account = self._create_account(+ _properties={"csm": {"id": self.user.id, "email": self.user.email}, "billing_id": "B-1"}+ )++ response = self.client.get(f"{self.endpoint_base}{account.id}/")++ self.assertEqual(response.json()["properties"], {"billing_id": "B-1"})def test_update(self):- account = self._create_account(properties={"csm": {"id": self.user.id, "email": self.user.email}})+ account = self._create_account(properties={"stripe_customer_id": "cus_123"})response = self.client.patch(f"{self.endpoint_base}{account.id}/",{"name": "Renamed",- "properties": {"account_owner": {"id": self.user.id, "email": self.user.email}},+ "properties": {"sfdc_id": "001xx"},},format="json",)@@ -503,7 +513,7 @@ class TestAccountViewSet(APIBaseTest):self.assertEqual(status.HTTP_200_OK, response.status_code)account.refresh_from_db()self.assertEqual(account.name, "Renamed")- self.assertEqual(account.properties.account_owner, AccountAssignment(id=self.user.id, email=self.user.email))+ self.assertEqual(account.properties.sfdc_id, "001xx")def test_delete(self):account = self._create_account()@@ -621,13 +631,8 @@ class TestAccountViewSet(APIBaseTest):"properties",),(- "properties_assignment_missing_email",- {"name": "Acme", "properties": {"csm": {"id": 1}}},- "properties",- ),- (- "properties_assignment_wrong_id_type",- {"name": "Acme", "properties": {"csm": {"id": "not-an-int", "email": "[email protected]"}}},+ "properties_retired_role_key",+ {"name": "Acme", "properties": {"csm": {"id": 1, "email": "[email protected]"}}},"properties",),]@@ -833,72 +838,21 @@ class TestAccountViewSet(APIBaseTest):new_logs = ActivityLog.objects.filter(team_id=self.team.id, scope="Account", activity="updated").count()self.assertGreater(new_logs, initial_logs)- def test_list_accounts_filter_by_csm_user_id(self):- self._create_account(name="A", _properties={"csm": {"id": 7, "email": "[email protected]"}})- self._create_account(name="B", _properties={"csm": {"id": 9, "email": "[email protected]"}})- response = self.client.get(f"/api/environments/{self.team.id}/accounts/?csm=7")- names = [r["name"] for r in response.json()["results"]]- assert names == ["A"]-- @parameterized.expand(- [- # `_properties` defaults to {} — every role key is absent.- ("absent_keys", {"_properties": {}}),- # The manager fills every role key with an explicit JSON null.- ("null_valued_keys", {"properties": {}}),- ]- )- def test_list_accounts_filter_by_csm_unassigned(self, _name, unassigned_kwargs):- self._create_account(name="Assigned", properties={"csm": {"id": 7, "email": "[email protected]"}})- self._create_account(name="Unassigned", **unassigned_kwargs)- response = self.client.get(f"{self.endpoint_base}?csm=unassigned")- assert [r["name"] for r in response.json()["results"]] == ["Unassigned"]-- def test_list_accounts_filter_by_account_executive_user_id(self):- self._create_account(name="A", _properties={"account_executive": {"id": 7, "email": "[email protected]"}})- self._create_account(name="B")- response = self.client.get(f"/api/environments/{self.team.id}/accounts/?account_executive=7")- assert [r["name"] for r in response.json()["results"]] == ["A"]-- def test_list_accounts_filter_by_account_owner_user_id(self):- self._create_account(name="A", _properties={"account_owner": {"id": 7, "email": "[email protected]"}})- self._create_account(name="B")- response = self.client.get(f"/api/environments/{self.team.id}/accounts/?account_owner=7")- assert [r["name"] for r in response.json()["results"]] == ["A"]-- @parameterized.expand(- [- # `_properties` defaults to {} — every role key is absent.- ("absent_keys", {"_properties": {}}),- # The manager fills every role key with an explicit JSON null.- ("null_valued_keys", {"properties": {}}),- ]- )- def test_list_accounts_filter_all_roles_unassigned(self, _name, unassigned_kwargs):- # Created through the manager, so every role key is present and csm has a real id.- self._create_account(name="Has CSM", properties={"csm": {"id": 7, "email": "[email protected]"}})- self._create_account(name="Unassigned", **unassigned_kwargs)+ def test_list_accounts_filter_all_roles_unassigned(self):+ definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(+ team_id=self.team.id, name="CSM"+ )+ assigned = self._create_account(name="Has CSM")+ AccountRelationship.objects.for_team(self.team.id).create(+ team_id=self.team.id, account=assigned, definition=definition, user=self.user+ )+ ended = self._create_account(name="Ended CSM")+ AccountRelationship.objects.for_team(self.team.id).create(+ team_id=self.team.id, account=ended, definition=definition, user=self.user, ended_at=timezone.now()+ )+ self._create_account(name="Unassigned")response = self.client.get(f"{self.endpoint_base}?all_roles_unassigned=true")- assert [r["name"] for r in response.json()["results"]] == ["Unassigned"]-- def test_list_accounts_filter_combined_role_and_tags(self):- account_a = self._create_account(name="A", _properties={"csm": {"id": 7, "email": "[email protected]"}})- account_b = self._create_account(name="B", _properties={"csm": {"id": 7, "email": "[email protected]"}})- account_c = self._create_account(name="C", _properties={"csm": {"id": 8, "email": "[email protected]"}})- set_tags_on_object(["enterprise"], account_a)- set_tags_on_object(["startup"], account_b)- set_tags_on_object(["enterprise"], account_c)- response = self.client.get(f'/api/environments/{self.team.id}/accounts/?csm=7&tags=["enterprise"]')- assert [r["name"] for r in response.json()["results"]] == ["A"]-- def test_list_accounts_invalid_csm_value_is_ignored(self):- # Malformed user id should be a no-op (return both accounts), not "match nothing".- self._create_account(name="A")- self._create_account(name="B", _properties={"csm": {"id": 7, "email": "[email protected]"}})- response = self.client.get(f"/api/environments/{self.team.id}/accounts/?csm=not-a-user")- assert response.status_code == status.HTTP_200_OK- names = sorted(r["name"] for r in response.json()["results"])- assert names == ["A", "B"]+ assert sorted(r["name"] for r in response.json()["results"]) == ["Ended CSM", "Unassigned"]def test_list_accounts_ordering_by_name_asc(self):# Create in alphabetical order so default `-created_at` order is [Banana, Apple];@@ -952,17 +906,6 @@ class TestAccountViewSet(APIBaseTest):response = self.client.get(f"{self.endpoint_base}?search=acme")assert len(response.json()["results"]) == 1- def test_list_accounts_role_filter_respects_team_isolation(self):- other_team = Team.objects.create(organization=self.organization, name="other")- self._create_account(- team=other_team,- name="OtherTeamAccount",- _properties={"csm": {"id": 7, "email": "[email protected]"}},- )- self._create_account(name="MyAccount", _properties={"csm": {"id": 7, "email": "[email protected]"}})- response = self.client.get(f"/api/environments/{self.team.id}/accounts/?csm=7")- assert [r["name"] for r in response.json()["results"]] == ["MyAccount"]-def test_retrieve_returns_empty_notebooks_when_none_linked(self):account = self._create_account()@@ -2353,33 +2296,36 @@ class TestAccountNotesViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)def test_list_filter_by_assigned_to(self):- # "My accounts" on the Notes tab: notes on accounts where the user is CSM or AE.- # account_owner is deliberately not treated as "assigned" (mirrors the accounts list).- csm_account = Account.objects.unscoped().create(- team=self.team, name="CSM Co", _properties={"csm": {"id": self.user.id, "email": self.user.email}}- )- ae_account = Account.objects.unscoped().create(- team=self.team,- name="AE Co",- _properties={"account_executive": {"id": self.user.id, "email": self.user.email}},- )- owner_account = Account.objects.unscoped().create(- team=self.team,- name="Owner Co",- _properties={"account_owner": {"id": self.user.id, "email": self.user.email}},+ # "My accounts" on the Notes tab: notes on accounts where the user actively holds any+ # relationship (mirrors the accounts list runner's assignedToUserIds).+ definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(+ team_id=self.team.id, name="CSM"+ )+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ assigned_account = Account.objects.unscoped().create(team=self.team, name="Assigned Co")+ AccountRelationship.objects.for_team(self.team.id).create(+ team_id=self.team.id, account=assigned_account, definition=definition, user=self.user+ )+ ended_account = Account.objects.unscoped().create(team=self.team, name="Ended Co")+ AccountRelationship.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ account=ended_account,+ definition=definition,+ user=self.user,+ ended_at=timezone.now(),)- other_account = Account.objects.unscoped().create(- team=self.team, name="Other Co", _properties={"csm": {"id": 999999, "email": "[email protected]"}}+ other_account = Account.objects.unscoped().create(team=self.team, name="Other Co")+ AccountRelationship.objects.for_team(self.team.id).create(+ team_id=self.team.id, account=other_account, definition=definition, user=other_user)- self._link_note(title="CSM note", account=csm_account)- self._link_note(title="AE note", account=ae_account)- self._link_note(title="Owner note", account=owner_account)+ self._link_note(title="Assigned note", account=assigned_account)+ self._link_note(title="Ended note", account=ended_account)self._link_note(title="Other note", account=other_account)response = self.client.get(f"{self.endpoint_base}?assigned_to={self.user.id}")titles = {n["title"] for n in response.json()["results"]}- self.assertEqual(titles, {"CSM note", "AE note"})+ self.assertEqual(titles, {"Assigned note"})@parameterized.expand([diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 3a7d53922ed5..0f4cdc213490 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -210,25 +210,10 @@ export const SlackSummaryCadenceEnumApi = {} as const/**- * Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/export type AccountApiProperties = {- /** @nullable */- csm?: {- id: number- email: string- } | null- /** @nullable */- account_executive?: {- id: number- email: string- } | null- /** @nullable */- account_owner?: {- id: number- email: string- } | null/** @nullable */stripe_customer_id?: string | null/** @nullable */@@ -264,7 +249,7 @@ export interface AccountApi {*/external_id?: string | null/**- * Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/properties?: AccountApiProperties@@ -393,25 +378,10 @@ export interface AccountRelationshipWriteApi {}/**- * Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/export type PatchedAccountApiProperties = {- /** @nullable */- csm?: {- id: number- email: string- } | null- /** @nullable */- account_executive?: {- id: number- email: string- } | null- /** @nullable */- account_owner?: {- id: number- email: string- } | null/** @nullable */stripe_customer_id?: string | null/** @nullable */@@ -447,7 +417,7 @@ export interface PatchedAccountApi {*/external_id?: string | null/**- * Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/properties?: PatchedAccountApiProperties@@ -1474,21 +1444,9 @@ export type AccountRelationshipDefinitionsListParams = {export type AccountsListParams = {/**- * Filter by account executive. Use 'unassigned' or an integer user id.- */- account_executive?: string- /**- * Filter by account owner. Use 'unassigned' or an integer user id.- */- account_owner?: string- /**- * When true, returns only accounts where CSM, account executive, and account owner are all unset.+ * When true, returns only accounts where no user actively holds any relationship.*/all_roles_unassigned?: boolean- /**- * Filter by CSM. Use 'unassigned' for accounts with no CSM, or an integer user id.- */- csm?: string/*** Number of results to return per page.*/diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 80013e240537..b92bef286af7 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -101,24 +101,6 @@ export const AccountsCreateBody = /* @__PURE__ */ zod),properties: zod.object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -130,7 +112,7 @@ export const AccountsCreateBody = /* @__PURE__ */ zod}).nullish().describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.'+ 'Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.'),tags: zod.array(zod.string())@@ -194,24 +176,6 @@ export const AccountsUpdateBody = /* @__PURE__ */ zod),properties: zod.object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -223,7 +187,7 @@ export const AccountsUpdateBody = /* @__PURE__ */ zod}).nullish().describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.'+ 'Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.'),tags: zod.array(zod.string())@@ -263,24 +227,6 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod),properties: zod.object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -292,7 +238,7 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod}).nullish().describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.'+ 'Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.'),tags: zod.array(zod.string())diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 3841733d86e3..e84a58540567 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -112,16 +112,15 @@ tools:description: >Create a new Customer Analytics account. An account is a logical container for assigning ownership acrossthe customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional- `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external system- identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional- `tags` to categorize the account.+ `properties` to set external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`,+ `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account. To assign users (CSM, account+ executive, ...), use `accounts-relationships-create` after creating the account.param_overrides:properties:description: >- Typed account properties. `csm`, `account_executive`, `account_owner` are role assignments — each- takes `{id, email}` of an existing user. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`,- `sfdc_id`, `zendesk_id` are optional string identifiers for the account in external systems. All- fields are optional.+ Typed account properties. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`,+ `zendesk_id` are optional string identifiers for the account in external systems. All fields are+ optional.tags:description: >Tag names to attach to the account. Tags are created on demand if they do not already exist for the@@ -189,17 +188,18 @@ tools:title: List accountsdescription: >List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the- account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive,- account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,- zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g.- `["enterprise","priority"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve`- for a single account by id. The `properties` above are the built-in fields only; teams also define their own- typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list`- first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole- schema or guessing at property names. To link a user to a specific account rather than the bare list,- deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is- optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the- list to that account, expands it, and opens the tab.+ account `id`, `name`, `external_id`, typed `properties` (external identifiers stripe_customer_id,+ hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. User assignments+ (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. Pass `tags`+ (JSON-encoded array, e.g. `["enterprise","priority"]`) to filter to accounts that have any of the listed+ tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields+ only; teams also define their own typed attributes as custom properties, which do not appear here. Call+ `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than+ assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific+ account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>`+ (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g.+ `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the+ tab.param_overrides:tags:description: >@@ -284,9 +284,9 @@ tools:properties:description: >Typed account properties. The server replaces the `properties` object as a whole, so include any- existing values you want to preserve. Supported keys: `csm`, `account_executive`, `account_owner`- (each `{id, email}` of an existing user), plus `stripe_customer_id`, `hubspot_deal_id`,- `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems).+ existing values you want to preserve. Supported keys: `stripe_customer_id`, `hubspot_deal_id`,+ `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems). To assign+ users (CSM, account executive, ...), use `accounts-relationships-create` instead.tags:description: >Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not a@@ -356,14 +356,14 @@ tools:idempotent: truetitle: Get accountdescription: >- Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm,- account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,- zendesk_id external identifiers) and `tags`. These are the built-in fields only; a team's own typed- attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see- what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user- to this account rather than the bare list, deep-link it with the path- `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of- notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).+ Fetch a single Customer Analytics account by id. Returns the full account including typed `properties`+ (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. User+ assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`.+ These are the built-in fields only; a team's own typed attributes are custom properties and are not returned+ here. Call `custom-property-definitions-list` to see what the team tracks, then+ `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than+ the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`;+ tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).feature_flag: customer-analytics-cspaccounts-summaries-list:operation: accounts_summaries_listdiff --git a/products/signals/skills/signals-scout-customer-analytics/SKILL.md b/products/signals/skills/signals-scout-customer-analytics/SKILL.mdindex 0cdcb25719c6..c5ec6536665b 100644--- a/products/signals/skills/signals-scout-customer-analytics/SKILL.md+++ b/products/signals/skills/signals-scout-customer-analytics/SKILL.md@@ -22,7 +22,7 @@ metadata:You are a focused customer-analytics scout. Customer analytics is the **Accounts** product: each row in `system.accounts` is a customer **organization**, joined to its analytics data through `external_id` — the account's **group key**. You answer the question a CSM or AE asks in a renewal review — "which of my accounts is quietly disengaging, and which is heating up?" — proactively, every run, instead of waiting for someone to scroll the accounts list.-**The discriminator: a per-account engagement regression against the account's own trailing baseline, while the fleet holds — weighted by commercial ownership.** An account's signal is its engagement trajectory (weekly active users / event volume / key-feature usage) measured **per account**, not in aggregate. The move is real when one account deviates sharply from its own recent baseline **while most accounts hold steady**, and it matters most when a human has **staked commercial ownership** on that account — an assigned `csm` / `account_executive` / `account_owner`, or a CRM link (`stripe_customer_id`, `hubspot_deal_id`, `sfdc_id`). Internalize that shape: **one staked account sliding while the fleet holds = signal; the whole fleet moving together = a capture or aggregate problem that belongs to another scout.**+**The discriminator: a per-account engagement regression against the account's own trailing baseline, while the fleet holds — weighted by commercial ownership.** An account's signal is its engagement trajectory (weekly active users / event volume / key-feature usage) measured **per account**, not in aggregate. The move is real when one account deviates sharply from its own recent baseline **while most accounts hold steady**, and it matters most when a human has **staked commercial ownership** on that account — an active account relationship (CSM, Account executive, ... in `system.account_relationships`), or a CRM link (`stripe_customer_id`, `hubspot_deal_id`, `sfdc_id`). Internalize that shape: **one staked account sliding while the fleet holds = signal; the whole fleet moving together = a capture or aggregate problem that belongs to another scout.****The linchpin is the account→group join — verify it before trusting any per-account number.** `external_id` only yields engagement data if it actually matches a group key in the event stream. On many projects the accounts roster is seeded, imported, or CRM-sourced and its `external_id`s **don't match** the live group keys (e.g. accounts keyed by an internal UUID while events are keyed by domain). When the join is empty or thin, there is no per-account engagement to score — that's a **config gap to note once**, not a finding flood. Always confirm overlap first (see Orient).@@ -94,10 +94,11 @@ The classic leading churn indicator: a named account whose engagement drops shar```sqlWITH staked AS (- SELECT external_id, name, JSONExtractString(properties,'csm') AS csm+ SELECT external_id, nameFROM system.accountsWHERE external_id != ''- AND (JSONExtractString(properties,'csm') != '' OR JSONExtractString(properties,'account_executive') != '')+ AND id IN (SELECT account_id FROM system.account_relationships+ WHERE isNull(ended_at) AND isNotNull(user_id))),ev AS (SELECT $group_1 AS gk,@@ -106,13 +107,15 @@ ev AS (count(DISTINCT if(timestamp > now() - INTERVAL 7 DAY, distinct_id, NULL)) AS wauFROM events WHERE timestamp > now() - INTERVAL 14 DAY AND $group_1 != '' GROUP BY gk)-SELECT s.name, s.csm != '' AS has_csm, e.wk, e.prev, e.wau,+SELECT s.name, e.wk, e.prev, e.wau,round((e.wk - e.prev) / nullif(e.prev,0) * 100) AS pct_changeFROM staked s INNER JOIN ev e ON e.gk = s.external_idWHERE e.prev > 200 AND e.wk < e.prev * 0.5ORDER BY e.prev DESC LIMIT 25```+Who holds the relationship (and which kind — definitions are team-defined, so don't assume "CSM" exists) comes from `system.account_relationships` joined to `system.account_relationship_definitions` on `definition_id`, filtered to `isNull(ended_at)`.+Confirm against a longer baseline (extend to 4–6 prior weeks, same weekday span) before trusting a single week — a one-week dip on an account with a lumpy cadence is not a cliff. The strong shape is a sustained drop, broad across the account's users (not one departing user — see single-threading), with the **fleet holding** over the same window.#### Dormancy onset on a staked account@@ -129,12 +132,14 @@ WITH ev AS ()SELECT a.name, e.baseline, e.recent, e.last_seenFROM system.accounts a INNER JOIN ev e ON e.gk = a.external_id-WHERE a.external_id != '' AND JSONExtractString(a.properties,'csm') != ''+WHERE a.external_id != ''+ AND a.id IN (SELECT account_id FROM system.account_relationships+ WHERE isNull(ended_at) AND isNotNull(user_id))AND e.baseline > 300 AND e.recent = 0ORDER BY e.baseline DESC LIMIT 25```-A previously-busy CSM-assigned account at zero for two weeks is the renewal-risk classic. Tune the `baseline` floor and the silence window to the project's cadence (recorded in scratchpad).+A previously-busy account with an assigned owner at zero for two weeks is the renewal-risk classic. Tune the `baseline` floor and the silence window to the project's cadence (recorded in scratchpad).#### Single-threading / champion departure@@ -150,7 +155,7 @@ Write a scratchpad entry whenever you observe something a future run should know- `pattern:customer_analytics:group-type` — _"Account grain is `$group_1` (group_type_index 1); 1,438 accounts, ~1,180 join to event group keys. external_id = group key = customer domain."_- `pattern:customer_analytics:fleet-baseline` — _"~600 accounts active in a normal week; fleet WAU steady ~X. Weekend dip is normal."_-- `watchlist:customer_analytics:account:<external_id>` — _name, assigned roles, value tier, baseline weekly volume/WAU, cadence, `last_scored` + `next_due`._+- `watchlist:customer_analytics:account:<external_id>` — _name, active relationship holders, value tier, baseline weekly volume/WAU, cadence, `last_scored` + `next_due`._- `baseline:customer_analytics:account:<external_id>` — _the learned normal: weekly event-volume / WAU band (median + MAD), so the next run scores cheaply instead of recomputing._- `dedupe:customer_analytics:account:<external_id>` — _a risk already surfaced, with the condition that should re-escalate it (a further drop, or recovery + relapse)._- `noise:customer_analytics:account:<external_id>` — _"this account is a known sandbox / migrating off / seasonal — its dips are expected."_@@ -191,7 +196,7 @@ When in doubt, refresh the baseline memory instead of filing a report. A false cDirect (read-only):-- `execute-sql` — the primary scorer. `system.accounts` for the roster (`external_id`, `name`, `properties` → `csm` / `account_executive` / `account_owner` tuples, `stripe_customer_id` / `hubspot_deal_id` / `sfdc_id` / `zendesk_id`, `tags`, `created_at`), joined to group-keyed `events` on the discovered `$group_N` index for per-account engagement.+- `execute-sql` — the primary scorer. `system.accounts` for the roster (`external_id`, `name`, `stripe_customer_id` / `hubspot_deal_id` / `sfdc_id` / `zendesk_id` extracted from `properties`, `tags`, `created_at`), joined to group-keyed `events` on the discovered `$group_N` index for per-account engagement. Commercial ownership lives in `system.account_relationships` (one row per assignment, `ended_at` NULL while active) with team-defined kinds in `system.account_relationship_definitions`; per-account active assignments are also exposed as the `system.accounts.relationships` lazy join, keyed by definition id.- `query-trends` — sanity-check a per-account or fleet-wide trend with a breakdown by the account group; confirm the fleet held while one account moved.- `query-stickiness` — per-account engagement frequency shift (days-active dropping).- `read-data-schema events` / `read-data-schema event_properties` — confirm the group key column and the events that constitute "engagement" for this project before any SQL.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex ff6834b37fd1..32c95268ca79 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -75,7 +75,7 @@"feature_flag": "customer-analytics-csp"},"accounts-create": {- "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account.",+ "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account. To assign users (CSM, account executive, ...), use `accounts-relationships-create` after creating the account.","category": "Customer analytics","feature": "customer_analytics","summary": "Create account",@@ -135,7 +135,7 @@"feature_flag": "customer-analytics-csp"},"accounts-list": {- "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields only; teams also define their own typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab.",+ "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields only; teams also define their own typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab.","category": "Customer analytics","feature": "customer_analytics","summary": "List accounts",@@ -270,7 +270,7 @@"feature_flag": "customer-analytics-csp"},"accounts-retrieve": {- "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. These are the built-in fields only; a team's own typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).",+ "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. These are the built-in fields only; a team's own typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).","category": "Customer analytics","feature": "customer_analytics","summary": "Get account",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 8f9460618d70..96cc1d1be4ee 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -75,7 +75,7 @@"feature_flag": "customer-analytics-csp"},"accounts-create": {- "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set role assignments (`csm`, `account_executive`, `account_owner`) and external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account.",+ "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account. To assign users (CSM, account executive, ...), use `accounts-relationships-create` after creating the account.","category": "Customer analytics","feature": "customer_analytics","summary": "Create account",@@ -135,7 +135,7 @@"feature_flag": "customer-analytics-csp"},"accounts-list": {- "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields only; teams also define their own typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab.",+ "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields only; teams also define their own typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab.","category": "Customer analytics","feature": "customer_analytics","summary": "List accounts",@@ -270,7 +270,7 @@"feature_flag": "customer-analytics-csp"},"accounts-retrieve": {- "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. These are the built-in fields only; a team's own typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).",+ "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. These are the built-in fields only; a team's own typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).","category": "Customer analytics","feature": "customer_analytics","summary": "Get account",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cbc139166189..fedac3d0fc10 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -143,25 +143,10 @@ export namespace Schemas {} as const;/**- * Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/export type AccountProperties = {- /** @nullable */- csm?: {- id: number;- email: string;- } | null;- /** @nullable */- account_executive?: {- id: number;- email: string;- } | null;- /** @nullable */- account_owner?: {- id: number;- email: string;- } | null;/** @nullable */stripe_customer_id?: string | null;/** @nullable */@@ -211,7 +196,7 @@ export namespace Schemas {*/external_id?: string | null;/**- * Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/properties?: AccountProperties;@@ -49353,25 +49338,10 @@ export namespace Schemas {}/**- * Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/export type PatchedAccountProperties = {- /** @nullable */- csm?: {- id: number;- email: string;- } | null;- /** @nullable */- account_executive?: {- id: number;- email: string;- } | null;- /** @nullable */- account_owner?: {- id: number;- email: string;- } | null;/** @nullable */stripe_customer_id?: string | null;/** @nullable */@@ -49407,7 +49377,7 @@ export namespace Schemas {*/external_id?: string | null;/**- * Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.+ * Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.* @nullable*/properties?: PatchedAccountProperties;@@ -76079,21 +76049,9 @@ export namespace Schemas {export type AccountsListParams = {/**- * Filter by account executive. Use 'unassigned' or an integer user id.- */- account_executive?: string;- /**- * Filter by account owner. Use 'unassigned' or an integer user id.- */- account_owner?: string;- /**- * When true, returns only accounts where CSM, account executive, and account owner are all unset.+ * When true, returns only accounts where no user actively holds any relationship.*/all_roles_unassigned?: boolean;- /**- * Filter by CSM. Use 'unassigned' for accounts with no CSM, or an integer user id.- */- csm?: string;/*** Number of results to return per page.*/diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex 6410ab6ce261..c3b3a032895f 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -114,19 +114,10 @@ export const AccountsListParams = /* @__PURE__ */ zod.object({})export const AccountsListQueryParams = /* @__PURE__ */ zod.object({- account_executive: zod- .string()- .optional()- .describe("Filter by account executive. Use 'unassigned' or an integer user id."),- account_owner: zod.string().optional().describe("Filter by account owner. Use 'unassigned' or an integer user id."),all_roles_unassigned: zod.boolean().optional()- .describe('When true, returns only accounts where CSM, account executive, and account owner are all unset.'),- csm: zod- .string()- .optional()- .describe("Filter by CSM. Use 'unassigned' for accounts with no CSM, or an integer user id."),+ .describe('When true, returns only accounts where no user actively holds any relationship.'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),ordering: zod.string().optional().describe("Sort order. Defaults to '-created_at'."),@@ -163,24 +154,6 @@ export const AccountsCreateBody = /* @__PURE__ */ zod),properties: zod.object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -192,7 +165,7 @@ export const AccountsCreateBody = /* @__PURE__ */ zod}).nullish().describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.'+ 'Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.'),tags: zod.array(zod.string())@@ -376,24 +349,6 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod),properties: zod.object({- csm: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_executive: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),- account_owner: zod- .object({- id: zod.number(),- email: zod.string(),- })- .nullish(),stripe_customer_id: zod.string().nullish(),hubspot_deal_id: zod.string().nullish(),billing_id: zod.string().nullish(),@@ -405,7 +360,7 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod}).nullish().describe(- 'Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected.'+ 'Typed account properties: external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.'),tags: zod.array(zod.string())diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.tsindex d30f03e9d573..c2c96537d196 100644--- a/services/mcp/src/tools/generated/customer_analytics.ts+++ b/services/mcp/src/tools/generated/customer_analytics.ts@@ -202,7 +202,7 @@ const accountRelationshipDefinitionsRetrieve = (): ToolBase<const AccountsCreateSchema = AccountsCreateBody.extend({properties: AccountsCreateBody.shape['properties'].describe(- 'Typed account properties. `csm`, `account_executive`, `account_owner` are role assignments — each takes `{id, email}` of an existing user. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` are optional string identifiers for the account in external systems. All fields are optional.'+ 'Typed account properties. `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` are optional string identifiers for the account in external systems. All fields are optional.'),tags: AccountsCreateBody.shape['tags'].describe('Tag names to attach to the account. Tags are created on demand if they do not already exist for the team.'@@ -315,10 +315,7 @@ const accountsList = (): ToolBase<typeof AccountsListSchema, WithPostHogUrl<Schemethod: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/accounts/`,query: {- account_executive: params.account_executive,- account_owner: params.account_owner,all_roles_unassigned: params.all_roles_unassigned,- csm: params.csm,limit: params.limit,offset: params.offset,ordering: params.ordering,@@ -418,7 +415,7 @@ const AccountsPartialUpdateSchema = AccountsPartialUpdateParams.omit({ project_i.extend(AccountsPartialUpdateBody.shape).extend({properties: AccountsPartialUpdateBody.shape['properties'].describe(- 'Typed account properties. The server replaces the `properties` object as a whole, so include any existing values you want to preserve. Supported keys: `csm`, `account_executive`, `account_owner` (each `{id, email}` of an existing user), plus `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems).'+ 'Typed account properties. The server replaces the `properties` object as a whole, so include any existing values you want to preserve. Supported keys: `stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id` (optional string identifiers for external systems). To assign users (CSM, account executive, ...), use `accounts-relationships-create` instead.'),tags: AccountsPartialUpdateBody.shape['tags'].describe('Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not a delta. Tags are created on demand if they do not already exist for the team.'