Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(growth): trigger account audits from workflows (#108224)

Oliver Browne5871475311c8
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 3bb25603c419..98070d1d2426 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -56,6 +56,7 @@ rules:
(?x)(
AccessControl
|Account
+ |AccountAuditAdmission
|AccountChannelSummary
|AccountRelationship
|AccountRelationshipControl
@@ -521,6 +522,7 @@ rules:
(?x)(
AccessControl
|Account
+ |AccountAuditAdmission
|AccountChannelSummary
|AccountRelationship
|AccountRelationshipControl
@@ -1205,7 +1207,8 @@ rules:
metavariable: $MODEL
regex: |
(?x)(
- CommunitySkillVote
+ AccountAuditCredential
+ |CommunitySkillVote
|DashboardPrivilege
|GitHubInstallRequest
|PersonalAPIKey
@@ -1262,7 +1265,8 @@ rules:
metavariable: $MODEL
regex: |
(?x)(
- CommunitySkillVote
+ AccountAuditCredential
+ |CommunitySkillVote
|DashboardPrivilege
|GitHubInstallRequest
|PersonalAPIKey
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index 401af67ff2b9..14e97d1e52bf 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -222,6 +222,15 @@ worker mints, it also injects `AI_GATEWAY_PRODUCT` and `AI_GATEWAY_AI_STAGE`, na
the product the token is pinned to, and the agent routes on those in preference to
what it derives itself. Both are reserved keys: a sandbox environment cannot set them.
+Account audit runs use the reserved `account_audit` origin and AI product, and must
+carry the server-set `internal` flag before they can mint a token. Add
+`account_audit` to `SANDBOX_AI_GATEWAY_PRODUCTS` to route them to the Go gateway.
+Their Python gateway fallback uses `background_agents`. Signup onboarding stays
+on `onboarding` and cannot mint these cost-tracking tokens. A periodic completion task
+waits three minutes for cost accounting before reporting the audit result. Audits use an
+internal `CUSTOM` sandbox environment with no extra allowed domains. Each new
+audit reasserts this policy; only the platform service allowlist stays reachable.
+
When a run lands on the Python gateway unexpectedly, check those two variables first.
Their absence means no token was minted, so the agent falls back to deriving the
product from the task run it fetches at boot, which is the path that fails quietly.
diff --git a/frontend/package.json b/frontend/package.json
index 0d735c32c290..7dae8707f095 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -83,6 +83,7 @@
"@posthog/icons": "catalog:",
"@posthog/llm-normalizer": "workspace:*",
"@posthog/products-access-control": "workspace:*",
+ "@posthog/products-account-audits": "workspace:*",
"@posthog/products-actions": "workspace:*",
"@posthog/products-ai-observability": "workspace:*",
"@posthog/products-ai-training": "workspace:*",
diff --git a/packages/agent/packages/agent/src/utils/gateway.test.ts b/packages/agent/packages/agent/src/utils/gateway.test.ts
index 541d0159f3e2..0b3eab6edd8a 100644
--- a/packages/agent/packages/agent/src/utils/gateway.test.ts
+++ b/packages/agent/packages/agent/src/utils/gateway.test.ts
@@ -98,6 +98,16 @@ describe("resolveGatewayProduct", () => {
originProduct: "review_hog",
expected: "posthog_code",
},
+ {
+ isInternal: true,
+ originProduct: "account_audit",
+ expected: "account_audit",
+ },
+ {
+ isInternal: false,
+ originProduct: "account_audit",
+ expected: "posthog_code",
+ },
{
isInternal: true,
originProduct: "loop",
@@ -520,47 +530,56 @@ describe("resolveGatewayTarget", () => {
});
});
- it("keeps the review_hog legacy leg on the background_agents slug", () => {
- expect(
- resolveGatewayTarget({
- product: "review_hog",
+ it.each(["review_hog", "account_audit"] as const)(
+ "keeps the %s legacy leg on the background_agents slug",
+ (product) => {
+ expect(
+ resolveGatewayTarget({
+ product,
+ aiStage: "validation-c1",
+ posthogHost: PY_HOST,
+ env: {},
+ }),
+ ).toEqual({
+ baseUrl: "https://gateway.us.posthog.com/background_agents",
+ isAiGateway: false,
+ aiProduct: product,
aiStage: "validation-c1",
- posthogHost: PY_HOST,
- env: {},
- }),
- ).toEqual({
- baseUrl: "https://gateway.us.posthog.com/background_agents",
- isAiGateway: false,
- aiProduct: "review_hog",
- aiStage: "validation-c1",
- });
- });
+ });
+ },
+ );
- it("keeps the legacy override on an LLM_GATEWAY_URL base too", () => {
- expect(
- resolveGatewayTarget({
- product: "review_hog",
- posthogHost: PY_HOST,
- env: { LLM_GATEWAY_URL: "https://gateway.dev.posthog.dev" },
- }).baseUrl,
- ).toBe("https://gateway.dev.posthog.dev/background_agents");
- });
+ it.each(["review_hog", "account_audit"] as const)(
+ "keeps the %s legacy override on an LLM_GATEWAY_URL base too",
+ (product) => {
+ expect(
+ resolveGatewayTarget({
+ product,
+ posthogHost: PY_HOST,
+ env: { LLM_GATEWAY_URL: "https://gateway.dev.posthog.dev" },
+ }).baseUrl,
+ ).toBe("https://gateway.dev.posthog.dev/background_agents");
+ },
+ );
- it("routes review_hog to the Go gateway slugless once listed", () => {
- expect(
- resolveGatewayTarget({
- product: "review_hog",
+ it.each(["review_hog", "account_audit"] as const)(
+ "routes %s to the Go gateway slugless once listed",
+ (product) => {
+ expect(
+ resolveGatewayTarget({
+ product,
+ aiStage: "validation-c1",
+ posthogHost: PY_HOST,
+ env: { AI_GATEWAY_URL: GO, AI_GATEWAY_PRODUCTS: product },
+ }),
+ ).toEqual({
+ baseUrl: GO,
+ isAiGateway: true,
+ aiProduct: product,
aiStage: "validation-c1",
- posthogHost: PY_HOST,
- env: { AI_GATEWAY_URL: GO, AI_GATEWAY_PRODUCTS: "review_hog" },
- }),
- ).toEqual({
- baseUrl: GO,
- isAiGateway: true,
- aiProduct: "review_hog",
- aiStage: "validation-c1",
- });
- });
+ });
+ },
+ );
it("honours an LLM_GATEWAY_URL override on the unrouted path", () => {
expect(
diff --git a/packages/agent/packages/agent/src/utils/gateway.ts b/packages/agent/packages/agent/src/utils/gateway.ts
index bb31df65451a..6917babd86b5 100644
--- a/packages/agent/packages/agent/src/utils/gateway.ts
+++ b/packages/agent/packages/agent/src/utils/gateway.ts
@@ -8,6 +8,7 @@ export type GatewayProduct =
| "workflows"
| "posthog_ai"
| "conversations"
+ | "account_audit"
| "onboarding"
| "review_hog";
@@ -25,6 +26,7 @@ export function resolveGatewayProduct({
loop: "posthog_code",
metrics_import: "posthog_ai",
onboarding: "onboarding",
+ account_audit: "account_audit",
posthog_ai: "posthog_ai",
review_hog: "review_hog",
scout_suggestions: "signals",
@@ -40,7 +42,10 @@ export function resolveGatewayProduct({
const mapped = originProductToGatewayProductMap[originProduct];
// Stored rows may carry a caller-set review_hog origin predating its
// reservation; only the server-stamped `internal` flag admits the mintable product.
- if (mapped === "review_hog" && !isInternal) {
+ if (
+ (mapped === "review_hog" || originProduct === "account_audit") &&
+ !isInternal
+ ) {
return "posthog_code";
}
return mapped;
@@ -51,13 +56,13 @@ export function resolveGatewayProduct({
return "posthog_code";
}
-// The legacy gateway's review_hog product is API-key-only, so sandbox OAuth
-// tokens 403 on that slug; the legacy leg, including the mint-failure
-// fallback, uses background_agents.
+// The legacy gateway accepts sandbox OAuth under background_agents; review_hog
+// is API-key-only there, and account_audit has no legacy product config.
const LEGACY_PRODUCT_OVERRIDES: Partial<
Record<GatewayProduct, GatewayProduct>
> = {
review_hog: "background_agents",
+ account_audit: "background_agents",
};
function legacyProduct(product: GatewayProduct): GatewayProduct {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 921066682e06..48f7d8bd8d85 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -653,6 +653,9 @@ importers:
'@posthog/products-access-control':
specifier: workspace:*
version: link:../products/access_control
+ '@posthog/products-account-audits':
+ specifier: workspace:*
+ version: link:../products/account_audits
'@posthog/products-actions':
specifier: workspace:*
version: link:../products/actions
@@ -2335,6 +2338,8 @@ importers:
products/access_control: {}
+ products/account_audits: {}
+
products/actions:
dependencies:
'@posthog/brand':
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index 5b4a69252bdb..9d7cf79cee74 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -26,7 +26,7 @@ from posthog.ingress.verify.sns_signature import verify_sns_message
logger = structlog.get_logger(__name__)
-SignedInput = Literal["body", "v0_timestamp_body"]
+SignedInput = Literal["body", "v0_timestamp_body", "id_timestamp_body"]
SignatureEncoding = Literal["hex", "base64"]
# SHA-1 is on this list because one provider signs with it, not because it is a choice worth
# making for a new one. Reach for `HmacSha256` unless the provider leaves no option.
@@ -73,20 +73,20 @@ def header_value(headers: Mapping[str, str], name: str) -> str | None:
def hmac_signature(
- secret: str,
+ secret: str | bytes,
signed: bytes,
*,
digest: HmacDigest = "sha256",
encoding: SignatureEncoding = "hex",
prefix: str = "",
) -> str:
- computed = hmac.digest(secret.encode("utf-8"), signed, digest)
+ computed = hmac.digest(secret.encode("utf-8") if isinstance(secret, str) else secret, signed, digest)
encoded = base64.b64encode(computed).decode("ascii") if encoding == "base64" else computed.hex()
return prefix + encoded
def hmac_sha256_signature(
- secret: str,
+ secret: str | bytes,
signed: bytes,
*,
encoding: SignatureEncoding = "hex",
@@ -125,13 +125,14 @@ class HmacSignature:
to anything but the default.
"""
- secret_getter: Callable[[], str | None]
+ secret_getter: Callable[[], str | bytes | None]
signature_header: str
prefix: str = ""
digest: HmacDigest = "sha256"
encoding: SignatureEncoding = "hex"
signed_input: SignedInput = "body"
timestamp_header: str | None = None
+ delivery_id_header: str | None = None
timestamp_max_age_seconds: int = 300
timestamp_max_future_seconds: int = 300
# Cheap shape gate run before the HMAC, so a probe cannot drive digest CPU.
@@ -144,14 +145,16 @@ class HmacSignature:
return False
return -self.timestamp_max_future_seconds <= age_seconds <= self.timestamp_max_age_seconds
- def _signed_bytes(self, body: bytes, timestamp: str | None) -> bytes:
+ def _signed_bytes(self, body: bytes, timestamp: str | None, delivery_id: str | None = None) -> bytes:
if self.signed_input == "v0_timestamp_body" and timestamp is not None:
# Assembled as bytes rather than through a decoded string, so a body that is
# not valid UTF-8 fails the comparison instead of raising.
return b"v0:" + timestamp.encode("utf-8") + b":" + body
+ if self.signed_input == "id_timestamp_body" and timestamp is not None and delivery_id is not None:
+ return delivery_id.encode("utf-8") + b"." + timestamp.encode("utf-8") + b"." + body
return body
- def _expected_signature(self, secret: str, signed: bytes) -> str:
+ def _expected_signature(self, secret: str | bytes, signed: bytes) -> str:
return hmac_signature(secret, signed, digest=self.digest, encoding=self.encoding, prefix=self.prefix)
def _headers_fail(self, headers: Mapping[str, str]) -> bool:
@@ -160,6 +163,12 @@ class HmacSignature:
return True
if self.signature_pattern is not None and not self.signature_pattern.match(provided):
return True
+ if self.signed_input == "id_timestamp_body" and (
+ self.delivery_id_header is None
+ or not header_value(headers, self.delivery_id_header)
+ or self.timestamp_header is None
+ ):
+ return True
if self.timestamp_header is None:
return False
# Freshness needs only the clock, so a malformed or stale timestamp costs no body read either.
@@ -200,7 +209,8 @@ class HmacSignature:
timestamp = header_value(headers, self.timestamp_header) if self.timestamp_header is not None else None
- expected = self._expected_signature(secret, self._signed_bytes(body, timestamp))
+ delivery_id = header_value(headers, self.delivery_id_header) if self.delivery_id_header is not None else None
+ expected = self._expected_signature(secret, self._signed_bytes(body, timestamp, delivery_id))
if signatures_match(expected, provided):
return VerificationOutcome.VERIFIED
return VerificationOutcome.INVALID
diff --git a/posthog/ph_client.py b/posthog/ph_client.py
index 7adbf526f536..5020a58f3a36 100644
--- a/posthog/ph_client.py
+++ b/posthog/ph_client.py
@@ -148,11 +148,14 @@ class ScopedCapture:
@contextmanager
-def ph_scoped_capture(region: str = "US", *, raise_on_error: bool = False) -> Iterator[ScopedCapture]:
+def ph_scoped_capture(
+ region: str = "US", *, raise_on_error: bool = False, event_region: str | None = None
+) -> Iterator[ScopedCapture]:
"""Use this instead of posthoganalytics.capture() in Celery tasks — the global
client's background flush may never run before the worker exits, silently losing events.
This creates a dedicated client and flushes on context-manager exit.
Pass the deployment region when events must stay in their regional project.
+ Set event_region when the event's region differs from its destination.
In a long-lived worker (e.g. Temporal activities), prefer `ph_background_capture` —
the client setup and synchronous flush here add seconds of blocking per call.
@@ -168,6 +171,8 @@ def ph_scoped_capture(region: str = "US", *, raise_on_error: bool = False) -> It
errors.append(error)
ph_client = get_client(region, on_error=on_error) if raise_on_error else get_client(region)
+ if ph_client and event_region is not None:
+ ph_client.super_properties["region"] = event_region
# Flush even when the caller's block raises — events already captured
# before the exception shouldn't be dropped with the buffer.
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 8cf38cddc431..914e68065b93 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -43,6 +43,7 @@ AXES_HTTP_RESPONSE_CODE = 403
# TODO: Automatically generate these like we do for the frontend
# NOTE: Add these definitions here and on `tach.toml`
PRODUCTS_APPS = [
+ "products.account_audits.backend.apps.AccountAuditsConfig",
"products.ai_training.backend.apps.AiTrainingConfig",
"products.ml_inference.backend.apps.MlInferenceConfig",
"products.analytics_platform.backend.apps.AnalyticsPlatformConfig",
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 45c219de4fe8..fef33dcdb036 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -76,6 +76,7 @@ from posthog.tasks.uploaded_media import sweep_abandoned_media_uploads_task
from posthog.tasks.wizard_blocklist import revoke_blocklisted_gateway_credentials
from posthog.utils import get_crontab, get_instance_region
+from products.account_audits.backend.facade.tasks import reconcile_account_audits
from products.aeo.backend.facade.tasks import run_aeo_citation_checks_task
from products.ai_training.backend.facade.api import privacy_enabled
from products.ai_training.backend.facade.tasks import process_ai_training_privacy_requests
@@ -265,6 +266,9 @@ def add_periodic_task_with_expiry(
def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
+ add_periodic_task_with_expiry(
+ sender, crontab(minute="*"), reconcile_account_audits.s(), name="reconcile-account-audits"
+ )
if privacy_enabled():
sender.add_periodic_task(30.0, process_ai_training_privacy_requests.s(), name="process-ai-training-privacy")
# Short-interval heartbeat tasks (<60s) use intervals since cron minimum is 1 minute.
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 6f6fa9c6a201..2004710fb1ff 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -5117,6 +5117,22 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
},
)
+ _create_event(
+ event="$ai_generation",
+ team=analytics_team,
+ distinct_id="user_account_audit",
+ timestamp=period.start + relativedelta(hours=4),
+ properties={
+ "team_id": self.org_1_team_1.id,
+ "$ai_trace_id": "trace_account_audit",
+ "$ai_total_cost_usd": 5.0,
+ "$ai_billable": True,
+ "ai_product": "posthog_code",
+ "task_origin_product": "account_audit",
+ "$group_1": "https://us.posthog.com",
+ },
+ )
+
flush_persons_and_events()
posthog_code_result = get_teams_with_posthog_code_credits_used_in_period(period.start, period.end)
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 92d15ecf9b9c..e14855309bd4 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -1780,7 +1780,7 @@ POSTHOG_AI_PRODUCTS = [
]
# ai_product values billed as PostHog Desktop credits.
-UNBILLED_TASK_ORIGIN_PRODUCTS = ("task_analysis",)
+UNBILLED_TASK_ORIGIN_PRODUCTS = ("task_analysis", "account_audit")
POSTHOG_CODE_AI_PRODUCTS = ["posthog_code"]
diff --git a/posthog/test/test_ph_client.py b/posthog/test/test_ph_client.py
index 9aa7451108dc..53dc135667a6 100644
--- a/posthog/test/test_ph_client.py
+++ b/posthog/test/test_ph_client.py
@@ -110,6 +110,16 @@ class TestScopedCaptureFlush(SimpleTestCase):
client.capture.assert_called_once_with(distinct_id="person", event="event")
client.shutdown.assert_called_once()
+ @override_settings(CLOUD_DEPLOYMENT="EU")
+ def test_cross_region_capture_preserves_the_event_region(self) -> None:
+ before_send = MagicMock(side_effect=lambda event: event)
+ client = get_client("US", send=False, disabled=False, enable_local_evaluation=False, before_send=before_send)
+ with patch("posthog.ph_client.get_client", return_value=client) as make_client:
+ with ph_scoped_capture(region="US", event_region="EU") as capture:
+ capture(distinct_id="person", event="account_audit_finished")
+ make_client.assert_called_once_with("US")
+ self.assertEqual(before_send.call_args.args[0]["properties"]["region"], "EU")
+
class TestGetClientTestGuard(SimpleTestCase):
def test_client_is_disabled_under_test_settings(self) -> None:
diff --git a/products/account_audits/__init__.py b/products/account_audits/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/account_audits/backend/__init__.py b/products/account_audits/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/account_audits/backend/admin.py b/products/account_audits/backend/admin.py
new file mode 100644
index 000000000000..2626d4a23987
--- /dev/null
+++ b/products/account_audits/backend/admin.py
@@ -0,0 +1,65 @@
+import base64
+import secrets
+
+from django import forms
+from django.contrib import admin
+from django.http import HttpRequest, HttpResponse
+from django.template.response import TemplateResponse
+from django.urls import reverse
+
+from posthog.utils import absolute_uri
+
+from products.account_audits.backend.models import AccountAuditCredential
+
+
+class AccountAuditCredentialForm(forms.ModelForm):
+ class Meta:
+ model = AccountAuditCredential
+ fields = ("is_active",)
+ help_texts = {
+ "is_active": "Disable to revoke access. To rotate, configure the workflow with a new credential before disabling this one.",
+ }
+
+
[email protected](AccountAuditCredential)
+class AccountAuditCredentialAdmin(admin.ModelAdmin):
+ form = AccountAuditCredentialForm
+ readonly_fields = ("public_key_id", "created_by", "created_at")
+ list_display = ("public_key_id", "created_by", "is_active", "created_at")
+ list_filter = ("is_active",)
+ list_select_related = ("created_by",)
+ search_fields = ("public_key_id", "created_by__email")
+ actions = None
+
+ def get_fields(self, request: HttpRequest, obj: AccountAuditCredential | None = None) -> tuple[str, ...]:
+ if obj is None:
+ return ("is_active",)
+ return ("public_key_id", "created_by", "is_active", "created_at")
+
+ def has_delete_permission(self, request: HttpRequest, obj: AccountAuditCredential | None = None) -> bool:
+ return False
+
+ def save_model(
+ self, request: HttpRequest, obj: AccountAuditCredential, form: forms.ModelForm, change: bool
+ ) -> None:
+ if not change:
+ obj.created_by_id = request.user.pk
+ obj.signing_secret = f"whsec_{base64.b64encode(secrets.token_bytes(32)).decode()}"
+ super().save_model(request, obj, form, change)
+
+ def response_add(
+ self, request: HttpRequest, obj: AccountAuditCredential, post_url_continue: str | None = None
+ ) -> HttpResponse:
+ return TemplateResponse(
+ request,
+ "admin/account_audits/account_audit_credential_created.html",
+ {
+ **self.admin_site.each_context(request),
+ "title": "Account audit credential created",
+ "opts": self.model._meta,
+ "key_id": obj.public_key_id,
+ "signing_secret": obj.signing_secret,
+ "credential_url": reverse("admin:account_audits_accountauditcredential_change", args=[obj.pk]),
+ "api_url": absolute_uri(reverse("account_audits-start")),
+ },
+ )
diff --git a/products/account_audits/backend/apps.py b/products/account_audits/backend/apps.py
new file mode 100644
index 000000000000..6528662209b2
--- /dev/null
+++ b/products/account_audits/backend/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class AccountAuditsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.account_audits.backend"
+ label = "account_audits"
diff --git a/products/account_audits/backend/facade/__init__.py b/products/account_audits/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/account_audits/backend/facade/api.py b/products/account_audits/backend/facade/api.py
new file mode 100644
index 000000000000..458bad5f8ed8
--- /dev/null
+++ b/products/account_audits/backend/facade/api.py
@@ -0,0 +1,12 @@
+from uuid import UUID
+
+from products.account_audits.backend.facade.contracts import AccountAuditRequest, AccountAuditResult
+from products.account_audits.backend.logic import service
+
+
+def signing_secret_for(public_key_id: UUID) -> str | None:
+ return service.AccountAuditService.signing_secret_for(public_key_id)
+
+
+def start(payload: AccountAuditRequest, public_key_id: UUID, webhook_id: str) -> AccountAuditResult:
+ return service.AccountAuditService.start(payload, public_key_id, webhook_id)
diff --git a/products/account_audits/backend/facade/contracts.py b/products/account_audits/backend/facade/contracts.py
new file mode 100644
index 000000000000..c67213f3ba18
--- /dev/null
+++ b/products/account_audits/backend/facade/contracts.py
@@ -0,0 +1,29 @@
+from typing import Literal
+from uuid import UUID
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class AccountAuditRequest:
+ organization_id: UUID
+ team_id: int | None = None
+ reason: str
+ skill_project: int
+ skill_name: str
+
+
+@frozen
+class AccountAuditResult:
+ status: Literal[
+ "accepted",
+ "skipped",
+ "invalid",
+ "skill_unavailable",
+ "unauthorized",
+ "forbidden",
+ "conflict",
+ "unavailable",
+ ]
+ task_run_id: UUID | None = None
+ team_id: int | None = None
diff --git a/products/account_audits/backend/facade/tasks.py b/products/account_audits/backend/facade/tasks.py
new file mode 100644
index 000000000000..c3cd5545a00d
--- /dev/null
+++ b/products/account_audits/backend/facade/tasks.py
@@ -0,0 +1,3 @@
+from products.account_audits.backend.tasks.tasks import reconcile_account_audits
+
+__all__ = ["reconcile_account_audits"]
diff --git a/products/account_audits/backend/logic/__init__.py b/products/account_audits/backend/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/account_audits/backend/logic/execution.py b/products/account_audits/backend/logic/execution.py
new file mode 100644
index 000000000000..2def9c4ab7d4
--- /dev/null
+++ b/products/account_audits/backend/logic/execution.py
@@ -0,0 +1,127 @@
+import logging
+from datetime import timedelta
+from uuid import UUID
+
+from django.utils import timezone
+
+from pydantic import BaseModel, Field
+
+from posthog.event_usage import groups
+from posthog.models import Team
+from posthog.models.scoping.manager import TeamScopeError
+from posthog.ph_client import ph_scoped_capture
+from posthog.utils import absolute_uri, get_instance_region
+
+from products.account_audits.backend.models import AccountAuditAdmission
+from products.notebooks.backend.facade import api as notebooks_facade
+from products.notebooks.backend.facade.content import convert_notebook_content_to_markdown
+from products.skills.backend.facade.api import SkillPrompt
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.billing import get_task_run_cost
+
+logger = logging.getLogger(__name__)
+COMPLETION_GRACE = timedelta(minutes=3)
+
+
+class AccountAuditOutput(BaseModel):
+ notebook_short_id: str = Field(min_length=1)
+
+
+def create_audit_task(*, team_id: int, user_id: int, skill: SkillPrompt, notebook_short_id: str) -> UUID:
+ # The sandbox policy admits platform services; audit skills need no other network access.
+ environment_id = tasks_facade.upsert_internal_sandbox_env(
+ team_id,
+ "ACCOUNT_AUDIT",
+ tasks_facade.SandboxNetworkAccessLevel.CUSTOM,
+ allowed_domains=[],
+ include_default_domains=False,
+ )
+ created = tasks_facade.create_and_run_task(
+ team=Team.objects.get(id=team_id),
+ title="Account audit",
+ description=(
+ f"{skill.body}\n\nThe audited project ID is {team_id}. "
+ f"Use this project for every query. Save the audit to the existing notebook {notebook_short_id} "
+ "with PostHog MCP, even if the skill asks you to create a notebook. "
+ "Read the saved notebook before you return its short ID as notebook_short_id."
+ ),
+ origin_product=tasks_facade.TaskOriginProduct.ACCOUNT_AUDIT,
+ user_id=user_id,
+ repository=None,
+ create_pr=False,
+ internal=True,
+ sandbox_environment_id=str(environment_id),
+ posthog_mcp_scopes=["user:read", "query:read", "insight:read", "notebook:read", "notebook:write"],
+ model="claude-sonnet-5",
+ output_schema=AccountAuditOutput,
+ sandbox_timeout_seconds=3 * 60 * 60,
+ extra_run_state={"audit_skill_version": skill.version},
+ )
+ if created.latest_run is None:
+ raise RuntimeError("Account audit task was created without a run")
+ return created.latest_run.id
+
+
+def finish_account_audit(*, team_id: int, task_run_id: UUID) -> None:
+ try:
+ admission = (
+ AccountAuditAdmission.objects.for_team(team_id)
+ .filter(task_run_id=task_run_id, finalized_at__isnull=True)
+ .first()
+ )
+ except TeamScopeError:
+ # A queued completion can arrive after tenant deletion cascades the admission.
+ return
+ if admission is None:
+ return
+ run = tasks_facade.get_task_run(str(task_run_id), team_id=team_id)
+ if run is None:
+ AccountAuditAdmission.objects.for_team(team_id).filter(pk=admission.pk).update(finalized_at=timezone.now())
+ return
+ if not run.is_terminal:
+ return
+ if run.status == tasks_facade.TaskRunStatus.COMPLETED:
+ # Gateway callbacks can arrive after completion, even when the pending list is empty.
+ if timezone.now() < (run.completed_at or run.updated_at or admission.created_at) + COMPLETION_GRACE:
+ return
+ notebook_id = admission.notebook_short_id
+ notebook = notebooks_facade.get_notebook(team_id, notebook_id)
+ valid = (
+ run.task_origin_product == tasks_facade.TaskOriginProduct.ACCOUNT_AUDIT
+ and (run.output or {}).get("notebook_short_id") == notebook_id
+ and notebook is not None
+ and run.created_by_id is not None
+ and notebook.created_by_id == run.created_by_id
+ and any(
+ line.strip() and not line.lstrip().startswith("#")
+ for line in convert_notebook_content_to_markdown(notebook.content).splitlines()
+ )
+ )
+ team = (
+ Team.objects.select_related("organization")
+ .filter(id=team_id, organization_id=admission.organization_id)
+ .first()
+ )
+ if valid and run.created_by_distinct_id and team and team.organization.is_ai_data_processing_approved:
+ cost = get_task_run_cost(run_id=task_run_id, team_id=team_id)
+ with ph_scoped_capture(
+ region="US", event_region=get_instance_region() or "US", raise_on_error=True
+ ) as capture:
+ capture(
+ distinct_id=run.created_by_distinct_id,
+ event="account_audit_finished",
+ properties={
+ "organization_id": str(admission.organization_id),
+ "team_id": team_id,
+ "notebook_url": absolute_uri(f"/project/{team_id}/notebooks/{notebook_id}"),
+ "reason": admission.reason,
+ "skill_project": admission.skill_project,
+ "skill_name": admission.skill_name,
+ "token_cost_cents": cost.token_cost,
+ "$insert_id": f"account-audit-finished-{task_run_id}",
+ },
+ groups=groups(team.organization, team),
+ )
+ else:
+ logger.warning("account_audit_result_rejected", extra={"task_run_id": str(task_run_id)})
+ AccountAuditAdmission.objects.for_team(team_id).filter(pk=admission.pk).update(finalized_at=timezone.now())
diff --git a/products/account_audits/backend/logic/service.py b/products/account_audits/backend/logic/service.py
new file mode 100644
index 000000000000..504153890e40
--- /dev/null
+++ b/products/account_audits/backend/logic/service.py
@@ -0,0 +1,150 @@
+import logging
+from datetime import timedelta
+from uuid import UUID
+
+from django.db import connection, transaction
+from django.db.models import Count, F, FilteredRelation, Q
+from django.utils import timezone
+
+from posthog.event_usage import groups
+from posthog.models import Organization, Team
+from posthog.ph_client import ph_scoped_capture
+from posthog.utils import get_instance_region
+
+from products.account_audits.backend.facade.contracts import AccountAuditRequest, AccountAuditResult
+from products.account_audits.backend.logic.execution import create_audit_task
+from products.account_audits.backend.models import AccountAuditAdmission, AccountAuditCredential
+from products.notebooks.backend.facade import api as notebooks_facade
+from products.signals.backend.facade.api import resolve_audit_actor_for_team
+from products.skills.backend.facade.api import get_skill_prompt_for_audit
+
+PROJECT_ACTIVITY_WINDOW = timedelta(days=30)
+logger = logging.getLogger(__name__)
+
+
+class AccountAuditService:
+ @staticmethod
+ def signing_secret_for(public_key_id: UUID) -> str | None:
+ return (
+ AccountAuditCredential.objects.filter(public_key_id=public_key_id, is_active=True)
+ .values_list("signing_secret", flat=True)
+ .first()
+ )
+
+ @classmethod
+ def start(cls, payload: AccountAuditRequest, public_key_id: UUID, webhook_id: str) -> AccountAuditResult:
+ credential = AccountAuditCredential.objects.filter(public_key_id=public_key_id, is_active=True).first()
+ if credential is None:
+ return AccountAuditResult(status="unauthorized")
+ if (get_instance_region() or "US") not in ("US", "EU"):
+ return AccountAuditResult(status="unavailable")
+ organization = Organization.objects.filter(id=payload.organization_id).first()
+ if organization is None:
+ return AccountAuditResult(status="forbidden")
+ try:
+ if not organization.is_ai_data_processing_approved:
+ team_id = cls._resolve_team_id(payload)
+ if team_id is None:
+ return AccountAuditResult(status="invalid")
+ with ph_scoped_capture(
+ region="US", event_region=get_instance_region() or "US", raise_on_error=True
+ ) as capture:
+ capture(
+ distinct_id=str(organization.id),
+ event="audit_not_run",
+ properties={
+ "organization_id": str(organization.id),
+ "team_id": team_id,
+ "reason": "no ai opt in",
+ "audit_reason": payload.reason,
+ "skill_project": payload.skill_project,
+ "skill_name": payload.skill_name,
+ "$insert_id": f"audit-not-run-{credential.public_key_id}-{webhook_id}",
+ },
+ groups=groups(organization, Team.objects.get(id=team_id)),
+ )
+ return AccountAuditResult(status="skipped")
+ return cls._admit(payload, credential, webhook_id)
+ except Exception:
+ logger.exception("account_audit_creation_failed")
+ return AccountAuditResult(status="unavailable")
+
+ @classmethod
+ def _admit(
+ cls, payload: AccountAuditRequest, credential: AccountAuditCredential, webhook_id: str
+ ) -> AccountAuditResult:
+ with transaction.atomic():
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",
+ [f"account-audit-delivery:{credential.id}:{webhook_id}"],
+ )
+ existing = (
+ AccountAuditAdmission.objects.unscoped().filter(credential=credential, webhook_id=webhook_id).first()
+ )
+ if existing is not None:
+ if (
+ existing.organization_id != payload.organization_id
+ or (payload.team_id is not None and existing.team_id != payload.team_id)
+ or existing.reason != payload.reason
+ or existing.skill_project != payload.skill_project
+ or existing.skill_name != payload.skill_name
+ ):
+ return AccountAuditResult(status="conflict")
+ return AccountAuditResult(status="accepted", task_run_id=existing.task_run_id, team_id=existing.team_id)
+ team_id = cls._resolve_team_id(payload)
+ if team_id is None:
+ return AccountAuditResult(status="invalid")
+ actor_id = resolve_audit_actor_for_team(team_id)
+ if actor_id is None:
+ return AccountAuditResult(status="forbidden")
+ skill = get_skill_prompt_for_audit(team_id=payload.skill_project, skill_name=payload.skill_name)
+ if skill is None or not skill.body.strip():
+ return AccountAuditResult(status="skill_unavailable")
+ notebook = notebooks_facade.create_notebook(
+ team_id,
+ title="Account audit",
+ content={"type": "doc", "content": []},
+ text_content="",
+ created_by_id=actor_id,
+ last_modified_by_id=actor_id,
+ visibility="internal",
+ creation_source="server",
+ )
+ run_id = create_audit_task(
+ team_id=team_id, user_id=actor_id, skill=skill, notebook_short_id=notebook.short_id
+ )
+ AccountAuditAdmission.objects.for_team(team_id).create(
+ credential=credential,
+ webhook_id=webhook_id,
+ organization_id=payload.organization_id,
+ team_id=team_id,
+ reason=payload.reason,
+ skill_project=payload.skill_project,
+ skill_name=payload.skill_name,
+ task_run_id=run_id,
+ notebook_short_id=notebook.short_id,
+ )
+ return AccountAuditResult(status="accepted", task_run_id=run_id, team_id=team_id)
+
+ @staticmethod
+ def _resolve_team_id(request: AccountAuditRequest) -> int | None:
+ teams = Team.objects.filter(organization_id=request.organization_id).exclude(project__is_pending_deletion=True)
+ team_id = request.team_id
+ if team_id is not None:
+ # Admission reads canonicalize a child environment ID to its parent, so a child ID could never finalize.
+ return teams.filter(id=team_id, parent_team__isnull=True).values_list("id", flat=True).first()
+ return (
+ teams.filter(id=F("project_id"), parent_team__isnull=True, is_demo=False)
+ .alias(
+ recent_views=FilteredRelation(
+ "filesystemviewlog",
+ condition=Q(filesystemviewlog__viewed_at__gte=timezone.now() - PROJECT_ACTIVITY_WINDOW),
+ )
+ )
+ .values("id", "project__created_at")
+ .annotate(recent_active_users=Count("recent_views__user_id", distinct=True))
+ .order_by("-recent_active_users", "project__created_at", "id")
+ .values_list("id", flat=True)
+ .first()
+ )
diff --git a/products/account_audits/backend/migrations/0001_initial.py b/products/account_audits/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..7827f8e6d847
--- /dev/null
+++ b/products/account_audits/backend/migrations/0001_initial.py
@@ -0,0 +1,110 @@
+# Generated by Django 5.2.18 on 2026-10-13 09:38
+
+import uuid
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("posthog", "1396_events_retention_config"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="AccountAuditCredential",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "public_key_id",
+ models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
+ ),
+ (
+ "signing_secret",
+ posthog.helpers.encrypted_fields.EncryptedTextField(),
+ ),
+ ("is_active", models.BooleanField(default=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AccountAuditAdmission",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("webhook_id", models.CharField(max_length=255)),
+ ("organization_id", models.UUIDField()),
+ ("reason", models.CharField(db_default="", default="", max_length=500)),
+ ("skill_project", models.BigIntegerField(null=True)),
+ (
+ "skill_name",
+ models.CharField(
+ db_default="account-audit",
+ default="account-audit",
+ max_length=64,
+ ),
+ ),
+ ("task_run_id", models.UUIDField(unique=True)),
+ ("notebook_short_id", models.CharField(max_length=12)),
+ ("finalized_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "credential",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ related_name="admissions",
+ to="account_audits.accountauditcredential",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("credential", "webhook_id"),
+ name="account_audit_admission_delivery",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/account_audits/backend/migrations/__init__.py b/products/account_audits/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/account_audits/backend/migrations/max_migration.txt b/products/account_audits/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/account_audits/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/account_audits/backend/models.py b/products/account_audits/backend/models.py
new file mode 100644
index 000000000000..84499c6953f6
--- /dev/null
+++ b/products/account_audits/backend/models.py
@@ -0,0 +1,35 @@
+from uuid import uuid4
+
+from django.db import models
+
+from posthog.helpers.encrypted_fields import EncryptedTextField
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+
+
+class AccountAuditCredential(models.Model):
+ public_key_id = models.UUIDField(default=uuid4, unique=True, editable=False)
+ signing_secret = EncryptedTextField()
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, db_constraint=False, related_name="+"
+ )
+ is_active = models.BooleanField(default=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+
+class AccountAuditAdmission(TeamScopedRootMixin):
+ credential = models.ForeignKey(AccountAuditCredential, on_delete=models.PROTECT, related_name="admissions")
+ webhook_id = models.CharField(max_length=255)
+ organization_id = models.UUIDField()
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ reason = models.CharField(max_length=500, default="", db_default="")
+ skill_project = models.BigIntegerField(null=True)
+ skill_name = models.CharField(max_length=64, default="account-audit", db_default="account-audit")
+ task_run_id = models.UUIDField(unique=True)
+ notebook_short_id = models.CharField(max_length=12)
+ finalized_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["credential", "webhook_id"], name="account_audit_admission_delivery"),
+ ]
diff --git a/products/account_audits/backend/presentation/__init__.py b/products/account_audits/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/account_audits/backend/presentation/views.py b/products/account_audits/backend/presentation/views.py
new file mode 100644
index 000000000000..dd69b0ed4d42
--- /dev/null
+++ b/products/account_audits/backend/presentation/views.py
@@ -0,0 +1,179 @@
+import base64
+import binascii
+from collections.abc import Mapping
+from datetime import timedelta
+from typing import Any
+from uuid import UUID
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import Throttled
+from rest_framework.parsers import JSONParser
+from rest_framework.permissions import AllowAny
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.throttling import SimpleRateThrottle
+from rest_framework.views import APIView
+
+from posthog.ingress.verify.schemes import HmacSha256, VerificationOutcome
+from posthog.rate_limit import IPThrottle
+
+from products.account_audits.backend.facade import api as account_audits
+from products.account_audits.backend.facade.contracts import AccountAuditRequest
+
+MAX_BODY_BYTES = 4 * 1024
+SIGNATURE_TOLERANCE = timedelta(minutes=5)
+
+
+class AccountAuditStartThrottle(IPThrottle):
+ scope = "account_audit_start"
+ rate = "600/minute"
+
+
+class AccountAuditCredentialThrottle(SimpleRateThrottle):
+ scope = "account_audit_credential"
+ rate = "60/minute"
+
+ def get_cache_key(self, request: Request, view: APIView) -> str:
+ return self.cache_format % {"scope": self.scope, "ident": str(UUID(request.headers["X-PostHog-Audit-Key"]))}
+
+
+class AccountAuditStartRequestSerializer(serializers.Serializer):
+ organization_id = serializers.UUIDField(help_text="Organization that owns the target team.")
+ team_id = serializers.IntegerField(
+ required=False,
+ help_text="Target team ID. Defaults to the non-demo root project with the most distinct resource viewers in the last 30 days, excluding projects pending deletion. Ties use the oldest project.",
+ min_value=1,
+ )
+ reason = serializers.CharField(max_length=500, help_text="Why the account audit is being requested.")
+ skill_project = serializers.IntegerField(
+ min_value=1,
+ help_text="Project ID containing the skill in this region. Audit credentials authorize reading skills from any project.",
+ )
+ skill_name = serializers.CharField(
+ max_length=64,
+ help_text="Name of the single-file skill in skill_project. Uses its latest active version.",
+ )
+
+ def to_internal_value(self, data: Any) -> dict[str, Any]:
+ field_types = {"organization_id": str, "team_id": int, "reason": str, "skill_project": int, "skill_name": str}
+ if not isinstance(data, dict) or set(data) - field_types.keys():
+ raise serializers.ValidationError(
+ {"non_field_errors": ["Expected an object containing only supported audit parameters."]}
+ )
+ if any(type(value) is not field_types[key] for key, value in data.items()):
+ raise serializers.ValidationError({"non_field_errors": ["Audit parameters have invalid types."]})
+ return super().to_internal_value(data)
+
+
+class AccountAuditStartResponseSerializer(serializers.Serializer):
+ task_run_id = serializers.UUIDField(help_text="Native task run executing the account audit.")
+ team_id = serializers.IntegerField(help_text="Resolved target team ID.")
+
+
+class AccountAuditConflictSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="Why this audit did not start.")
+
+
+class AccountAuditStartViewSet(viewsets.ViewSet):
+ authentication_classes: list[type] = []
+ permission_classes = [AllowAny]
+ parser_classes = [JSONParser]
+ scope_object = "INTERNAL"
+
+ @extend_schema(
+ request=AccountAuditStartRequestSerializer,
+ responses={
+ 202: AccountAuditStartResponseSerializer,
+ 204: None,
+ 400: OpenApiResponse(
+ description=(
+ "The request was rejected. A body that is not JSON or is too large, or a missing or ineligible "
+ "team, returns no body. Invalid fields return a validation error body. A missing "
+ "or unsupported skill returns a detail message."
+ )
+ ),
+ 401: None,
+ 403: None,
+ 409: AccountAuditConflictSerializer,
+ 503: None,
+ },
+ )
+ @action(methods=["POST"], detail=False, throttle_classes=[AccountAuditStartThrottle])
+ def start(self, request: Request) -> Response:
+ if request.content_type != "application/json":
+ return Response(status=status.HTTP_400_BAD_REQUEST)
+ try:
+ if int(request.META.get("CONTENT_LENGTH") or 0) > MAX_BODY_BYTES:
+ return Response(status=status.HTTP_400_BAD_REQUEST)
+ except ValueError:
+ return Response(status=status.HTTP_400_BAD_REQUEST)
+ raw_body = request.body
+ if len(raw_body) > MAX_BODY_BYTES:
+ return Response(status=status.HTTP_400_BAD_REQUEST)
+
+ public_key_id = self._verified_credential_key_id(request, raw_body)
+ if public_key_id is None:
+ return Response(status=status.HTTP_401_UNAUTHORIZED)
+
+ throttle = AccountAuditCredentialThrottle()
+ if not throttle.allow_request(request, self):
+ raise Throttled(wait=throttle.wait())
+
+ serializer = AccountAuditStartRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ payload = AccountAuditRequest(**serializer.validated_data)
+ result = account_audits.start(payload, public_key_id, request.headers["webhook-id"])
+ if result.status == "accepted":
+ return Response(AccountAuditStartResponseSerializer(instance=result).data, status=202)
+ if result.status == "skipped":
+ return Response(status=204)
+ if result.status == "skill_unavailable":
+ return Response(
+ {"detail": "Skill not found or unsupported. Check skill_project and skill_name."},
+ status=400,
+ )
+ if result.status == "conflict":
+ return Response({"detail": "This delivery ID has another audit request."}, status=409)
+ return Response(
+ status={"invalid": 400, "unauthorized": 401, "forbidden": 403, "unavailable": 503}[result.status]
+ )
+
+ @classmethod
+ def _verified_credential_key_id(cls, request: Request, raw_body: bytes) -> UUID | None:
+ key_id = request.headers.get("X-PostHog-Audit-Key")
+ try:
+ public_key_id = UUID(key_id or "")
+ except (TypeError, ValueError, AttributeError):
+ return None
+ signing_secret = account_audits.signing_secret_for(public_key_id)
+ webhook_id = request.headers.get("webhook-id")
+ if (
+ signing_secret is None
+ or not webhook_id
+ or len(webhook_id) > 255
+ or not cls._valid_signature(signing_secret, raw_body, request.headers)
+ ):
+ return None
+ return public_key_id
+
+ @staticmethod
+ def _valid_signature(signing_secret: str, raw_body: bytes, headers: Mapping[str, str]) -> bool:
+ secret = signing_secret.removeprefix("whsec_")
+ try:
+ signing_key = base64.b64decode(secret, validate=True)
+ except (ValueError, binascii.Error):
+ return False
+ scheme = HmacSha256(
+ secret_getter=lambda: signing_key,
+ signature_header="webhook-signature",
+ prefix="v1,",
+ encoding="base64",
+ signed_input="id_timestamp_body",
+ delivery_id_header="webhook-id",
+ timestamp_header="webhook-timestamp",
+ timestamp_max_age_seconds=int(SIGNATURE_TOLERANCE.total_seconds()),
+ timestamp_max_future_seconds=int(SIGNATURE_TOLERANCE.total_seconds()),
+ )
+ return scheme.verify(body=raw_body, headers=headers).outcome == VerificationOutcome.VERIFIED
diff --git a/products/account_audits/backend/routes.py b/products/account_audits/backend/routes.py
new file mode 100644
index 000000000000..bad29a21dae2
--- /dev/null
+++ b/products/account_audits/backend/routes.py
@@ -0,0 +1,7 @@
+from posthog.api.routing import RouterRegistry
+
+from products.account_audits.backend.presentation.views import AccountAuditStartViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.root.register(r"account_audits", AccountAuditStartViewSet, "account_audits")
diff --git a/products/account_audits/backend/tasks/__init__.py b/products/account_audits/backend/tasks/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/account_audits/backend/tasks/tasks.py b/products/account_audits/backend/tasks/tasks.py
new file mode 100644
index 000000000000..69ce0c10accd
--- /dev/null
+++ b/products/account_audits/backend/tasks/tasks.py
@@ -0,0 +1,29 @@
+from uuid import UUID
+
+from celery import shared_task
+
+from posthog.redis import get_client
+
+from products.account_audits.backend.models import AccountAuditAdmission
+
+
+@shared_task(ignore_result=True, soft_time_limit=60, time_limit=70)
+def finalize_account_audit(team_id: int, task_run_id: str) -> None:
+ from products.account_audits.backend.logic.execution import ( # noqa: PLC0415 — keeps agent dependencies off task registration
+ finish_account_audit,
+ )
+
+ lock = get_client().lock(f"account-audit-finish:{team_id}:{task_run_id}", timeout=90)
+ if not lock.acquire(blocking=False):
+ return
+ try:
+ finish_account_audit(team_id=team_id, task_run_id=UUID(task_run_id))
+ finally:
+ lock.release()
+
+
+@shared_task(ignore_result=True, soft_time_limit=60, time_limit=70)
+def reconcile_account_audits() -> None:
+ pending = AccountAuditAdmission.objects.unscoped().filter(finalized_at__isnull=True)
+ for team_id, run_id in pending.values_list("team_id", "task_run_id").iterator(chunk_size=100):
+ finalize_account_audit.delay(team_id, str(run_id))
diff --git a/products/account_audits/backend/templates/admin/account_audits/account_audit_credential_created.html b/products/account_audits/backend/templates/admin/account_audits/account_audit_credential_created.html
new file mode 100644
index 000000000000..d5de49633e16
--- /dev/null
+++ b/products/account_audits/backend/templates/admin/account_audits/account_audit_credential_created.html
@@ -0,0 +1,47 @@
+{% extends "admin/base_site.html" %}
+{% block content %}
+ <p>Copy this signing secret now. It will not be shown again.</p>
+ <p>In the workflow HTTP action, set these values. The workflow can run in either region.</p>
+ <dl>
+ <dt>
+ <label for="api-url">POST URL</label>
+ </dt>
+ <dd>
+ <input id="api-url" type="text" readonly value="{{ api_url }}" size="60">
+ </dd>
+ <dt>
+ <label for="key-id">X-PostHog-Audit-Key header</label>
+ </dt>
+ <dd>
+ <input id="key-id" type="text" readonly value="{{ key_id }}" size="40">
+ </dd>
+ <dt>
+ <label for="signing-secret">Signing secret</label>
+ </dt>
+ <dd>
+ <input id="signing-secret"
+ type="text"
+ readonly
+ value="{{ signing_secret }}"
+ size="54"
+ autocomplete="off">
+ </dd>
+ <dt>
+ <label for="json-body">JSON body</label>
+ </dt>
+ <dd>
+ <textarea id="json-body" readonly rows="6" cols="60">{
+ "organization_id": "&lt;organization ID&gt;",
+ "reason": "&lt;why this audit is needed&gt;",
+ "skill_project": 123,
+ "skill_name": "&lt;skill name&gt;"
+}</textarea>
+ </dd>
+ </dl>
+ <p>
+ Replace the action's default JSON body with this one. Set skill_project to the numeric ID of the project containing the skill in this region. You can also add team_id as a number to select the audit target. Other fields, such as event or person, are rejected.
+ </p>
+ <p>This credential authorizes audits and skill reads across projects in this region. Keep separate credentials for US and EU requests.</p>
+ <p>Publish the workflow changes and verify a request succeeds before disabling the old credential.</p>
+ <p><a href="{{ credential_url }}">Manage credential</a></p>
+{% endblock %}
diff --git a/products/account_audits/backend/tests/__init__.py b/products/account_audits/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/account_audits/backend/tests/test_account_audit_admin.py b/products/account_audits/backend/tests/test_account_audit_admin.py
new file mode 100644
index 000000000000..82378b6c3ff9
--- /dev/null
+++ b/products/account_audits/backend/tests/test_account_audit_admin.py
@@ -0,0 +1,58 @@
+import base64
+
+from posthog.test.base import BaseTest
+
+from django.contrib.admin.models import LogEntry
+from django.urls import reverse
+
+from posthog.models import User
+
+from products.account_audits.backend.models import AccountAuditCredential
+
+
+class TestAccountAuditCredentialAdmin(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save(update_fields=["is_staff"])
+ self.client.force_login(self.user)
+ self.add_url = reverse("admin:account_audits_accountauditcredential_add")
+ self.add_data = {"is_active": "on"}
+
+ def test_admin_provisions_once_then_allows_overlap_and_revocation_without_exposing_secret(self) -> None:
+ site_url = "https://eu.posthog.com"
+ self.enterContext(self.settings(SITE_URL=site_url))
+ other_staff = User.objects.create(email="[email protected]", is_staff=True)
+ self.assertNotContains(self.client.get(self.add_url), 'name="created_by"')
+ response = self.client.post(self.add_url, {**self.add_data, "created_by": other_staff.pk})
+ self.assertEqual(response.status_code, 200)
+ credential = AccountAuditCredential.objects.get()
+ self.assertEqual(credential.created_by_id, self.user.pk)
+ secret = credential.signing_secret
+ self.assertTrue(secret.startswith("whsec_"))
+ self.assertEqual(len(base64.b64decode(secret.removeprefix("whsec_"))), 32)
+ self.assertContains(response, secret)
+ self.assertContains(response, f"{site_url}{reverse('account_audits-start')}")
+ self.assertIn("no-store", response.headers["Cache-Control"])
+ change_url = reverse("admin:account_audits_accountauditcredential_change", args=[credential.pk])
+ self.assertNotContains(self.client.get(change_url), secret)
+ self.assertNotContains(
+ self.client.get(reverse("admin:account_audits_accountauditcredential_changelist")), secret
+ )
+ self.assertFalse(LogEntry.objects.filter(change_message__contains=secret).exists())
+
+ response = self.client.post(self.add_url, self.add_data)
+ self.assertEqual(response.status_code, 200)
+ replacement = AccountAuditCredential.objects.exclude(pk=credential.pk).get()
+ self.assertNotEqual(replacement.signing_secret, secret)
+ credential.refresh_from_db()
+ self.assertTrue(credential.is_active)
+
+ response = self.client.post(change_url, {"created_by": "", "signing_secret": "replacement"})
+ self.assertEqual(response.status_code, 302)
+ credential.refresh_from_db()
+ self.assertFalse(credential.is_active)
+ self.assertEqual(credential.created_by_id, self.user.pk)
+ self.assertEqual(credential.signing_secret, secret)
+ replacement.refresh_from_db()
+ self.assertTrue(replacement.is_active)
diff --git a/products/account_audits/backend/tests/test_account_audits.py b/products/account_audits/backend/tests/test_account_audits.py
new file mode 100644
index 000000000000..b532fd4403c0
--- /dev/null
+++ b/products/account_audits/backend/tests/test_account_audits.py
@@ -0,0 +1,460 @@
+import hmac
+import json
+import time
+import base64
+import hashlib
+from datetime import timedelta
+from uuid import uuid4
+
+import time_machine
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.core.cache.backends.locmem import LocMemCache
+from django.db.models.deletion import ProtectedError
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, Team
+from posthog.models.file_system.file_system_view_log import FileSystemViewLog
+from posthog.models.user import User
+
+from products.access_control.backend.models import AccessControl
+from products.account_audits.backend.models import AccountAuditAdmission, AccountAuditCredential
+from products.account_audits.backend.presentation.views import (
+ AccountAuditCredentialThrottle,
+ AccountAuditStartRequestSerializer,
+ AccountAuditStartThrottle,
+)
+from products.notebooks.backend.models import Notebook
+from products.skills.backend.models import LLMSkill
+from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun
+
+
+class TestAccountAuditStartAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ self.user.is_staff = True
+ self.user.save(update_fields=["is_staff"])
+ self.secret = f"whsec_{base64.b64encode(b'a' * 32).decode()}"
+ self.credential = AccountAuditCredential.objects.create(created_by=self.user, signing_secret=self.secret)
+ self.skill = LLMSkill.objects.create(
+ team=self.team, name="account-audit", description="Audit", body="Audit this project.", version=2
+ )
+ self.workflow = self.enterContext(
+ patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ )
+ self.url = "/api/account_audits/start/"
+
+ def _post(
+ self,
+ payload: object,
+ *,
+ webhook_id: str = "delivery-1",
+ timestamp: str | None = None,
+ signature: str | None = None,
+ signing_body: bytes | None = None,
+ key_id: str | None = None,
+ ):
+ if isinstance(payload, dict):
+ payload = {
+ "reason": "testing",
+ "skill_project": self.team.id,
+ "skill_name": "account-audit",
+ **payload,
+ }
+ raw_body = payload if isinstance(payload, bytes) else json.dumps(payload, separators=(",", ":")).encode()
+ timestamp = timestamp if timestamp is not None else str(int(time.time()))
+ signed_body = signing_body if signing_body is not None else raw_body
+ signature = (
+ signature
+ or base64.b64encode(
+ hmac.new(
+ b"a" * 32,
+ webhook_id.encode() + b"." + timestamp.encode() + b"." + signed_body,
+ hashlib.sha256,
+ ).digest()
+ ).decode()
+ )
+ return self.client.post(
+ self.url,
+ data=raw_body,
+ content_type="application/json",
+ HTTP_X_POSTHOG_AUDIT_KEY=key_id or str(self.credential.public_key_id),
+ HTTP_WEBHOOK_ID=webhook_id,
+ HTTP_WEBHOOK_TIMESTAMP=timestamp,
+ HTTP_WEBHOOK_SIGNATURE=f"v1,{signature}",
+ )
+
+ def test_rate_limits_verified_credentials_separately_from_shared_ip(self) -> None:
+ cache = LocMemCache(str(uuid4()), {})
+ payload = {"organization_id": str(self.organization.id)}
+ with (
+ patch.object(AccountAuditStartThrottle, "cache", cache),
+ patch.object(AccountAuditStartThrottle, "rate", "4/minute"),
+ patch.object(AccountAuditCredentialThrottle, "cache", cache),
+ patch.object(AccountAuditCredentialThrottle, "rate", "1/minute"),
+ ):
+ self.assertEqual(self._post(payload, signature="invalid").status_code, 401)
+ self.assertEqual(self._post(payload).status_code, 202)
+ limited = self._post(payload, key_id=str(self.credential.public_key_id).upper())
+ self.assertEqual(limited.status_code, 429)
+ self.assertGreater(int(limited.headers["Retry-After"]), 0)
+ self.credential = AccountAuditCredential.objects.create(created_by=self.user, signing_secret=self.secret)
+ self.assertEqual(self._post(payload).status_code, 202)
+ self.assertEqual(self._post(payload, signature="invalid").status_code, 429)
+
+ def test_signed_delivery_creates_a_restricted_audit_and_reuses_the_same_run(self) -> None:
+ payload = {"organization_id": str(self.organization.id), "reason": "activation-review"}
+ with self.captureOnCommitCallbacks(execute=True):
+ first = self._post(payload)
+ other_team = Team.objects.create(organization=self.organization, name="Recently active project")
+ FileSystemViewLog.objects.create(team=other_team, user=self.user, type="dashboard", ref="1")
+ second = self._post(payload)
+
+ self.assertEqual(first.status_code, 202)
+ admission = AccountAuditAdmission.objects.for_team(self.team.id).get(credential=self.credential)
+ self.assertEqual(first.json(), {"task_run_id": str(admission.task_run_id), "team_id": self.team.id})
+ self.assertEqual(second.status_code, 202)
+ self.assertEqual(second.json(), first.json())
+ self.assertEqual(admission.reason, "activation-review")
+ self.assertEqual((admission.skill_project, admission.skill_name), (self.team.id, self.skill.name))
+ run = TaskRun.objects.select_related("task").get(id=admission.task_run_id)
+ self.assertEqual(TaskRun.objects.count(), 1)
+ self.workflow.assert_called_once()
+ self.assertEqual(run.task.created_by_id, self.user.id)
+ self.assertTrue(run.task.internal)
+ self.assertEqual(run.task.origin_product, "account_audit")
+ self.assertIsNone(run.task.repository)
+ self.assertIn(self.skill.body, run.task.description)
+ self.assertIn(admission.notebook_short_id, run.task.description)
+ self.assertEqual(run.state["audit_skill_version"], self.skill.version)
+ self.assertFalse(run.state["pending_dispatch"]["create_pr"])
+ self.assertEqual(
+ run.state["pending_dispatch"]["posthog_mcp_scopes"],
+ ["user:read", "query:read", "insight:read", "notebook:read", "notebook:write"],
+ )
+ env = SandboxEnvironment.objects.get(id=run.state["sandbox_environment_id"])
+ self.assertTrue(env.internal)
+ self.assertEqual(env.network_access_level, "custom")
+ self.assertEqual(env.allowed_domains, [])
+ self.assertFalse(env.include_default_domains)
+ notebook = self.client.get(f"/api/projects/{self.team.id}/notebooks/{admission.notebook_short_id}/")
+ self.assertEqual(notebook.status_code, 200)
+ listed = self.client.get(f"/api/projects/{self.team.id}/notebooks/")
+ self.assertNotIn(admission.notebook_short_id, [item["short_id"] for item in listed.json()["results"]])
+ fresh = self._post({**payload, "team_id": self.team.id}, webhook_id="delivery-2")
+ self.assertEqual(fresh.status_code, 202)
+ self.assertNotEqual(fresh.json()["task_run_id"], first.json()["task_run_id"])
+
+ @parameterized.expand([(False, False, False), (False, False, True), (True, False, True), (False, True, True)])
+ def test_defaults_to_the_oldest_eligible_root_project_on_tied_activity(
+ self, is_demo: bool, pending_deletion: bool, has_views: bool
+ ) -> None:
+ self.team.is_demo = is_demo
+ self.team.save(update_fields=["is_demo"])
+ self.team.project.is_pending_deletion = pending_deletion
+ self.team.project.save(update_fields=["is_pending_deletion"])
+ next_team = Team.objects.create(organization=self.organization, name="Renamed project")
+ self.skill.team = next_team
+ self.skill.save(update_fields=["team"])
+ child = Team.objects.create(
+ organization=self.organization, project=self.team.project, parent_team=self.team, name="Child"
+ )
+ if has_views:
+ for team in (self.team, next_team, child):
+ FileSystemViewLog.objects.create(team=team, user=self.user, type="dashboard", ref="1")
+ other_user = User.objects.create(email="[email protected]")
+ FileSystemViewLog.objects.create(team=child, user=other_user, type="dashboard", ref="1")
+ expected_id = next_team.id if is_demo or pending_deletion else self.team.id
+ response = self._post({"organization_id": str(self.organization.id), "skill_project": next_team.id})
+ self.assertEqual(response.status_code, 202)
+ self.assertEqual(response.json()["team_id"], expected_id)
+ self.assertEqual(Task.objects.get().team_id, expected_id)
+
+ @parameterized.expand([(30, False), (31, False), (29, True)])
+ @time_machine.travel("2026-01-01T00:00:00Z", tick=False)
+ def test_selects_distinct_recent_viewers_unless_a_team_is_explicit(
+ self, days_ago: int, explicit_team: bool
+ ) -> None:
+ self.team.project.created_at = timezone.now() - timedelta(days=90)
+ self.team.project.save(update_fields=["created_at"])
+ active_team = Team.objects.create(organization=self.organization, name="Active project")
+ other_user = User.objects.create(email="[email protected]")
+ for ref in ("1", "2", "3"):
+ FileSystemViewLog.objects.create(team=self.team, user=self.user, type="dashboard", ref=ref)
+ for user in (self.user, other_user):
+ FileSystemViewLog.objects.create(
+ team=active_team,
+ user=user,
+ type="dashboard",
+ ref="1",
+ viewed_at=timezone.now() - timedelta(days=days_ago),
+ )
+ payload: dict[str, object] = {"organization_id": str(self.organization.id)}
+ if explicit_team:
+ payload["team_id"] = self.team.id
+ expected_id = self.team.id if explicit_team or days_ago > 30 else active_team.id
+ response = self._post(payload)
+ self.assertEqual(response.status_code, 202)
+ self.assertEqual(response.json()["team_id"], expected_id)
+ self.assertEqual(Task.objects.get().team_id, expected_id)
+
+ def test_rejects_an_organization_without_an_eligible_default_project(self) -> None:
+ self.team.is_demo = True
+ self.team.save(update_fields=["is_demo"])
+ response = self._post({"organization_id": str(self.organization.id)})
+ self.assertEqual(response.status_code, 400)
+ self.assertFalse(Task.objects.exists())
+
+ def test_failed_run_creation_rolls_back_and_allows_retry(self) -> None:
+ payload = {"organization_id": str(self.organization.id)}
+ with patch(
+ "products.tasks.backend.models.TaskRun.objects.create", side_effect=RuntimeError("database unavailable")
+ ):
+ with self.captureOnCommitCallbacks(execute=True):
+ self.assertEqual(self._post(payload).status_code, 503)
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+ self.assertFalse(Task.objects.exists())
+ self.assertFalse(Notebook.objects.filter(team_id=self.team.id).exists())
+ self.workflow.assert_not_called()
+ self.assertEqual(self._post(payload).status_code, 202)
+ self.assertEqual(AccountAuditAdmission.objects.unscoped().count(), 1)
+
+ def test_rejects_invalid_missing_and_stale_signatures(self) -> None:
+ payload = {"organization_id": str(self.organization.id), "team_id": self.team.id}
+ cases = [
+ ("invalid", "not-base64", None),
+ ("stale", None, str(int(time.time()) - 301)),
+ ]
+ for name, signature, timestamp in cases:
+ with self.subTest(name=name):
+ self.assertEqual(self._post(payload, signature=signature, timestamp=timestamp).status_code, 401)
+ response = self.client.post(
+ self.url,
+ data=json.dumps(payload).encode(),
+ content_type="application/json",
+ HTTP_X_POSTHOG_AUDIT_KEY=str(self.credential.public_key_id),
+ HTTP_WEBHOOK_ID="delivery-missing-signature",
+ HTTP_WEBHOOK_TIMESTAMP=str(int(time.time())),
+ )
+
+ self.assertEqual(response.status_code, 401)
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+
+ def test_rejects_a_signature_for_a_different_raw_body(self) -> None:
+ payload = {"organization_id": str(self.organization.id), "team_id": self.team.id}
+ response = self._post(payload, signing_body=b'{"organization_id":"different","team_id":1}')
+
+ self.assertEqual(response.status_code, 401)
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+
+ @parameterized.expand([("invalid_json",), ("unsupported_field",), ("oversized",)])
+ def test_rejects_invalid_request_bodies(self, problem: str) -> None:
+ payload = {
+ "organization_id": str(self.organization.id),
+ "reason": "testing",
+ "skill_project": self.team.id,
+ "skill_name": self.skill.name,
+ }
+ body = (
+ b"{"
+ if problem == "invalid_json"
+ else json.dumps({**payload, **({"extra": True} if problem == "unsupported_field" else {})}).encode()
+ )
+ if problem == "oversized":
+ body += b" " * 4096
+ self.assertEqual(self._post(body).status_code, 400)
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+
+ @parameterized.expand([("US",), ("EU",)])
+ def test_skips_without_ai_processing_approval(self, region: str) -> None:
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ payload = {"organization_id": str(self.organization.id), "reason": "activation"}
+ with (
+ self.settings(CLOUD_DEPLOYMENT=region),
+ patch("products.account_audits.backend.logic.service.ph_scoped_capture") as capture_context,
+ ):
+ first = self._post(payload)
+ second = self._post(payload)
+ self.assertEqual(first.status_code, 204)
+ self.assertEqual(second.status_code, 204)
+ capture_context.assert_called_with(region="US", event_region=region, raise_on_error=True)
+ captures = capture_context.return_value.__enter__.return_value.call_args_list
+ self.assertEqual(captures[0], captures[1])
+ self.assertEqual(captures[0].kwargs["event"], "audit_not_run")
+ self.assertEqual(
+ captures[0].kwargs["properties"],
+ {
+ "organization_id": str(self.organization.id),
+ "team_id": self.team.id,
+ "reason": "no ai opt in",
+ "audit_reason": "activation",
+ "skill_project": self.team.id,
+ "skill_name": "account-audit",
+ "$insert_id": f"audit-not-run-{self.credential.public_key_id}-delivery-1",
+ },
+ )
+ self.assertFalse(Task.objects.exists())
+ self.assertFalse(Notebook.objects.filter(team_id=self.team.id).exists())
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+
+ def test_retries_a_skipped_event_if_capture_fails(self) -> None:
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ with patch("products.account_audits.backend.logic.service.ph_scoped_capture") as capture:
+ capture.return_value.__exit__.side_effect = RuntimeError("capture unavailable")
+ self.assertEqual(self._post({"organization_id": str(self.organization.id)}).status_code, 503)
+ capture.return_value.__exit__.side_effect = None
+ self.assertEqual(self._post({"organization_id": str(self.organization.id)}).status_code, 204)
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+
+ def test_rejects_a_deployment_that_cannot_capture_the_completion_event(self) -> None:
+ payload = {"organization_id": str(self.organization.id), "team_id": self.team.id}
+ with self.settings(CLOUD_DEPLOYMENT="DEV"):
+ response = self._post(payload)
+
+ self.assertEqual(response.status_code, 503)
+ self.assertFalse(Task.objects.exists())
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+
+ def test_rejects_when_the_audit_skill_is_unavailable_without_admitting(self) -> None:
+ self.skill.delete()
+ response = self._post({"organization_id": str(self.organization.id)})
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(
+ response.json()["detail"], "Skill not found or unsupported. Check skill_project and skill_name."
+ )
+ self.assertFalse(Task.objects.exists())
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+
+ @parameterized.expand([("another_organization",), ("child_environment",)])
+ def test_rejects_an_ineligible_explicit_team(self, problem: str) -> None:
+ organization_id, team_id = self.organization.id, self.team.id
+ if problem == "another_organization":
+ other_org = Organization.objects.create(name="Other organization", is_ai_data_processing_approved=True)
+ Team.objects.create(organization=other_org, name="Other team")
+ organization_id = other_org.id
+ else:
+ team_id = Team.objects.create(
+ organization=self.organization, project=self.team.project, parent_team=self.team, name="Child"
+ ).id
+ payload = {"organization_id": str(organization_id), "team_id": team_id}
+ response = self._post(payload)
+
+ self.assertEqual(response.status_code, 400)
+ self.assertFalse(Task.objects.exists())
+
+ def test_rejects_when_no_team_actor_is_available(self) -> None:
+ self.user.is_active = False
+ self.user.save(update_fields=["is_active"])
+ response = self._post({"organization_id": str(self.organization.id), "team_id": self.team.id})
+ self.assertEqual(response.status_code, 403)
+ self.assertFalse(Task.objects.exists())
+
+ @parameterized.expand([("team_id",), ("reason",), ("skill_project",), ("skill_name",)])
+ def test_rejects_a_repeated_delivery_with_changed_parameters(self, field: str) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ payload = {"organization_id": str(self.organization.id), "team_id": self.team.id}
+ changed_payload = {
+ **payload,
+ field: other_team.id if field in ("team_id", "skill_project") else "another-audit",
+ }
+ self.assertEqual(self._post(payload).status_code, 202)
+ response = self._post(changed_payload)
+
+ self.assertEqual(response.status_code, 409)
+ self.assertEqual(response.json()["detail"], "This delivery ID has another audit request.")
+ self.assertEqual(TaskRun.objects.count(), 1)
+ self.assertEqual(AccountAuditAdmission.objects.unscoped().count(), 1)
+
+ @parameterized.expand([("inactive",), ("not_staff",), ("deleted",)])
+ def test_audit_uses_a_private_skill_independently_of_credential_creator(self, condition: str) -> None:
+ creator = User.objects.create(email="[email protected]", is_staff=True)
+ self.credential.created_by = creator
+ self.credential.save(update_fields=["created_by"])
+ if condition == "deleted":
+ creator.delete()
+ else:
+ User.objects.filter(pk=creator.pk).update(**{"is_active" if condition == "inactive" else "is_staff": False})
+ skill_org = Organization.objects.create(
+ name="Skill organization", available_product_features=[{"key": AvailableFeature.ACCESS_CONTROL}]
+ )
+ skill_team = Team.objects.create(organization=skill_org, name="Private skills")
+ skill = LLMSkill.objects.create(
+ team=skill_team, name="account-audit", description="Audit", body="# Audit\n", is_latest=True
+ )
+ AccessControl.objects.create(
+ team=skill_team, resource="project", resource_id=str(skill_team.id), access_level="none"
+ )
+ AccessControl.objects.create(
+ team=skill_team, resource="llm_skill", resource_id=str(skill.id), access_level="none"
+ )
+ response = self._post({"organization_id": str(self.organization.id), "skill_project": skill_team.id})
+
+ self.assertEqual(response.status_code, 202)
+ self.assertIn(skill.body, Task.objects.get().description)
+ self.assertEqual(AccountAuditAdmission.objects.unscoped().get().skill_project, skill_team.id)
+
+ @parameterized.expand([("revoked",), ("unknown_key",), ("wrong_secret",)])
+ def test_rejects_an_ineligible_destination_credential(self, condition: str) -> None:
+ if condition == "revoked":
+ AccountAuditCredential.objects.filter(pk=self.credential.pk).update(is_active=False)
+ elif condition == "unknown_key":
+ AccountAuditCredential.objects.filter(pk=self.credential.pk).update(public_key_id=uuid4())
+ else:
+ AccountAuditCredential.objects.filter(pk=self.credential.pk).update(
+ signing_secret=f"whsec_{base64.b64encode(b'b' * 32).decode()}"
+ )
+ response = self._post({"organization_id": str(self.organization.id)})
+ self.assertEqual(response.status_code, 401)
+ self.assertFalse(Task.objects.exists())
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().exists())
+
+ def test_preserves_historic_admissions_when_a_creator_or_credential_is_deleted(self) -> None:
+ creator = User.objects.create_user(email="[email protected]", password=None, first_name="Audit")
+ credential = AccountAuditCredential.objects.create(created_by=creator, signing_secret=self.secret)
+ admission = AccountAuditAdmission.objects.unscoped().create(
+ credential=credential,
+ task_run_id=uuid4(),
+ webhook_id="delivery-1",
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ )
+
+ creator.delete()
+ credential.refresh_from_db()
+ self.assertIsNone(credential.created_by)
+ with self.assertRaises(ProtectedError):
+ credential.delete()
+ self.assertTrue(AccountAuditAdmission.objects.unscoped().filter(pk=admission.pk).exists())
+
+
+class TestAccountAuditRequestValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("unknown_field", {"extra": True}),
+ ("boolean_project", {"skill_project": True}),
+ ("string_team", {"team_id": "1"}),
+ ("null_team", {"team_id": None}),
+ ("numeric_reason", {"reason": 1}),
+ ("numeric_skill", {"skill_name": 1}),
+ ]
+ )
+ def test_rejects_values_that_drf_would_coerce(self, _name: str, changes: dict[str, object]) -> None:
+ serializer = AccountAuditStartRequestSerializer(
+ data={
+ "organization_id": str(uuid4()),
+ "reason": "testing",
+ "skill_project": 1,
+ "skill_name": "account-audit",
+ **changes,
+ }
+ )
+ self.assertFalse(serializer.is_valid())
diff --git a/products/account_audits/backend/tests/test_audit_execution.py b/products/account_audits/backend/tests/test_audit_execution.py
new file mode 100644
index 000000000000..e695662a179d
--- /dev/null
+++ b/products/account_audits/backend/tests/test_audit_execution.py
@@ -0,0 +1,188 @@
+from datetime import timedelta
+from uuid import UUID
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import User
+
+from products.account_audits.backend.logic.execution import finish_account_audit
+from products.account_audits.backend.models import AccountAuditAdmission, AccountAuditCredential
+from products.account_audits.backend.tasks.tasks import reconcile_account_audits
+from products.notebooks.backend.models import Notebook
+from products.tasks.backend.models import Task, TaskRun
+
+
+@override_settings(SITE_URL="http://testserver")
+@time_machine.travel("2026-09-01T12:00:00Z", tick=False)
+class TestAuditExecution(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ self.task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Audit",
+ description="Audit.",
+ origin_product=Task.OriginProduct.ACCOUNT_AUDIT,
+ internal=True,
+ )
+ self.notebook = Notebook.objects.filter(team_id=self.team.id).create(
+ team=self.team,
+ created_by=self.user,
+ title="Audit",
+ visibility="internal",
+ content={
+ "type": "doc",
+ "content": [{"type": "ph-markdown-notebook", "attrs": {"markdown": "# Audit\n\nFindings."}}],
+ },
+ )
+ self.task_run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ environment=TaskRun.Environment.CLOUD,
+ completed_at=timezone.now() - timedelta(minutes=4),
+ output={"notebook_short_id": self.notebook.short_id},
+ state={"unprocessed_request_ids": [], "token_cost": {"claude": {"anthropic": {"cost_microusd": 270000}}}},
+ )
+ credential = AccountAuditCredential.objects.create(created_by=self.user, signing_secret="unused")
+ self.admission = AccountAuditAdmission.objects.for_team(self.team.id).create(
+ credential=credential,
+ webhook_id="delivery",
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ task_run_id=self.task_run.id,
+ notebook_short_id=self.notebook.short_id,
+ reason="testing",
+ skill_project=self.team.id,
+ skill_name="custom-audit",
+ )
+ self.capture_context = self.enterContext(
+ patch("products.account_audits.backend.logic.execution.ph_scoped_capture")
+ )
+ self.capture = self.capture_context.return_value.__enter__.return_value
+
+ def finish(self) -> None:
+ self.task_run.save(update_fields=["status", "completed_at", "state", "output"])
+ if self.notebook.pk:
+ self.notebook.save(update_fields=["content", "created_by"])
+ finish_account_audit(team_id=self.team.id, task_run_id=self.task_run.id)
+ self.admission.refresh_from_db()
+
+ @parameterized.expand([("US", 0), ("EU", 27)])
+ def test_emits_verified_result_with_native_cost_once(self, region: str, token_cost: int) -> None:
+ self.task_run.state["token_cost"]["claude"]["anthropic"]["cost_microusd"] = token_cost * 10000
+ with self.settings(CLOUD_DEPLOYMENT=region):
+ self.finish()
+ self.finish()
+ self.capture_context.assert_called_once_with(region="US", event_region=region, raise_on_error=True)
+ self.capture.assert_called_once()
+ event = self.capture.call_args.kwargs
+ self.assertEqual(event["event"], "account_audit_finished")
+ self.assertEqual(
+ event["properties"],
+ {
+ "organization_id": str(self.organization.id),
+ "team_id": self.team.id,
+ "notebook_url": f"http://testserver/project/{self.team.id}/notebooks/{self.notebook.short_id}",
+ "reason": "testing",
+ "skill_project": self.team.id,
+ "skill_name": "custom-audit",
+ "token_cost_cents": token_cost,
+ "$insert_id": f"account-audit-finished-{self.task_run.id}",
+ },
+ )
+ self.assertIsNotNone(self.admission.finalized_at)
+
+ @parameterized.expand([("failed",), ("cancelled",), ("in_progress",)])
+ def test_no_success_event_for_other_statuses(self, status: str) -> None:
+ self.task_run.status = status
+ self.finish()
+ self.capture.assert_not_called()
+ self.assertEqual(self.admission.finalized_at is not None, status != "in_progress")
+
+ @parameterized.expand(
+ [
+ ("empty",),
+ ("heading",),
+ ("missing",),
+ ("wrong_output",),
+ ("wrong_creator",),
+ ("wrong_origin",),
+ ("no_consent",),
+ ]
+ )
+ def test_rejects_unverified_results(self, problem: str) -> None:
+ if problem == "empty":
+ self.notebook.content = {"type": "doc", "content": []}
+ elif problem == "heading":
+ self.notebook.content["content"][0]["attrs"]["markdown"] = "# Audit"
+ elif problem == "missing":
+ self.notebook.delete()
+ elif problem == "wrong_output":
+ self.task_run.output = {"notebook_short_id": "another"}
+ elif problem == "wrong_creator":
+ self.notebook.created_by = User.objects.create(email="[email protected]")
+ elif problem == "wrong_origin":
+ self.task.origin_product = Task.OriginProduct.USER_CREATED
+ self.task.save(update_fields=["origin_product"])
+ else:
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ self.finish()
+ self.capture.assert_not_called()
+ self.assertIsNotNone(self.admission.finalized_at)
+
+ @parameterized.expand([("settled",), ("pending",)])
+ def test_waits_for_callbacks_then_reports_native_cost(self, accounting: str) -> None:
+ self.task_run.completed_at = timezone.now()
+ self.task_run.state["token_cost"] = {}
+ self.finish()
+ self.assertIsNone(self.admission.finalized_at)
+ self.capture.assert_not_called()
+ self.task_run.state["unprocessed_request_ids"] = ["request-1"]
+ if accounting == "settled":
+ self.task_run.state["unprocessed_request_ids"] = []
+ self.task_run.state["token_cost"] = {"claude": {"anthropic": {"cost_microusd": 270000}}}
+ self.finish()
+ self.capture.assert_not_called()
+ with time_machine.travel(timezone.now() + timedelta(minutes=3), tick=False):
+ self.finish()
+ self.assertEqual(
+ self.capture.call_args.kwargs["properties"]["token_cost_cents"], 27 if accounting == "settled" else None
+ )
+ self.assertIsNotNone(self.admission.finalized_at)
+
+ @parameterized.expand([("project",), ("organization",)])
+ def test_deletes_admission_with_its_tenant(self, tenant: str) -> None:
+ if tenant == "project":
+ self.team.project.delete()
+ else:
+ self.organization.delete()
+ finish_account_audit(team_id=self.team.id, task_run_id=self.task_run.id)
+ self.assertFalse(AccountAuditAdmission.objects.unscoped().filter(pk=self.admission.pk).exists())
+ self.capture.assert_not_called()
+
+ def test_periodic_scan_retries_capture_failure_and_stops_after_finalization(self) -> None:
+ self.capture.side_effect = RuntimeError("capture unavailable")
+ with self.assertRaises(RuntimeError):
+ self.finish()
+ self.assertIsNone(self.admission.finalized_at)
+ self.capture.side_effect = None
+ with patch(
+ "products.account_audits.backend.tasks.tasks.finalize_account_audit.delay",
+ side_effect=lambda team_id, run_id: finish_account_audit(team_id=team_id, task_run_id=UUID(run_id)),
+ ) as enqueue:
+ reconcile_account_audits()
+ self.admission.refresh_from_db()
+ self.assertIsNotNone(self.admission.finalized_at)
+ reconcile_account_audits()
+ enqueue.assert_called_once_with(self.team.id, str(self.task_run.id))
diff --git a/products/account_audits/frontend/generated/api.schemas.ts b/products/account_audits/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..cd1f8134b28d
--- /dev/null
+++ b/products/account_audits/frontend/generated/api.schemas.ts
@@ -0,0 +1,45 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+export interface AccountAuditStartRequestApi {
+ /** Organization that owns the target team. */
+ organization_id: string
+ /**
+ * Target team ID. Defaults to the non-demo root project with the most distinct resource viewers in the last 30 days, excluding projects pending deletion. Ties use the oldest project.
+ * @minimum 1
+ */
+ team_id?: number
+ /**
+ * Why the account audit is being requested.
+ * @maxLength 500
+ */
+ reason: string
+ /**
+ * Project ID containing the skill in this region. Audit credentials authorize reading skills from any project.
+ * @minimum 1
+ */
+ skill_project: number
+ /**
+ * Name of the single-file skill in skill_project. Uses its latest active version.
+ * @maxLength 64
+ */
+ skill_name: string
+}
+
+export interface AccountAuditStartResponseApi {
+ /** Native task run executing the account audit. */
+ task_run_id: string
+ /** Resolved target team ID. */
+ team_id: number
+}
+
+export interface AccountAuditConflictApi {
+ /** Why this audit did not start. */
+ detail: string
+}
diff --git a/products/account_audits/frontend/generated/api.ts b/products/account_audits/frontend/generated/api.ts
new file mode 100644
index 000000000000..54e9320f2691
--- /dev/null
+++ b/products/account_audits/frontend/generated/api.ts
@@ -0,0 +1,27 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type { AccountAuditStartRequestApi, AccountAuditStartResponseApi } from './api.schemas'
+
+export const getAccountAuditsStartCreateUrl = () => {
+ return `/api/account_audits/start/`
+}
+
+export const accountAuditsStartCreate = async (
+ accountAuditStartRequestApi: AccountAuditStartRequestApi,
+ options?: RequestInit
+): Promise<AccountAuditStartResponseApi | void> => {
+ return apiMutator<AccountAuditStartResponseApi | void>(getAccountAuditsStartCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(accountAuditStartRequestApi),
+ })
+}
diff --git a/products/account_audits/frontend/generated/api.zod.ts b/products/account_audits/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..6d990b8095c2
--- /dev/null
+++ b/products/account_audits/frontend/generated/api.zod.ts
@@ -0,0 +1,39 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+export const accountAuditsStartCreateBodyReasonMax = 500
+
+export const accountAuditsStartCreateBodySkillNameMax = 64
+
+export const AccountAuditsStartCreateBody = /* @__PURE__ */ zod.object({
+ organization_id: zod.uuid().describe('Organization that owns the target team.'),
+ team_id: zod
+ .number()
+ .min(1)
+ .optional()
+ .describe(
+ 'Target team ID. Defaults to the non-demo root project with the most distinct resource viewers in the last 30 days, excluding projects pending deletion. Ties use the oldest project.'
+ ),
+ reason: zod
+ .string()
+ .max(accountAuditsStartCreateBodyReasonMax)
+ .describe('Why the account audit is being requested.'),
+ skill_project: zod
+ .number()
+ .min(1)
+ .describe(
+ 'Project ID containing the skill in this region. Audit credentials authorize reading skills from any project.'
+ ),
+ skill_name: zod
+ .string()
+ .max(accountAuditsStartCreateBodySkillNameMax)
+ .describe('Name of the single-file skill in skill_project. Uses its latest active version.'),
+})
diff --git a/products/account_audits/manifest.tsx b/products/account_audits/manifest.tsx
new file mode 100644
index 000000000000..32fce61ea84e
--- /dev/null
+++ b/products/account_audits/manifest.tsx
@@ -0,0 +1,12 @@
+import { ProductManifest } from '../../frontend/src/types'
+
+export const manifest: ProductManifest = {
+ name: 'AccountAudits',
+ scenes: {},
+ routes: {},
+ redirects: {},
+ urls: {},
+ fileSystemTypes: {},
+ treeItemsNew: [],
+ treeItemsProducts: [],
+}
diff --git a/products/account_audits/package.json b/products/account_audits/package.json
new file mode 100644
index 000000000000..b1c2ad75d999
--- /dev/null
+++ b/products/account_audits/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "@posthog/products-account-audits",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
+ }
+}
diff --git a/products/account_audits/product.yaml b/products/account_audits/product.yaml
new file mode 100644
index 000000000000..e6577e22762f
--- /dev/null
+++ b/products/account_audits/product.yaml
@@ -0,0 +1,3 @@
+name: Account audits
+owners:
+ - team-growth
diff --git a/products/account_audits/tsconfig.json b/products/account_audits/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/account_audits/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/account_audits/turbo.json b/products/account_audits/turbo.json
new file mode 100644
index 000000000000..030ffc540ce3
--- /dev/null
+++ b/products/account_audits/turbo.json
@@ -0,0 +1,18 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/webhook_consumers.py",
+ "backend/tasks/**",
+ "backend/models.py",
+ "backend/migrations/**",
+ "backend/routes.py"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index e0d3989e7671..5433ff29687f 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -19672,6 +19672,7 @@ export namespace Schemas {
}>;
/**
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -19699,6 +19700,7 @@ export namespace Schemas {
*/
export type TaskOriginProductEnum =
| "onboarding"
+ | "account_audit"
| "error_tracking"
| "eval_clusters"
| "user_created"
@@ -22812,6 +22814,7 @@ export namespace Endpoints {
created_by: number;
exclude_origin_product:
| "onboarding"
+ | "account_audit"
| "error_tracking"
| "eval_clusters"
| "user_created"
diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.py
index 6f3acedf35f9..8ec623375abf 100644
--- a/products/notebooks/backend/facade/api.py
+++ b/products/notebooks/backend/facade/api.py
@@ -16,6 +16,8 @@ from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from uuid import UUID
+from django.db import transaction
+
from asgiref.sync import sync_to_async
from .. import logic, markdown_migration
@@ -196,13 +198,15 @@ def create_notebook(
last_modified_by_id=last_modified_by_id,
visibility=visibility,
)
- capture_notebook_created(
- short_id=notebook.short_id,
- creation_source=creation_source,
- team_id=team_id,
- created_by_id=created_by_id,
- visibility=notebook.visibility,
- node_count=notebook_node_count(notebook.content),
+ transaction.on_commit(
+ lambda: capture_notebook_created(
+ short_id=notebook.short_id,
+ creation_source=creation_source,
+ team_id=team_id,
+ created_by_id=created_by_id,
+ visibility=notebook.visibility,
+ node_count=notebook_node_count(notebook.content),
+ )
)
return _to_notebook_data(notebook)
diff --git a/products/notebooks/backend/test/test_facade.py b/products/notebooks/backend/test/test_facade.py
index 8b49637ed51b..b6e925eb900a 100644
--- a/products/notebooks/backend/test/test_facade.py
+++ b/products/notebooks/backend/test/test_facade.py
@@ -32,14 +32,18 @@ class TestNotebooksFacade(BaseTest):
def _doc(self, text: str = "hello") -> dict:
return {"type": "doc", "content": [content.create_paragraph_with_text(text)]}
- def test_create_notebook_returns_contract(self):
- data = api.create_notebook(
- self.team.id,
- title="My notebook",
- content=self._doc(),
- created_by_id=self.user.id,
- last_modified_by_id=self.user.id,
- )
+ @patch("products.notebooks.backend.facade.api.capture_notebook_created")
+ def test_create_notebook_returns_contract(self, capture):
+ with self.captureOnCommitCallbacks(execute=True):
+ data = api.create_notebook(
+ self.team.id,
+ title="My notebook",
+ content=self._doc(),
+ created_by_id=self.user.id,
+ last_modified_by_id=self.user.id,
+ )
+ capture.assert_not_called()
+ capture.assert_called_once()
self.assertEqual(data.title, "My notebook")
self.assertEqual(data.visibility, Notebook.Visibility.DEFAULT)
self.assertEqual(data.created_by_id, self.user.id)
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index ff1056664ea9..450a25d0c46d 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -1369,6 +1369,14 @@ def repair_report_actionability_cache(
return repair_latest_actionability(team_id=team_id, batch_size=batch_size, after=after)
+def resolve_audit_actor_for_team(team_id: int) -> int | None:
+ from products.signals.backend.temporal.agentic import (
+ resolve_acting_user_id_for_team, # noqa: PLC0415 — keeps Temporal agent dependencies off the facade import path
+ )
+
+ return resolve_acting_user_id_for_team(team_id)
+
+
def retract_source_signals(*, team: "Team", source_product: str, source_type: str, source_id: str) -> int:
"""Replace a source record's signal embeddings with an empty deleted row.
diff --git a/products/skills/backend/facade/__init__.py b/products/skills/backend/facade/__init__.py
new file mode 100644
index 000000000000..af5987b5c9aa
--- /dev/null
+++ b/products/skills/backend/facade/__init__.py
@@ -0,0 +1,3 @@
+from .api import SkillPrompt, get_skill_prompt_for_audit
+
+__all__ = ["SkillPrompt", "get_skill_prompt_for_audit"]
diff --git a/products/skills/backend/facade/api.py b/products/skills/backend/facade/api.py
new file mode 100644
index 000000000000..9b04e3e999df
--- /dev/null
+++ b/products/skills/backend/facade/api.py
@@ -0,0 +1,28 @@
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.skills.backend.api.skill_services import get_skill_by_name_from_db
+
+_MAX_SKILL_PROMPT_BODY_BYTES = 64 * 1024
+
+
+@frozen
+class SkillPrompt:
+ body: str
+ version: int
+
+
+def get_skill_prompt_for_audit(*, team_id: int, skill_name: str) -> SkillPrompt | None:
+ """Admin-issued audit credentials authorize skill reads independently of user permissions."""
+ team = Team.objects.filter(pk=team_id, project__is_pending_deletion=False).first()
+ if team is None:
+ return None
+
+ skill = get_skill_by_name_from_db(team, skill_name)
+ if skill is None or not skill.body or len(skill.body.encode("utf-8")) > _MAX_SKILL_PROMPT_BODY_BYTES:
+ return None
+
+ if skill.files.exists():
+ return None
+
+ return SkillPrompt(body=skill.body, version=skill.version)
diff --git a/products/skills/backend/test/test_facade.py b/products/skills/backend/test/test_facade.py
new file mode 100644
index 000000000000..3371a57ccc8c
--- /dev/null
+++ b/products/skills/backend/test/test_facade.py
@@ -0,0 +1,81 @@
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.skills.backend.facade.api import get_skill_prompt_for_audit
+from products.skills.backend.models import LLMSkill, LLMSkillFile
+
+
+class TestGetSkillPrompt(BaseTest):
+ def _create_skill(
+ self,
+ *,
+ name: str = "account-audit",
+ body: str = "# Account audit\n",
+ version: int = 1,
+ is_latest: bool = True,
+ deleted: bool = False,
+ team: Team | None = None,
+ ) -> LLMSkill:
+ return LLMSkill.objects.create(
+ team=team or self.team,
+ name=name,
+ description="Test skill.",
+ body=body,
+ version=version,
+ is_latest=is_latest,
+ deleted=deleted,
+ created_by=self.user,
+ )
+
+ def test_returns_only_the_requested_teams_skill(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ self._create_skill(body="# Other team\n", team=other_team)
+
+ assert get_skill_prompt_for_audit(team_id=self.team.id, skill_name="account-audit") is None
+
+ def test_returns_the_latest_active_version(self) -> None:
+ self._create_skill(body="# Version one\n", version=1, is_latest=False)
+ self._create_skill(body="# Version two\n", version=2)
+
+ prompt = get_skill_prompt_for_audit(team_id=self.team.id, skill_name="account-audit")
+
+ assert prompt is not None
+ assert prompt.body == "# Version two\n"
+ assert prompt.version == 2
+
+ @parameterized.expand(
+ [
+ ("missing",),
+ ("archived",),
+ ("empty",),
+ ("project_deleted",),
+ ("project_missing",),
+ ]
+ )
+ def test_returns_none_for_unavailable_skill(self, state: str) -> None:
+ if state == "archived":
+ self._create_skill(deleted=True)
+ elif state == "empty":
+ self._create_skill(body="")
+ elif state == "project_deleted":
+ self._create_skill()
+ self.team.project.is_pending_deletion = True
+ self.team.project.save(update_fields=["is_pending_deletion"])
+ elif state == "project_missing":
+ Team.objects.filter(pk=self.team.pk).delete()
+
+ assert get_skill_prompt_for_audit(team_id=self.team.id, skill_name="account-audit") is None
+
+ def test_returns_none_when_skill_has_bundled_files(self) -> None:
+ skill = self._create_skill()
+ LLMSkillFile.objects.create(skill=skill, path="references/guide.md", content="# Guide\n")
+
+ assert get_skill_prompt_for_audit(team_id=self.team.id, skill_name="account-audit") is None
+
+ def test_returns_none_when_skill_body_exceeds_64_kb(self) -> None:
+ self._create_skill(body="x" * (64 * 1024 + 1))
+
+ assert get_skill_prompt_for_audit(team_id=self.team.id, skill_name="account-audit") is None
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 3abd71c4b94c..032108bb937e 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -5928,6 +5928,9 @@ def _resolve_cloud_pr_authorship_mode(
user_github_integration_is_usable,
)
+ if task.origin_product == Task.OriginProduct.ACCOUNT_AUDIT:
+ return None, None
+
if pr_authorship_mode != PrAuthorshipMode.USER or github_user_token:
return pr_authorship_mode, None
@@ -7627,6 +7630,12 @@ def create_task(
if github_user_integration is not None:
validated_data["github_user_integration"] = github_user_integration.integration
+ if validated_data["origin_product"] == Task.OriginProduct.ACCOUNT_AUDIT:
+ validated_data["repository"] = None
+ validated_data["repositories"] = []
+ validated_data.pop("github_integration", None)
+ validated_data.pop("github_user_integration", None)
+
title = (validated_data.get("title") or "").strip()
if not title and (naming_source or validated_data.get("description")):
validated_data["title"] = generate_task_title(naming_source or validated_data["description"])
@@ -7737,7 +7746,11 @@ def update_task(
# Repo and credential are immutable for code-access-exempt tasks: a mutable repo reopens the
# gate (see task_exempt_from_code_access), and provisioning injects whatever integration is
# attached, so an attachable one would credential a run the create path left credential-less.
- if task.origin_product in (Task.OriginProduct.SIGNALS_CHAT, Task.OriginProduct.SIGNAL_REPORT):
+ if task.origin_product in (
+ Task.OriginProduct.SIGNALS_CHAT,
+ Task.OriginProduct.SIGNAL_REPORT,
+ Task.OriginProduct.ACCOUNT_AUDIT,
+ ):
validated_data.pop("repository", None)
validated_data.pop("repositories", None)
validated_data.pop("github_integration", None)
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index fa9b538c07a4..fb4aeec94b22 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -96,6 +96,7 @@ STREAMLIT_AUTH_PROXY_PORT = 8080
# host.docker.internal at `docker run` time (non-localhost hosts pass through).
_DOCKER_URL_ENV_KEYS = frozenset(
{
+ "AI_GATEWAY_URL",
"LLM_GATEWAY_URL",
"POSTHOG_API_URL",
"POSTHOG_SITE_URL",
diff --git a/products/tasks/backend/logic/services/gateway_model_pin.py b/products/tasks/backend/logic/services/gateway_model_pin.py
index 00b0ee01ba10..b9dec5107674 100644
--- a/products/tasks/backend/logic/services/gateway_model_pin.py
+++ b/products/tasks/backend/logic/services/gateway_model_pin.py
@@ -53,6 +53,7 @@ FREE_TIER_PIN_KEY = "posthog_code:free"
PRODUCT_ALLOWED_MODELS: dict[str, list[str]] = {
"posthog_ai": _first_party_pin("posthog_ai"),
+ "account_audit": _first_party_pin("account_audit"),
"posthog_code": DESKTOP_AGENT_MODELS,
FREE_TIER_PIN_KEY: FREE_TIER_MODELS,
"review_hog": _first_party_pin("review_hog"),
diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
index 3f21897ef725..b40a8ce45156 100644
--- a/products/tasks/backend/logic/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -305,6 +305,7 @@ class TestDockerSandboxUnit:
environment_variables={
"LLM_GATEWAY_URL": "http://localhost:13308",
"POSTHOG_API_URL": "http://localhost:8000",
+ "AI_GATEWAY_URL": "http://127.0.0.1:8080",
"POSTHOG_PROJECT_ID": "1",
},
)
@@ -318,6 +319,7 @@ class TestDockerSandboxUnit:
env_args = " ".join(docker_args)
assert "LLM_GATEWAY_URL=http://host.docker.internal:13308" in env_args
assert "POSTHOG_API_URL=http://host.docker.internal:8000" in env_args
+ assert "AI_GATEWAY_URL=http://host.docker.internal:8080" in env_args
assert "POSTHOG_PROJECT_ID=1" in env_args
@patch("products.tasks.backend.logic.services.docker_sandbox.subprocess.run")
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 1bd13fe4b4ed..f91018003f2e 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -368,6 +368,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
class OriginProduct(models.TextChoices):
ONBOARDING = "onboarding", "Onboarding"
+ ACCOUNT_AUDIT = "account_audit", "Account audit"
ERROR_TRACKING = "error_tracking", "Error Tracking"
EVAL_CLUSTERS = "eval_clusters", "Eval Clusters"
USER_CREATED = "user_created", "User Created"
@@ -1169,15 +1170,19 @@ class Task(Taggable, DeletedMetaFields, models.Model):
user_github_integration_is_usable,
)
- # A repo-less signals, autoresearch or metrics import task must carry no GitHub credential at
- # all, team or personal. Provisioning injects whatever integration is attached, and these runs read
- # text any member can write, so an attached token turns planted text into repository access.
- github_resolution_allowed = bool(repository) or origin_product not in (
- Task.OriginProduct.SIGNALS_CHAT,
- Task.OriginProduct.SIGNAL_REPORT,
- Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,
- Task.OriginProduct.AUTORESEARCH,
- Task.OriginProduct.METRICS_IMPORT,
+ # Audits and repo-less signals, autoresearch or metrics import tasks must carry no GitHub
+ # credential. Provisioning injects any attached integration; these runs read member-authored
+ # text, so an attached token turns planted text into repository access.
+ github_resolution_allowed = origin_product != Task.OriginProduct.ACCOUNT_AUDIT and (
+ bool(repository)
+ or origin_product
+ not in (
+ Task.OriginProduct.SIGNALS_CHAT,
+ Task.OriginProduct.SIGNAL_REPORT,
+ Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,
+ Task.OriginProduct.AUTORESEARCH,
+ Task.OriginProduct.METRICS_IMPORT,
+ )
)
github_integration = None
if github_resolution_allowed:
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 79713374d34c..050ac2750fa3 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -1000,6 +1000,7 @@ class TaskWriteSerializer(serializers.Serializer):
# forged origin would be free model access. Only create_wizard_cloud_run sets it,
# behind its own rate limits and daily cap.
tasks_facade.TaskOriginProduct.ONBOARDING,
+ tasks_facade.TaskOriginProduct.ACCOUNT_AUDIT,
# Exempt from the Desktop code-access gate on run endpoints, so a forged origin
# would bypass the waitlist. Only the signals scout-chat endpoint sets it.
tasks_facade.TaskOriginProduct.SIGNALS_CHAT,
diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
index a1b5b72676cc..ab82f9637909 100644
--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
@@ -57,6 +57,7 @@ _ORIGIN_TO_GATEWAY_PRODUCT: dict[str, str] = {
"loop": "posthog_code",
"metrics_import": "posthog_ai",
"onboarding": "onboarding",
+ "account_audit": "account_audit",
"posthog_ai": "posthog_ai",
"review_hog": "review_hog",
"scout_suggestions": "signals",
@@ -93,6 +94,7 @@ _SCOUT_STAGE_PREFIX = "scout:"
MINTABLE_PRODUCTS = frozenset(
{
"posthog_ai",
+ "account_audit",
"posthog_code",
"review_hog",
"slack_app",
@@ -134,6 +136,9 @@ def resolve_sandbox_ai_product(origin_product: str | None, ai_stage: str | None,
if gateway_product == "review_hog" and not internal:
logger.warning("review_hog origin without server-stamped internal flag; resolving posthog_code")
return "posthog_code"
+ if origin_product == "account_audit" and not internal:
+ logger.warning("account_audit origin without server-stamped internal flag; resolving posthog_code")
+ return "posthog_code"
if gateway_product is None:
gateway_product = "background_agents" if internal else "posthog_code"
if gateway_product == "signals" and ai_stage:
@@ -233,9 +238,12 @@ def mint_refusal(
runtime: str | None,
internal: bool = False,
prior_slack_run: bool = False,
+ origin_product: str | None = None,
distinct_id: str | None = None,
) -> str | None:
"""Why a routed run must not mint; a run without a token stays on the Python gateway."""
+ if ai_product == "account_audit" and (origin_product != "account_audit" or not internal):
+ return "no_account_audit_provenance"
if ai_product == "slack_app" and not has_slack_provenance(
state, internal=internal, prior_slack_run=prior_slack_run
):
diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
index 4a1e72d176ea..1040f9c2aae6 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
@@ -97,6 +97,10 @@ class TestResolveSandboxAiProduct:
assert resolve_sandbox_ai_product("review_hog", "validation-c1") == "posthog_code"
assert resolve_sandbox_ai_product("review_hog", None, internal=False) == "posthog_code"
+ def test_account_audit_requires_the_server_stamped_internal_flag(self):
+ assert resolve_sandbox_ai_product("account_audit", None, internal=True) == "account_audit"
+ assert resolve_sandbox_ai_product("account_audit", None, internal=False) == "posthog_code"
+
def test_unmapped_internal_is_background_agents(self):
assert resolve_sandbox_ai_product("image_builder", None, internal=True) == "background_agents"
@@ -287,7 +291,7 @@ class TestMintScopedToken:
assert body["product"] == "review_hog"
assert body["allowed_models"] == _PRODUCT_ALLOWED_MODELS["review_hog"]
- @pytest.mark.parametrize("product", ["posthog_ai", "review_hog", "slack_app", "workflows"])
+ @pytest.mark.parametrize("product", ["posthog_ai", "account_audit", "review_hog", "slack_app", "workflows"])
def test_model_pin_follows_the_catalog(self, product):
from products.tasks.backend.facade.run_config import RuntimeAdapter, get_models_for_runtime_adapter
from products.tasks.backend.logic.services.gateway_model_pin import SDK_IMPLICIT_MODELS
@@ -1420,6 +1424,30 @@ class TestPosthogAiMint:
assert post.call_args.kwargs["json"]["ttl_seconds"] == MAX_SANDBOX_TTL_SECONDS + 3600
+ "origin,internal,mints",
+ [
+ ("account_audit", True, True),
+ ("account_audit", False, False),
+ ("onboarding", False, False),
+ ("onboarding", True, False),
+ ],
+)
+def test_account_audit_cost_routing_requires_server_provenance(
+ settings: Settings, origin: str, internal: bool, mints: bool
+) -> None:
+ settings.SANDBOX_AI_GATEWAY_URL = "https://ai-gateway.example.com"
+ settings.SANDBOX_AI_GATEWAY_PRODUCTS = "account_audit,onboarding"
+ with patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token", return_value="phe_test") as mint:
+ env = ai_gateway_env_vars(
+ team_id=123, origin_product=origin, internal=internal, model="claude-sonnet-5", runtime="acp"
+ )
+ assert ("AI_GATEWAY_TOKEN" in env) is mints
+ assert mint.called is mints
+ if mints:
+ mint.assert_called_once_with(ai_product="account_audit", team_id=123, user=None)
+
+
class TestPosthogCodeSandboxMint:
def _team(self, *, paid: bool) -> Team:
organization = Organization.objects.create(name="Code Org")
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index a2df0b3f9c6b..a614aa39d69e 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -503,14 +503,21 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
{"name": "x-posthog-mcp-consumer", "value": consumer},
]
+ @parameterized.expand([(None, True), ("account_audit", False)])
@patch(MOCK_API_URL)
@patch(MOCK_FACADE)
- def test_builds_configs_from_facade_results(self, mock_facade, mock_api_url) -> None:
+ def test_builds_configs_from_facade_results(
+ self, origin_product: str | None, mounts_store: bool, mock_facade, mock_api_url
+ ) -> None:
mock_api_url.return_value = self.API_BASE
installation = self._make_installation()
mock_facade.return_value = [installation]
- configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID)
+ configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, origin_product=origin_product)
+
+ if not mounts_store:
+ assert configs == []
+ return
mock_facade.assert_called_once_with(
self.TEAM_ID,
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 63cd91e55efd..b2a4d7176547 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -616,6 +616,9 @@ def get_user_mcp_server_configs(
Returns an empty list on errors (non-fatal).
"""
+ if origin_product == "account_audit":
+ return []
+
installations = get_installations_for_sandbox(
team_id,
user_id=user_id,
@@ -1584,6 +1587,7 @@ def ai_gateway_env_vars(
runtime=runtime,
internal=internal,
prior_slack_run=prior_slack_run,
+ origin_product=origin_product,
distinct_id=distinct_id,
)
if refusal:
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 31ae7d8c5706..9d256bbe7f6c 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -4776,6 +4776,28 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(task_run.state["pr_authorship_mode"], "bot")
mock_workflow.assert_not_called()
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_run_endpoint_cannot_start_a_product_private_account_audit(self, mock_workflow):
+ Integration.objects.create(team=self.team, kind="github", config={"access_token": "token"})
+ _grant_user_github_access(self.user)
+ task = self.create_task(created_by=self.user)
+ task.origin_product = Task.OriginProduct.ACCOUNT_AUDIT
+ task.internal = True
+ task.save(update_fields=["origin_product", "internal"])
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/runs/",
+ {
+ "environment": "cloud",
+ "pr_authorship_mode": "user",
+ "run_source": "manual",
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ mock_workflow.assert_not_called()
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
@patch(
"products.tasks.backend.facade.api.get_task_run_detail", side_effect=AssertionError("Run details not needed")
@@ -7205,13 +7227,19 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- def test_only_the_task_bound_sandbox_reads_a_product_private_task(self):
+ @parameterized.expand(
+ [
+ (Task.OriginProduct.BUSINESS_KNOWLEDGE,),
+ (Task.OriginProduct.ACCOUNT_AUDIT,),
+ ]
+ )
+ def test_only_the_task_bound_sandbox_reads_a_product_private_task(self, origin_product):
private_task = Task.objects.create(
team=self.team,
created_by=self.user,
title="Question",
description="Answer from business knowledge",
- origin_product=Task.OriginProduct.BUSINESS_KNOWLEDGE,
+ origin_product=origin_product,
)
other_task = self.create_task()
own_sandbox = self._sandbox_oauth_client(private_task.id)
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index 73f19770f306..3fb482de0f49 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -338,6 +338,7 @@ class TestTask(TestCase):
(Task.OriginProduct.SIGNAL_REPORT,),
(Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,),
(Task.OriginProduct.AUTORESEARCH,),
+ (Task.OriginProduct.ACCOUNT_AUDIT,),
]
)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
diff --git a/products/tasks/backend/tests/test_presentation_serializers.py b/products/tasks/backend/tests/test_presentation_serializers.py
index 4dc453b3de01..0a990b51b8b4 100644
--- a/products/tasks/backend/tests/test_presentation_serializers.py
+++ b/products/tasks/backend/tests/test_presentation_serializers.py
@@ -81,6 +81,7 @@ class TestTaskWriteSerializerOriginProduct(SimpleTestCase):
# internally funded inference under a per-run cap.
("signals_chat", True),
("scout_suggestions", True),
+ ("account_audit", True),
("user_created", False),
]
)
diff --git a/products/tasks/backend/visibility.py b/products/tasks/backend/visibility.py
index 826405e601d0..e7e7e8b3ab42 100644
--- a/products/tasks/backend/visibility.py
+++ b/products/tasks/backend/visibility.py
@@ -30,6 +30,7 @@ TEAM_READABLE_ORIGIN_PRODUCTS = [
# and scopes. Sandbox callers bypass these filters, so the run itself still works.
PRODUCT_PRIVATE_ORIGIN_PRODUCTS = [
Task.OriginProduct.BUSINESS_KNOWLEDGE,
+ Task.OriginProduct.ACCOUNT_AUDIT,
Task.OriginProduct.METRICS_IMPORT,
]
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 2e4eda707253..35b65c82cf77 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1439,6 +1439,7 @@ export interface PaginatedTaskListItemListApi {
/**
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -1468,6 +1469,7 @@ export type TaskOriginProductEnumApi = (typeof TaskOriginProductEnumApi)[keyof t
export const TaskOriginProductEnumApi = {
Onboarding: 'onboarding',
+ AccountAudit: 'account_audit',
ErrorTracking: 'error_tracking',
EvalClusters: 'eval_clusters',
UserCreated: 'user_created',
@@ -1548,6 +1550,7 @@ export interface TaskCreateApi {
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.
*
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -1783,6 +1786,7 @@ export interface TaskWriteApi {
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.
*
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -1919,6 +1923,7 @@ export interface PatchedTaskWriteApi {
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.
*
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -5316,6 +5321,7 @@ export type TasksListParams = {
* Exclude tasks with this origin product from the results
*
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -5461,6 +5467,7 @@ export type TasksListExcludeOriginProduct =
export const TasksListExcludeOriginProduct = {
Onboarding: 'onboarding',
+ AccountAudit: 'account_audit',
ErrorTracking: 'error_tracking',
EvalClusters: 'eval_clusters',
UserCreated: 'user_created',
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 180c9202fd36..45be53f28479 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -609,6 +609,7 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({
origin_product: zod
.enum([
'onboarding',
+ 'account_audit',
'error_tracking',
'eval_clusters',
'user_created',
@@ -635,11 +636,11 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({
'metrics_import',
])
.describe(
- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ '\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
),
repository: zod
.string()
@@ -807,6 +808,7 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.object({
origin_product: zod
.enum([
'onboarding',
+ 'account_audit',
'error_tracking',
'eval_clusters',
'user_created',
@@ -833,11 +835,11 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.object({
'metrics_import',
])
.describe(
- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ '\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
),
repository: zod
.string()
@@ -963,6 +965,7 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
origin_product: zod
.enum([
'onboarding',
+ 'account_audit',
'error_tracking',
'eval_clusters',
'user_created',
@@ -989,11 +992,11 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
'metrics_import',
])
.describe(
- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ '\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
),
repository: zod
.string()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 50fa5509c27f..34ddca1400e3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1667,6 +1667,43 @@ export namespace Schemas {
readonly email: string;
}
+ export interface AccountAuditConflict {
+ /** Why this audit did not start. */
+ detail: string;
+ }
+
+ export interface AccountAuditStartRequest {
+ /** Organization that owns the target team. */
+ organization_id: string;
+ /**
+ * Target team ID. Defaults to the non-demo root project with the most distinct resource viewers in the last 30 days, excluding projects pending deletion. Ties use the oldest project.
+ * @minimum 1
+ */
+ team_id?: number;
+ /**
+ * Why the account audit is being requested.
+ * @maxLength 500
+ */
+ reason: string;
+ /**
+ * Project ID containing the skill in this region. Audit credentials authorize reading skills from any project.
+ * @minimum 1
+ */
+ skill_project: number;
+ /**
+ * Name of the single-file skill in skill_project. Uses its latest active version.
+ * @maxLength 64
+ */
+ skill_name: string;
+ }
+
+ export interface AccountAuditStartResponse {
+ /** Native task run executing the account audit. */
+ task_run_id: string;
+ /** Resolved target team ID. */
+ team_id: number;
+ }
+
/**
* Metadata for one message a channel summary covered — never the message text.
*/
@@ -85785,6 +85822,7 @@ export namespace Schemas {
/**
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -85815,6 +85853,7 @@ export namespace Schemas {
export const TaskOriginProductEnum = {
Onboarding: 'onboarding',
+ AccountAudit: 'account_audit',
ErrorTracking: 'error_tracking',
EvalClusters: 'eval_clusters',
UserCreated: 'user_created',
@@ -85876,6 +85915,7 @@ export namespace Schemas {
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.
*
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -108684,6 +108724,7 @@ export namespace Schemas {
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.
*
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -110380,6 +110421,7 @@ export namespace Schemas {
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.
*
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -129675,6 +129717,7 @@ export namespace Schemas {
* Exclude tasks with this origin product from the results
*
* * `onboarding` - Onboarding
+ * * `account_audit` - Account audit
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -129823,6 +129866,7 @@ export namespace Schemas {
export const TasksListExcludeOriginProduct = {
Onboarding: 'onboarding',
+ AccountAudit: 'account_audit',
ErrorTracking: 'error_tracking',
EvalClusters: 'eval_clusters',
UserCreated: 'user_created',
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index 1ae7c0ec04ad..caa350b28a0b 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -187,6 +187,7 @@ export const TasksListQueryParams = () => zod.object({
exclude_origin_product: zod
.enum([
'onboarding',
+ 'account_audit',
'error_tracking',
'eval_clusters',
'user_created',
@@ -214,7 +215,7 @@ export const TasksListQueryParams = () => zod.object({
])
.optional()
.describe(
- 'Exclude tasks with this origin product from the results\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ 'Exclude tasks with this origin product from the results\n\n\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
),
hog_flow_id: zod
.string()
@@ -325,6 +326,7 @@ export const TasksCreateBody = () => zod.object({
origin_product: zod
.enum([
'onboarding',
+ 'account_audit',
'error_tracking',
'eval_clusters',
'user_created',
@@ -351,11 +353,11 @@ export const TasksCreateBody = () => zod.object({
'metrics_import',
])
.describe(
- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ '\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `account_audit` - Account audit\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `autoresearch` - Autoresearch\n\* `signals_scout` - Signals Scout\n\* `scout_suggestions` - Signals Scout Suggestions\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow\n\* `space_setup` - Space Setup\n\* `business_knowledge` - Business Knowledge\n\* `metrics_import` - Metrics Import'
),
repository: zod
.string()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json
index 68601af595ba..19d436cd7789 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json
@@ -39,9 +39,10 @@
"type": "number"
},
"exclude_origin_product": {
- "description": "Exclude tasks with this origin product from the results\n\n* `onboarding` - Onboarding\n* `error_tracking` - Error Tracking\n* `eval_clusters` - Eval Clusters\n* `user_created` - User Created\n* `slack` - Slack\n* `support_queue` - Support Queue\n* `session_summaries` - Session Summaries\n* `posthog_ai` - PostHog AI\n* `experiments` - Experiments\n* `signal_report` - Signal Report\n* `autoresearch` - Autoresearch\n* `signals_scout` - Signals Scout\n* `scout_suggestions` - Signals Scout Suggestions\n* `support_reply` - Support Reply\n* `hogdesk` - HogDesk\n* `review_hog` - ReviewHog\n* `image_builder` - Image Builder\n* `loop` - Loop\n* `mcp_analytics` - MCP Analytics\n* `signals_chat` - Signals Chat\n* `task_analysis` - Task Analysis\n* `workflow` - Workflow\n* `space_setup` - Space Setup\n* `business_knowledge` - Business Knowledge\n* `metrics_import` - Metrics Import",
+ "description": "Exclude tasks with this origin product from the results\n\n* `onboarding` - Onboarding\n* `account_audit` - Account audit\n* `error_tracking` - Error Tracking\n* `eval_clusters` - Eval Clusters\n* `user_created` - User Created\n* `slack` - Slack\n* `support_queue` - Support Queue\n* `session_summaries` - Session Summaries\n* `posthog_ai` - PostHog AI\n* `experiments` - Experiments\n* `signal_report` - Signal Report\n* `autoresearch` - Autoresearch\n* `signals_scout` - Signals Scout\n* `scout_suggestions` - Signals Scout Suggestions\n* `support_reply` - Support Reply\n* `hogdesk` - HogDesk\n* `review_hog` - ReviewHog\n* `image_builder` - Image Builder\n* `loop` - Loop\n* `mcp_analytics` - MCP Analytics\n* `signals_chat` - Signals Chat\n* `task_analysis` - Task Analysis\n* `workflow` - Workflow\n* `space_setup` - Space Setup\n* `business_knowledge` - Business Knowledge\n* `metrics_import` - Metrics Import",
"enum": [
"onboarding",
+ "account_audit",
"error_tracking",
"eval_clusters",
"user_created",
diff --git a/tach.toml b/tach.toml
index c4c12c8ff73a..1bf91aa7246d 100644
--- a/tach.toml
+++ b/tach.toml
@@ -83,6 +83,7 @@ layer = "modules"
[[modules]]
path = "posthog"
depends_on = [
+ "products.account_audits",
"products.alerts_platform",
"products.ai_training",
"products.autoresearch",
@@ -1735,3 +1736,17 @@ expose = [
from = [
"products.github_commands",
]
+
+[[modules]]
+path = "products.account_audits"
+depends_on = ["posthog", "products.notebooks", "products.signals", "products.skills", "products.tasks"]
+layer = "modules"
+
+[[interfaces]]
+expose = [
+ "backend\\.facade.*",
+ "backend\\.presentation\\.views.*",
+]
+from = [
+ "products.account_audits",
+]