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(wizard): add cloud wizard run endpoint and workflow integration (#66168)

Rafael Audibert93ffd92981df
diff --git a/.agents/skills/debugging-local-task-agent-runs/SKILL.md b/.agents/skills/debugging-local-task-agent-runs/SKILL.md
new file mode 100644
index 000000000000..6b96761ab92f
--- /dev/null
+++ b/.agents/skills/debugging-local-task-agent-runs/SKILL.md
@@ -0,0 +1,114 @@
+---
+name: debugging-local-task-agent-runs
+description: Debug the output of local PostHog task runs — the wizard cloud-run path that executes inside a Docker sandbox under the local Temporal `process-task` workflow (the wizard that integrates PostHog, then the coding agent that commits and opens the PR). Use when a local run looks stuck, failed, or silent, or when you need to read the wizard or agent logs. Covers the `.env.local` keys + `ai_features` intent required for cloud runs locally, finding the task UUID (docker ps, temporal CLI, Temporal UI at localhost:8081), tailing live logs inside the sandbox container (`/tmp/posthog-wizard.log`, `/tmp/agent-server.log`), and reading the durable per-run console log from object storage after the sandbox is torn down. Trigger terms: task-sandbox, run_wizard, agent-server, process-task, SANDBOX_PROVIDER, LLM_GATEWAY, cloud_run, posthog-wizard.log.
+---
+
+# Debugging local task/agent runs
+
+A "cloud run" of the Tasks product (e.g. the setup-wizard `cloud_run` endpoint) executes as the Temporal **`process-task`** workflow on the `development-task-queue`. Locally (`SANDBOX_PROVIDER=docker`) each run gets a **Docker sandbox container** in which two things happen in sequence:
+
+1. **`run_wizard`** activity — runs the published `@posthog/wizard` to integrate PostHog (writes `/tmp/posthog-wizard.log`).
+2. **`agent-server`** — the coding agent that commits the wizard's changes, opens the PR, and keeps it green (writes `/tmp/agent-server.log`).
+
+The hard part of debugging is that **the Temporal UI doesn't show this output** — workflow result/failure payloads are `binary/encrypted`, and the activity captures the wizard/agent output to the run's logs, not to the timeline. This skill is how you actually read it.
+
+## Prerequisites: env for local cloud runs
+
+Cloud runs only work locally if **all** of these are set in `.env.local` (values shown are the local targets — never commit real secrets). Inside the Docker sandbox, `localhost` is the container itself, so PostHog URLs use `host.docker.internal`.
+
+| Key | Purpose / local value |
+| ------------------------------- | ------------------------------------------------------------------------------------------------------ |
+| `SANDBOX_PROVIDER` | `"docker"` — route sandboxes to local Docker instead of Modal |
+| `SANDBOX_MCP_URL` | `"http://host.docker.internal:8787/mcp"` — MCP server the agent uses |
+| `SANDBOX_LLM_GATEWAY_URL` | `"http://host.docker.internal:3308"` — local LLM gateway the agent routes model calls through |
+| `SANDBOX_JWT_PRIVATE_KEY` | signs the scoped sandbox tokens |
+| `GITHUB_APP_CLIENT_ID` | your local GitHub App (clone + PR) |
+| `GITHUB_APP_CLIENT_SECRET` | "" |
+| `GITHUB_APP_SLUG` | "" |
+| `GITHUB_APP_PRIVATE_KEY` | "" |
+| `LLM_GATEWAY_ANTHROPIC_API_KEY` | real Anthropic key the **local gateway** proxies to (read via the gateway's `LLM_GATEWAY_` env prefix) |
+
+Two non-env requirements, or the keys above are inert:
+
+- **The LLM gateway must actually be running on `:3308`.** It's gated behind the `llm_gateway` capability — enable the **`ai_features`** intent (`hogli dev:setup`) so the `llm-gateway` proc starts. `SANDBOX_LLM_GATEWAY_URL` pointing at a dead port just yields `ConnectionRefused` from the agent.
+- **The wizard OAuth app must exist** — `bin/ensure-local-setup` provisions it and sets `WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID`; without it the `cloud_run` endpoint returns 404 "not available".
+
+After editing `.env.local`, **restart the stack** — env is read at process start, not hot-reloaded.
+
+## Step 1 — find the task UUID
+
+You need the **task UUID** for the container, and sometimes the **run UUID** for the durable log. The workflow id encodes both: `task-processing-<task_id>-<run_id>`.
+
+Fastest (no Temporal needed — the sandbox container name carries the task UUID):
+
+```bash
+docker ps --format '{{.Names}}' | grep task-sandbox
+# task-sandbox-<TASK_ID>-<suffix>
+```
+
+From the Temporal CLI (lists running/recent `process-task` workflows with both UUIDs):
+
+```bash
+docker exec posthog-temporal-admin-tools-1 \
+ temporal workflow list --address temporal:7233 --namespace default --limit 10 \
+ | grep process-task
+# task-processing-<TASK_ID>-<RUN_ID> process-task Running
+```
+
+From the **Temporal UI** — http://localhost:8081, open the `process-task` workflow; the id in the URL is `task-processing-<TASK_ID>-<RUN_ID>`.
+
+## Step 2 — tail live logs inside the sandbox (while it's running)
+
+The wizard and agent write line-by-line to files in the container **as they run**, so this is the only way to watch progress live (the activity buffers stdout and only flushes to the durable log when it finishes).
+
+```bash
+TASK_ID=<task-uuid-from-step-1>
+CID=$(docker ps -q --filter "name=task-sandbox-$TASK_ID")
+
+docker exec "$CID" tail -f /tmp/posthog-wizard.log # wizard stage (full agent SDK detail)
+docker exec "$CID" tail -f /tmp/agent-server.log # agent stage (commit + PR + CI loop)
+```
+
+Both files are JSON-heavy. For just the readable activity:
+
+```bash
+docker exec "$CID" tail -f /tmp/agent-server.log \
+ | grep -iE '"text"|tool_use|error|✔|✖|commit|PR|CI'
+```
+
+These files vanish when the sandbox is torn down (on run completion/failure), so grab them while the container is up.
+
+## Step 3 — read the durable per-run console log (after teardown)
+
+Everything the wizard and agent emit is persisted to the run's console log in object storage at `tasks/logs/team_<id>/task_<id>/run_<run_id>.jsonl`. This survives teardown. Read it with the run UUID (last UUID of the workflow id; or `TaskRun.objects.filter(task_id=...).latest("created_at")`):
+
+```bash
+RUN_ID=<run-uuid>
+flox activate -- bash -c "python manage.py shell <<'PY'
+import json
+from products.tasks.backend.models import TaskRun
+from posthog.storage import object_storage
+tr = TaskRun.objects.get(id='$RUN_ID')
+print('status:', tr.status)
+for line in (object_storage.read(tr.log_url, missing_ok=True) or '').splitlines():
+ n = json.loads(line).get('notification', {}); m = n.get('method'); p = n.get('params', {})
+ if m == '_posthog/console':
+ print(f\"[{p.get('level')}] {p.get('message','')[:300]}\")
+ elif m == 'session/update': # the agent stage (ACP stream)
+ u = p.get('update', {}); t = u.get('sessionUpdate')
+ if t == 'tool_call': print(' tool→', u.get('title') or u.get('kind'))
+ elif t == 'tool_call_update' and u.get('status'): print(' tool✓', u.get('status'))
+PY"
+```
+
+Notes on what you'll (not) see here:
+
+- **Wizard stdout/verbose** lands as `_posthog/console` debug events, but only **after `run_wizard` finishes** (buffered `sandbox.execute`). Mid-run, use Step 2.
+- **Agent prose is filtered out.** `append_log` drops `agent_message_chunk` events to keep the log lean, so the durable log shows _what the agent did_ (tool calls, commits, progress) but not its narration. For the agent's reasoning, read `/tmp/agent-server.log` in the container (Step 2) before teardown.
+
+## Common failure signatures
+
+- **`Could not determine cloud region from access token`** — the wizard hit cloud auth instead of your local instance. Local needs the wizard pointed at the local base URL; see `run_wizard._build_wizard_command` (`--base-url`, DEBUG-gated).
+- **`Unable to connect to API (ConnectionRefused)`** from the agent — `LLM_GATEWAY_URL=UNSET` or the gateway isn't on `:3308`. Check `SANDBOX_LLM_GATEWAY_URL` + the `ai_features` intent (gateway proc).
+- **Auth/4xx from the gateway** — the gateway is reachable but has no upstream provider key (`LLM_GATEWAY_ANTHROPIC_API_KEY`) or the token lacks `llm_gateway:read`.
+- **Workflow "running" but nothing happening** — it's in the wait loop (CI follow-up / inactivity). The workflow's Temporal **Current Details** field names what it's waiting on.
diff --git a/.env.development b/.env.development
index 27e9a304a15e..41a11dddcd23 100644
--- a/.env.development
+++ b/.env.development
@@ -81,3 +81,8 @@ PYDEVD_DISABLE_FILE_VALIDATION=1
# against the same key. All three sides MUST agree. See
# services/agent-shared/src/runtime/internal-jwt.ts.
AGENT_INTERNAL_SIGNING_KEY=dev-internal-signing-key-do-not-use-in-prod
+
+# Setup wizard cloud runs — local-only OAuth app client_id, created by bin/ensure-local-setup on
+# `hogli start`. Same ID as POSTHOG_DEV_CLIENT_ID in @posthog/wizard.
+WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ
+
diff --git a/bin/ensure-local-setup b/bin/ensure-local-setup
new file mode 100755
index 000000000000..c78aa72ad565
--- /dev/null
+++ b/bin/ensure-local-setup
@@ -0,0 +1,98 @@
+#!/usr/bin/env python
+# ruff: noqa: T201 — console output is the point of this bootstrap script
+"""Idempotent local-dev bootstrap.
+
+Runs on every `hogli start` (see bin/mprocs.yaml) and from `hogli dev:reset`. Every step must be
+idempotent and safe to re-run. Callers ensure the database and required tables are ready before
+invoking this: the mprocs unit waits via bin/wait-for-postgres-tables, and dev:reset runs it after
+migrations — so this script does no waiting of its own.
+"""
+
+import os
+import sys
+
+import django
+
+# This script lives in bin/, so the repo root isn't on sys.path the way it is for manage.py.
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+django.setup()
+
+from django.conf import settings # noqa: E402
+from django.core.management import call_command # noqa: E402
+
+from posthog.models import OAuthApplication # noqa: E402
+
+# What the wizard's agent step needs (mirrors @posthog/wizard's WIZARD_PROVISIONING_SCOPES). Local-dev
+# convenience only — no need to track the published wizard forever.
+WIZARD_SCOPES = [
+ "user:read",
+ "project:read",
+ "llm_gateway:read",
+ "dashboard:write",
+ "insight:write",
+ "query:read",
+ "notebook:write",
+]
+
+
+def ensure_wizard_oauth_app() -> None:
+ """Create the wizard cloud-run OAuth app the backend mints tokens under.
+
+ Inlined rather than given its own management command — it only ever runs from here. The client_id
+ is a committed, local-only id (WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID), not @posthog/wizard's dev/QA id.
+ """
+ if not settings.DEBUG or settings.CLOUD_DEPLOYMENT:
+ print(" not a local dev environment - skipping wizard OAuth app")
+ return
+
+ client_id = settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID
+ if not client_id:
+ print(" WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID not set - skipping wizard OAuth app")
+ return
+
+ # The wizard's OAuth login flow uses a loopback callback on an ephemeral port (unused by the
+ # headless cloud run). A portless localhost URI matches any port — see validate_redirect_uri in
+ # posthog/api/oauth/views.py, which extends RFC 8252 §7.3 loopback flexibility to localhost.
+ redirect_uris = "http://localhost/callback"
+ app, created = OAuthApplication.objects.get_or_create(
+ client_id=client_id,
+ defaults={
+ "name": "PostHog Wizard (local dev)",
+ "client_type": OAuthApplication.CLIENT_PUBLIC,
+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ "redirect_uris": redirect_uris,
+ "algorithm": "RS256",
+ "scopes": WIZARD_SCOPES,
+ },
+ )
+ if not created and sorted(app.scopes) != sorted(WIZARD_SCOPES):
+ app.scopes = WIZARD_SCOPES
+ app.save(update_fields=["scopes"])
+ status = "updated scopes for"
+ else:
+ status = "created" if created else "already have"
+ print(f" {status} wizard OAuth app (client_id={client_id})")
+
+
+# Logs which step it is running so the output clearly shows what got set up. A failing step warns and
+# the rest still run — local setup must never abort the dev stack.
+STEPS = [
+ ("dev personal API key", lambda: call_command("setup_local_api_key")),
+ ("wizard cloud-run OAuth app", ensure_wizard_oauth_app),
+]
+
+
+def main() -> None:
+ print("=== ensure-local-setup: local-dev bootstrap ===")
+ for label, fn in STEPS:
+ print(f"\n→ {label}")
+ try:
+ fn()
+ except Exception as e:
+ print(f" WARNING: '{label}' failed: {e}")
+ print("Local setup complete")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index 195bff54978a..7cc79295f425 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -564,6 +564,17 @@ procs:
layer: Infrastructure
tech: Migrations
+ ensure-local-setup:
+ # Idempotent local-dev bootstrap (feature flags, dev API key, wizard OAuth app). phrocs has no
+ # depends_on, so wait for the tables it touches before running (same approach as
+ # migrate-clickhouse waiting on posthog_instancesetting).
+ shell: 'bin/wait-for-docker && bin/wait-for-postgres-tables posthog_featureflag posthog_personalapikey posthog_oauthapplication && bin/ensure-local-setup'
+ capability: core_infra
+ ready_pattern: 'Local setup complete'
+ groups:
+ layer: Infrastructure
+ tech: Setup
+
migrate-clickhouse:
# Wait on posthog_instancesetting because Django queries that table at
# import time -- it's created by migrate-postgres. Without the guard,
diff --git a/frontend/src/lib/components/MarkdownEditor/inline/inlineMarkdownSlashCommands.test.tsx b/frontend/src/lib/components/MarkdownEditor/inline/inlineMarkdownSlashCommands.test.tsx
index 45b88c8f7bd7..44973a8c6b5b 100644
--- a/frontend/src/lib/components/MarkdownEditor/inline/inlineMarkdownSlashCommands.test.tsx
+++ b/frontend/src/lib/components/MarkdownEditor/inline/inlineMarkdownSlashCommands.test.tsx
@@ -34,6 +34,7 @@ const PREFLIGHT_WITH_OBJECT_STORAGE = {
slack_service: { available: false },
data_warehouse_integrations: { hubspot: {}, salesforce: {} },
object_storage: true,
+ wizard_cloud_run_available: false,
} satisfies PreflightStatus
const PREFLIGHT_WITHOUT_OBJECT_STORAGE: PreflightStatus = {
diff --git a/frontend/src/lib/components/Superpowers/superpowersLogic.ts b/frontend/src/lib/components/Superpowers/superpowersLogic.ts
index 299213bc02c7..3ab8fba4422b 100644
--- a/frontend/src/lib/components/Superpowers/superpowersLogic.ts
+++ b/frontend/src/lib/components/Superpowers/superpowersLogic.ts
@@ -54,12 +54,7 @@ export const superpowersLogic = kea<superpowersLogicType>([
superpowersEnabled: [
(s) => [s.user, s.preflight],
(user, preflight) => {
- return (
- user?.is_staff ||
- user?.is_impersonated ||
- preflight?.is_debug ||
- preflight?.instance_preferences?.debug_queries
- )
+ return user?.is_staff || preflight?.is_debug || preflight?.instance_preferences?.debug_queries
},
],
mcpHintsDismissed: [
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 49b35f3a8f5f..c6a78163e318 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4518,6 +4518,7 @@ export interface PreflightStatus {
/** Public base URL of the LLM gateway, for per-gateway endpoint examples. Null until configured. */
ai_gateway_url?: string | null
object_storage: boolean
+ wizard_cloud_run_available: boolean
public_egress_ip_addresses?: string[]
dev_disable_navigation_hooks?: boolean
}
diff --git a/hogli.yaml b/hogli.yaml
index c67d08c7790d..c89533b89108 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -303,7 +303,7 @@ core:
- name: dev:demo-data
cmd: python manage.py generate_demo_data --skip-flag-sync
- dev:sync-flags
- - dev:api-key
+ - ensure:local:setup
description: Full reset - wipe volumes, migrate, load demo data, sync flags
prompt: true
dev:api-key:
@@ -1121,3 +1121,7 @@ environment:
cmd: node dist/agent-proxy-server.mjs
description: 'Production entrypoint: run the agent-proxy Node service'
hidden: true
+ ensure:local:setup:
+ bin_script: ensure-local-setup
+ description: Idempotent local-dev bootstrap (e.g. the wizard OAuth app); runs automatically on hogli start
+ hidden: true
diff --git a/posthog/api/test/test_preflight.py b/posthog/api/test/test_preflight.py
index 88f2c9c215d2..f713792a722b 100644
--- a/posthog/api/test/test_preflight.py
+++ b/posthog/api/test/test_preflight.py
@@ -54,6 +54,7 @@ class TestPreflight(APIBaseTest, QueryMatchingTest):
"slack_service": {"available": False, "client_id": None},
"object_storage": False,
"public_egress_ip_addresses": [],
+ "wizard_cloud_run_available": False,
**options,
}
@@ -124,6 +125,18 @@ class TestPreflight(APIBaseTest, QueryMatchingTest):
assert response == self.preflight_authenticated_dict({"object_storage": True})
assert {"Europe/Moscow": 3, "UTC": 0}.items() <= available_timezones.items()
+ def test_preflight_request_with_wizard_cloud_run_available(self):
+ self.client.logout()
+ with self.is_cloud(False):
+ with self.settings(
+ OBJECT_STORAGE_ENABLED=False,
+ WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id",
+ ):
+ response = self.client.get("/_preflight/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == self.preflight_dict({"wizard_cloud_run_available": True})
+
@pytest.mark.ee
def test_cloud_preflight_request_unauthenticated(self):
set_instance_setting("EMAIL_HOST", "localhost")
diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.py
index 058d0bbba4f9..b95e3680c6e2 100644
--- a/posthog/api/wizard/http.py
+++ b/posthog/api/wizard/http.py
@@ -2,11 +2,14 @@ from __future__ import annotations
import json
import hashlib
+from typing import cast
+from django.conf import settings
from django.core.cache import cache
from django.utils.crypto import get_random_string
import posthoganalytics
+from drf_spectacular.utils import extend_schema
from google.genai.types import GenerateContentConfig, Schema
from openai.types.chat import (
ChatCompletionMessageParam,
@@ -23,14 +26,22 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.wizard.utils import json_schema_to_gemini_schema
-from posthog.auth import OAuthAccessTokenAuthentication
+from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication
from posthog.cloud_utils import get_api_host
from posthog.exceptions_capture import capture_exception
+from posthog.models import User
from posthog.models.project import Project
from posthog.permissions import APIScopePermission
-from posthog.rate_limit import SetupWizardAuthenticationRateThrottle, SetupWizardQueryRateThrottle
+from posthog.rate_limit import (
+ SetupWizardAuthenticationRateThrottle,
+ SetupWizardCloudRunBurstRateThrottle,
+ SetupWizardCloudRunSustainedRateThrottle,
+ SetupWizardQueryRateThrottle,
+)
from posthog.user_permissions import UserPermissions
+from products.tasks.backend.facade import api as tasks_facade
+
SETUP_WIZARD_CACHE_PREFIX = "setup-wizard:v1:"
SETUP_WIZARD_CACHE_TIMEOUT = 600
SETUP_WIZARD_DEFAULT_MODEL = "gpt-5-mini"
@@ -82,6 +93,38 @@ class SetupWizardQuerySerializer(serializers.Serializer):
return value
+class SetupWizardCloudRunSerializer(serializers.Serializer):
+ project_id = serializers.IntegerField(
+ help_text="ID of the PostHog project to integrate PostHog into. The authenticated user must have access to it."
+ )
+ repository = serializers.CharField(
+ help_text=(
+ "GitHub repository to set up PostHog in, as 'owner/repo' (e.g. 'posthog/posthog-js'). The user "
+ "must have a connected GitHub integration with access to it."
+ )
+ )
+ branch = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Base branch the wizard's pull request should target. Defaults to the repository's default branch.",
+ )
+
+ def validate_repository(self, value: str) -> str:
+ repository = value.strip()
+ parts = repository.split("/")
+ if len(parts) != 2 or not all(parts):
+ raise serializers.ValidationError("Repository must be in 'owner/repo' format.")
+ return repository
+
+
+class SetupWizardCloudRunResponseSerializer(serializers.Serializer):
+ task_id = serializers.CharField(
+ help_text="ID of the created task. Poll the tasks API for its status and the resulting pull request URL."
+ )
+ run_id = serializers.CharField(help_text="ID of the task's run.")
+ status = serializers.CharField(help_text="Initial status of the run (e.g. 'queued').")
+
+
class SetupWizardViewSet(viewsets.ViewSet):
permission_classes = ()
lookup_field = "hash"
@@ -341,8 +384,8 @@ class SetupWizardViewSet(viewsets.ViewSet):
project = Project.objects.get(id=project_id)
# Verify user has access to this project
- visible_teams_ids = UserPermissions(request.user).team_ids_visible_for_user
- if project.id not in visible_teams_ids:
+ visible_project_ids = UserPermissions(request.user).project_ids_visible_for_user
+ if project.id not in visible_project_ids:
raise serializers.ValidationError(
{"projectId": ["You don't have access to this project."]}, code="permission_denied"
)
@@ -369,3 +412,62 @@ class SetupWizardViewSet(viewsets.ViewSet):
cache.set(cache_key, wizard_data, SETUP_WIZARD_CACHE_TIMEOUT)
return response.Response({"success": True}, status=200)
+
+ @extend_schema(
+ request=SetupWizardCloudRunSerializer,
+ responses={200: SetupWizardCloudRunResponseSerializer},
+ )
+ @action(
+ methods=["POST"],
+ detail=False,
+ url_path="cloud_run",
+ authentication_classes=[SessionAuthentication],
+ permission_classes=[IsAuthenticated],
+ throttle_classes=[SetupWizardCloudRunBurstRateThrottle, SetupWizardCloudRunSustainedRateThrottle],
+ )
+ def cloud_run(self, request: Request) -> Response:
+ """Run the PostHog setup wizard in the cloud against the user's GitHub repository.
+
+ Provisions a task-run sandbox that runs the published wizard headlessly to integrate PostHog,
+ then hands off to the task agent to open the pull request and keep it green. The wizard
+ authenticates with a dedicated, scoped token minted under the wizard's own OAuth app — distinct
+ from the agent's sandbox token. This is the cloud alternative to copy-pasting the wizard command
+ to run locally; it is intentionally rate limited heavily because each run starts a sandbox.
+ """
+ if not bool(settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID):
+ raise exceptions.NotFound("Running the setup wizard in the cloud is not available.")
+
+ serializer = SetupWizardCloudRunSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ project_id = serializer.validated_data["project_id"]
+ repository = serializer.validated_data["repository"]
+ branch = serializer.validated_data.get("branch") or None
+
+ visible_project_ids = UserPermissions(cast(User, request.user)).project_ids_visible_for_user
+ try:
+ # nosemgrep: idor-lookup-without-org, idor-taint-user-input-to-org-model (permission check below)
+ project = Project.objects.get(id=project_id)
+ except Project.DoesNotExist:
+ raise serializers.ValidationError({"project_id": [ERROR_PROJECT_NOT_FOUND]}, code="not_found")
+ if project.id not in visible_project_ids:
+ raise exceptions.PermissionDenied("You don't have access to this project.")
+
+ try:
+ result = tasks_facade.create_wizard_cloud_run(
+ team=project.passthrough_team,
+ user_id=cast(User, request.user).id,
+ repository=repository,
+ branch=branch,
+ )
+ except ValueError as e:
+ # e.g. the team/user has no GitHub integration with access to the repository.
+ raise exceptions.ValidationError(str(e))
+
+ latest_run = result.latest_run
+ return Response(
+ {
+ "task_id": str(result.task_id),
+ "run_id": str(latest_run.id) if latest_run else "",
+ "status": latest_run.status if latest_run else "queued",
+ }
+ )
diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.py
index 0f6acfd82fa0..0eddec4c93cd 100644
--- a/posthog/api/wizard/test/test_http.py
+++ b/posthog/api/wizard/test/test_http.py
@@ -11,7 +11,8 @@ from rest_framework import status
from posthog.api.wizard.http import SETUP_WIZARD_CACHE_PREFIX, SETUP_WIZARD_CACHE_TIMEOUT
from posthog.cloud_utils import get_api_host
-from posthog.models import Organization, User
+from posthog.models import Organization, PersonalAPIKey, User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
class SetupWizardTests(APIBaseTest):
@@ -448,3 +449,85 @@ class SetupWizardTests(APIBaseTest):
def tearDown(self):
super().tearDown()
cache.clear() # Clears out all DRF throttle data
+
+
+@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")
+class SetupWizardCloudRunTests(APIBaseTest):
+ CLOUD_RUN_URL = "/api/wizard/cloud_run"
+
+ @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="")
+ def test_returns_404_when_feature_not_configured(self):
+ response = self.client.post(
+ self.CLOUD_RUN_URL,
+ data={"project_id": self.team.id, "repository": "acme/app"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ @patch("posthog.api.wizard.http.tasks_facade.create_wizard_cloud_run")
+ def test_creates_run_and_returns_ids(self, mock_create):
+ mock_create.return_value = MagicMock(task_id="task-uuid", latest_run=MagicMock(id="run-uuid", status="queued"))
+
+ response = self.client.post(
+ self.CLOUD_RUN_URL,
+ data={"project_id": self.team.id, "repository": "acme/app", "branch": ""},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json() == {"task_id": "task-uuid", "run_id": "run-uuid", "status": "queued"}
+ assert mock_create.call_count == 1
+ kwargs = mock_create.call_args.kwargs
+ assert kwargs["repository"] == "acme/app"
+ assert kwargs["user_id"] == self.user.id
+ assert kwargs["branch"] is None
+ assert kwargs["team"].id == self.team.id
+
+ @patch("posthog.api.wizard.http.tasks_facade.create_wizard_cloud_run")
+ def test_rejects_invalid_repository_format(self, mock_create):
+ response = self.client.post(
+ self.CLOUD_RUN_URL,
+ data={"project_id": self.team.id, "repository": "not-a-repo"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ mock_create.assert_not_called()
+
+ @patch("posthog.api.wizard.http.tasks_facade.create_wizard_cloud_run")
+ def test_rejects_personal_api_key_auth(self, mock_create):
+ # Cloud run is a UI/session-only action — an API token must not be able to start a run,
+ # even with a broad scope, since the project visibility check below wouldn't honor token scopes.
+ api_key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user,
+ label="Test API Key",
+ secure_value=hash_key_value(api_key_value),
+ scopes=["*"],
+ )
+ self.client.logout()
+
+ response = self.client.post(
+ self.CLOUD_RUN_URL,
+ data={"project_id": self.team.id, "repository": "acme/app"},
+ format="json",
+ headers={"authorization": f"Bearer {api_key_value}"},
+ )
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ mock_create.assert_not_called()
+
+ def test_rejects_project_without_access(self):
+ other_org = Organization.objects.create(name="Other Cloud Run Org")
+ other_user = User.objects.create_and_join(other_org, "[email protected]", None)
+ self.client.force_login(other_user)
+
+ response = self.client.post(
+ self.CLOUD_RUN_URL,
+ data={"project_id": self.team.id, "repository": "acme/app"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def tearDown(self):
+ super().tearDown()
+ cache.clear() # Clears out all DRF throttle data
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 6449571b3779..a4e8eb831cf2 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -833,6 +833,18 @@ class SetupWizardQueryRateThrottle(SimpleRateThrottle):
return f"throttle_wizard_query_{sha_hash}"
+class SetupWizardCloudRunBurstRateThrottle(UserRateThrottle):
+ # "Run the setup wizard in the cloud" provisions a Modal sandbox and runs an LLM agent per call,
+ # so cap it hard per user — a couple per hour only, with an absolute daily ceiling (sustained throttle below).
+ scope = "wizard_cloud_run_burst"
+ rate = "2/hour"
+
+
+class SetupWizardCloudRunSustainedRateThrottle(UserRateThrottle):
+ scope = "wizard_cloud_run_day"
+ rate = "5/day"
+
+
class SymbolSetUploadBurstRateThrottle(PersonalApiKeyRateThrottle):
scope = "symbol_set_upload_burst"
rate = "1200/minute"
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index ff6cebe8ff0c..ba1492b2b76f 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -47,6 +47,12 @@ SANDBOX_API_URL: str | None = get_from_env("SANDBOX_API_URL", None, optional=Tru
SANDBOX_LLM_GATEWAY_URL: str | None = get_from_env("SANDBOX_LLM_GATEWAY_URL", None, optional=True)
SANDBOX_MCP_URL: str | None = get_from_env("SANDBOX_MCP_URL", None, optional=True)
+# client_id of the OAuthApplication used to mint the access token the PostHog setup wizard
+# uses when it runs inside a task sandbox (the "run the wizard in the cloud" onboarding path).
+# It must be the wizard's own app so the LLM gateway authorizes the token like a normal wizard
+# run and the token carries the wizard's scope ceiling. Empty disables cloud wizard runs.
+WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID: str = get_from_env("WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID", "")
+
# When True, cloud-to-cloud resume boots from a Modal filesystem snapshot taken at
# end-of-run. When False, no Modal snapshot is taken and resume relies on the
# git-checkpoint mechanism in the agent server (same path as local-to-cloud handoff).
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index b7d106a655d1..0c75d2c57374 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -1,11 +1,12 @@
from datetime import timedelta
from typing import Literal
+from django.conf import settings
from django.utils import timezone
from posthog.models import OAuthAccessToken, OAuthApplication
from posthog.models.utils import generate_random_oauth_access_token
-from posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, OAUTH_HIDDEN_SCOPE_OBJECTS
+from posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, OAUTH_HIDDEN_SCOPE_OBJECTS, resolve_ceiling
from posthog.utils import get_instance_region
ARRAY_APP_CLIENT_ID_US = "HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W"
@@ -179,6 +180,21 @@ def get_sandbox_oauth_app(application: SandboxOAuthApplication = "array") -> OAu
return get_array_app()
+def _mint_oauth_access_token(user, team_id: int, *, app: OAuthApplication, scopes: list[str]) -> str:
+ token_value = generate_random_oauth_access_token(None)
+
+ OAuthAccessToken.objects.create(
+ user=user,
+ application=app,
+ token=token_value,
+ expires=timezone.now() + timedelta(seconds=TOKEN_EXPIRATION_SECONDS),
+ scope=" ".join(dict.fromkeys(scopes)),
+ scoped_teams=[team_id],
+ )
+
+ return token_value
+
+
def create_oauth_access_token_for_user(
user,
team_id: int,
@@ -189,15 +205,25 @@ def create_oauth_access_token_for_user(
) -> str:
resolved = resolve_scopes(scopes, include_internal_scopes=include_internal_scopes)
app = get_sandbox_oauth_app(application)
- token_value = generate_random_oauth_access_token(None)
+ return _mint_oauth_access_token(user, team_id, app=app, scopes=list(resolved))
- OAuthAccessToken.objects.create(
- user=user,
- application=app,
- token=token_value,
- expires=timezone.now() + timedelta(seconds=TOKEN_EXPIRATION_SECONDS),
- scope=" ".join(resolved),
- scoped_teams=[team_id],
+
+def get_wizard_app() -> OAuthApplication:
+ return _get_oauth_app_for_client_id(
+ settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID, "PostHog Wizard", get_instance_region()
)
- return token_value
+
+def create_wizard_oauth_access_token_for_user(user, team_id: int) -> str:
+ """Mint an OAuth access token under the wizard's own app for a cloud wizard run.
+
+ Deliberately separate from the sandbox/agent token (`create_oauth_access_token_for_user`) so the
+ wizard's scopes stay independent of the agent's. Uses the wizard app's configured scope ceiling.
+ """
+ app = get_wizard_app()
+
+ ceiling = resolve_ceiling(app.ceiling_scopes)
+ if ceiling is None or len(ceiling) == 0:
+ raise RuntimeError("Wizard app has no scope ceiling. Must be configured in the database.")
+
+ return _mint_oauth_access_token(user, team_id, app=app, scopes=sorted(ceiling))
diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.py
index f975679c8347..4d31bba042f1 100644
--- a/posthog/temporal/tests/test_oauth.py
+++ b/posthog/temporal/tests/test_oauth.py
@@ -11,10 +11,13 @@ from posthog.temporal.oauth import (
SCOUT_INTERNAL_SCOPES,
SCOUT_USER_WRITE_SCOPES,
create_oauth_access_token_for_user,
+ create_wizard_oauth_access_token_for_user,
has_write_scopes,
resolve_scopes,
)
+_WIZARD_CLIENT_ID = "wizard-test-client-id"
+
class TestResolveScopes(SimpleTestCase):
def test_read_only_preset(self) -> None:
@@ -165,3 +168,47 @@ class TestCreateOAuthAccessTokenForUser(TestCase):
with self.assertRaisesRegex(RuntimeError, "PostHog AI app not found"):
create_oauth_access_token_for_user(user, team.id, application="posthog_ai")
+
+
+class TestCreateWizardOAuthAccessTokenForUser(TestCase):
+ def _create_wizard_app(self, scopes: list[str]) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ client_id=_WIZARD_CLIENT_ID,
+ name="PostHog Wizard Test App",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="http://localhost:8237/callback",
+ algorithm="RS256",
+ scopes=scopes,
+ )
+
+ def _create_user_and_team(self) -> tuple[User, Team]:
+ organization = Organization.objects.create(name="Wizard OAuth test org")
+ team = Team.objects.create(organization=organization, name="Wizard OAuth test team")
+ user = User.objects.create(email="[email protected]")
+ return user, team
+
+ @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=_WIZARD_CLIENT_ID)
+ def test_mints_token_under_wizard_app_with_its_scopes(self) -> None:
+ # The token must be minted under the wizard's own app (so the gateway authorizes it like a normal wizard run)
+ # separate from the agent's sandbox token.
+ scopes = ["project:read", "insight:write", "llm_gateway:read"]
+ app = self._create_wizard_app(scopes=scopes)
+ user, team = self._create_user_and_team()
+
+ token = create_wizard_oauth_access_token_for_user(user, team.id)
+
+ assert token is not None
+ assert token.startswith("pha_")
+
+ access_token = OAuthAccessToken.objects.get(token=token)
+ assert access_token.application_id == app.id
+ assert access_token.scoped_teams == [team.id]
+ assert set(access_token.scope.split()) == set(scopes)
+
+ @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=_WIZARD_CLIENT_ID)
+ def test_requires_existing_app(self) -> None:
+ user, team = self._create_user_and_team()
+
+ with self.assertRaisesRegex(RuntimeError, "Wizard app not found"):
+ create_wizard_oauth_access_token_for_user(user, team.id)
diff --git a/posthog/views.py b/posthog/views.py
index d52380509bac..02be56e4c24c 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -220,6 +220,7 @@ def preflight_check(request: HttpRequest) -> JsonResponse:
},
"object_storage": in_cloud or _traced("preflight.is_object_storage_available", is_object_storage_available),
"public_egress_ip_addresses": settings.PUBLIC_EGRESS_IP_ADDRESSES,
+ "wizard_cloud_run_available": bool(settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID),
}
auth_brand = normalize_auth_brand(request.COOKIES.get(AUTH_BRAND_COOKIE))
if auth_brand:
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index 7ce8ad72b600..7efaa7eea47c 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -208,6 +208,7 @@ DEFAULT_TRUSTED_DOMAINS = [
RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS: frozenset[str] = frozenset(
{
"POSTHOG_PERSONAL_API_KEY",
+ "POSTHOG_WIZARD_API_KEY",
"POSTHOG_API_URL",
"POSTHOG_PROJECT_ID",
"JWT_PUBLIC_KEY",
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 438ae4937f20..ca21ec872f43 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -21,6 +21,7 @@ from datetime import datetime, timedelta
from typing import Any, Literal
from uuid import UUID, uuid4
+from django.conf import settings
from django.db import transaction
from django.db.models import CharField, Count, Exists, F, Min, OuterRef, Q, QuerySet, Subquery
from django.db.models.fields.json import KeyTextTransform
@@ -46,6 +47,7 @@ from products.tasks.backend.models import (
TaskAutomation,
TaskRun,
)
+from products.tasks.backend.prompts import WIZARD_PR_AGENT_PROMPT
from products.tasks.backend.visibility import task_run_visibility_q, task_visibility_q
from . import contracts
@@ -688,6 +690,42 @@ def create_and_run_task(
)
+def create_wizard_cloud_run(
+ *,
+ team,
+ user_id: int,
+ repository: str,
+ branch: str | None = None,
+) -> contracts.CreatedTaskDTO:
+ """Create + run a cloud setup-wizard task.
+
+ The workflow runs the published wizard in the sandbox (it integrates PostHog), then the agent
+ commits the changes, opens a PR on the user's repo, and keeps it green — it never implements
+ PostHog itself (see the wizard PR agent prompt). The wizard authenticates with its own scoped
+ token (see ``create_wizard_oauth_access_token``), independent of the agent's sandbox token, so
+ the agent runs with read-only PostHog scopes.``wizard_config`` marks the run so the workflow runs the wizard pre-agent step.
+
+ ``user_id`` is the person going through onboarding; it becomes the task's ``created_by`` so the
+ run is explicitly attributed to them.
+ """
+ return create_and_run_task(
+ team=team,
+ title="Set up PostHog",
+ description=WIZARD_PR_AGENT_PROMPT,
+ origin_product=Task.OriginProduct.ONBOARDING,
+ user_id=user_id,
+ repository=repository,
+ create_pr=True,
+ mode="background",
+ branch=branch,
+ wizard_config={},
+ posthog_mcp_scopes="read_only",
+ # The agent server boots idle; this is the message that actually kicks it off once ready
+ # (delivered by forward_pending_user_message). Without it the run stalls after "Started agent".
+ pending_user_message=WIZARD_PR_AGENT_PROMPT,
+ )
+
+
def create_task_without_run(
*,
team,
@@ -1156,6 +1194,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"sandbox_memory_gb",
"sandbox_ttl_seconds",
"inactivity_timeout_seconds",
+ "wizard_config",
}
)
@@ -1805,8 +1844,6 @@ def resolve_stream_base_url(*, distinct_id: str, organization_id: str | UUID) ->
read-via-proxy flag is enabled for the user, so rollout stays gradual and reversible. The
server owns this decision; clients just connect to whatever URL comes back.
"""
- from django.conf import settings # noqa: PLC0415 — keep settings access local to this helper
-
from products.tasks.backend.constants import STREAM_VIA_PROXY_FEATURE_FLAG # noqa: PLC0415
proxy_url = settings.TASKS_AGENT_PROXY_PUBLIC_URL
diff --git a/products/tasks/backend/migrations/0043_alter_task_origin_product.py b/products/tasks/backend/migrations/0043_alter_task_origin_product.py
new file mode 100644
index 000000000000..b552ee65eddb
--- /dev/null
+++ b/products/tasks/backend/migrations/0043_alter_task_origin_product.py
@@ -0,0 +1,33 @@
+# Generated by Django 5.2.14 on 2026-06-25 18:03
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0042_task_list_perf_indexes"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="task",
+ name="origin_product",
+ field=models.CharField(
+ choices=[
+ ("onboarding", "Onboarding"),
+ ("error_tracking", "Error Tracking"),
+ ("eval_clusters", "Eval Clusters"),
+ ("user_created", "User Created"),
+ ("automation", "Automation"),
+ ("slack", "Slack"),
+ ("support_queue", "Support Queue"),
+ ("session_summaries", "Session Summaries"),
+ ("posthog_ai", "PostHog AI"),
+ ("signal_report", "Signal Report"),
+ ("signals_scout", "Signals Scout"),
+ ("support_reply", "Support Reply"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 75756300bbcf..0ef9e1ab205b 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0042_task_list_perf_indexes
+0043_alter_task_origin_product
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 7ac2965a238e..cb5f52d4fb8b 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -58,6 +58,7 @@ def resolve_schema(schema: type[BaseModel] | dict) -> dict:
class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
class OriginProduct(models.TextChoices):
+ ONBOARDING = "onboarding", "Onboarding"
ERROR_TRACKING = "error_tracking", "Error Tracking"
EVAL_CLUSTERS = "eval_clusters", "Eval Clusters"
USER_CREATED = "user_created", "User Created"
@@ -343,6 +344,8 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
sandbox_resources: "SandboxResources | None" = None,
sandbox_timeout_seconds: int | None = None,
inactivity_timeout_seconds: int | None = None,
+ wizard_config: dict | None = None,
+ pending_user_message: str | None = None,
) -> tuple["Task", dict[str, Any]]:
"""Create the Task row and assemble the initial run's `extra_state`.
@@ -490,6 +493,17 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
if inactivity_timeout_seconds is not None:
extra_state["inactivity_timeout_seconds"] = inactivity_timeout_seconds
+ # Marks this as a cloud setup-wizard run: the workflow runs the wizard in the sandbox before
+ # the agent (see run_wizard activity / TaskProcessingContext.wizard_config).
+ if wizard_config is not None:
+ extra_state["wizard_config"] = wizard_config
+
+ # The first message handed to the agent once its server is ready (forward_pending_user_message
+ # reads it from run state). Without it a background run boots the agent idle — it never gets a
+ # prompt and just sits there while relay_sandbox_events waits for events that never come.
+ if pending_user_message:
+ extra_state["pending_user_message"] = pending_user_message
+
return task, extra_state
@staticmethod
@@ -567,6 +581,8 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
sandbox_timeout_seconds: int | None = None,
inactivity_timeout_seconds: int | None = None,
ai_stage: str | None = None,
+ wizard_config: dict | None = None,
+ pending_user_message: str | None = None,
) -> "Task":
from products.tasks.backend.temporal.client import execute_task_processing_workflow
@@ -593,6 +609,8 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
sandbox_timeout_seconds=sandbox_timeout_seconds,
inactivity_timeout_seconds=inactivity_timeout_seconds,
ai_stage=ai_stage,
+ wizard_config=wizard_config,
+ pending_user_message=pending_user_message,
)
task_run = task.create_run(mode=mode, extra_state=extra_state or None, branch=branch)
diff --git a/products/tasks/backend/prompts.py b/products/tasks/backend/prompts.py
new file mode 100644
index 000000000000..dd12653a2566
--- /dev/null
+++ b/products/tasks/backend/prompts.py
@@ -0,0 +1,50 @@
+WIZARD_PR_AGENT_PROMPT = """
+PostHog's setup wizard has already run in this repository and integrated PostHog. The working tree
+contains its uncommitted changes (modified source files, an updated package manifest, installed
+dependencies, a `posthog-setup-report.md` summary, and possibly a `.posthog-events.json` plan).
+
+The wizard's full console output is saved to `/tmp/wizard-cloud-run/wizard-output.log` (outside the
+repository, so it can never be committed). Read it whenever you need to understand what the wizard
+actually did - which files it touched, any warnings it printed, or why something in the working tree
+looks the way it does.
+
+Your job is NOT to integrate PostHog or write any product/instrumentation code. Do not add, remove,
+edit, or "improve" the PostHog setup the wizard produced, and do not create new PostHog events,
+dashboards, or insights. Your only responsibilities:
+
+1. Verify the project still builds, type-checks, and lints using the repo's existing scripts. If a
+ change the wizard made breaks the build, make the MINIMAL fix required to compile — do not
+ redesign or refactor.
+2. Commit the wizard's changes to a new branch called `posthog/instrumentation` with a clear
+ commit message. You should look at past commits to understand what's the convention for commit
+ messages in this repository. The commit message should resemble the concept of "Add PostHog to codebase".
+ - Do NOT commit `posthog-setup-report.md` or `.posthog-events.json` — they are a local reference
+ only. Make sure neither is staged or appears in the commit (leave them untracked, or exclude them).
+3. Attempt to identify how the codebase is deployed to production.
+ - If we can automatically configure the required environment variables in a file that will be read in production, do so.
+ - If you can't, simply make note of what values you'd need to set the environment variables to.
+ - You should know what the token is from the PostHog MCP server context. If you don't have access to the token,
+ you should run the `projects-get` tool to get the token.
+ - Commit the changes to the environment variables file to the new branch as a separate commit.
+4. Open a pull request. Write the PR description FROM the contents of `posthog-setup-report.md`:
+ - If there's a .github/pull_request_template.md, use it as a starting point.
+ - Summarize what the wizard changed (files, SDK, configuration).
+ - List EVERY PostHog insight and dashboard the wizard created, with their names and links from the report.
+ - Add a short "How to verify" section.
+ - You should include a section in the PR description explaining the environment variables situation.
+ If you've been able to automatically configure them, simply explain that PostHog will work automatically
+ as soon as the code gets deployed to production. If you've been unable to automatically configure
+ the environment variables, explain how to set them manually. If:
+ a. the project is in Javascript, assume the user is non-technical and carefully explain how to set them manually;
+ b. the project is in any other language, assume the user is technical and thus familiar with the
+ concept of environment variables.
+5. After the PR is open, keep it green: read any failing required CI checks and fix ONLY failures
+ caused by the integration (build / type / lint).
+
+Hard limits: stay strictly within the wizard's changes, plus the changes required to automatically
+configure the environment variables in production, plus the minimal fixes needed for CI to pass.
+When keeping CI green, do not modify unrelated code, add/remove/upgrade dependencies beyond
+what a failing required check requires, or touch `.github/workflows/**`, `CODEOWNERS`, or
+branch-protection config. If CI is red for reasons unrelated to the integration, note it as a comment
+in the PR rather than making broad changes.
+"""
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.py
index 6c2b1e3341cd..69904bd70612 100644
--- a/products/tasks/backend/temporal/__init__.py
+++ b/products/tasks/backend/temporal/__init__.py
@@ -34,6 +34,7 @@ from .process_task.activities import (
read_sandbox_logs,
refresh_sandbox_credentials,
relay_sandbox_events,
+ run_wizard,
send_followup_to_sandbox,
start_agent_server,
track_workflow_event,
@@ -63,6 +64,7 @@ ACTIVITIES = [
checkout_branch_in_sandbox,
get_sandbox_for_repository,
execute_task_in_sandbox,
+ run_wizard,
forward_pending_user_message,
relay_sandbox_events,
create_resume_snapshot,
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index c75912008f33..2010d5d4ceef 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -5,6 +5,7 @@ from posthog.temporal.oauth import (
PosthogMcpScopes,
SandboxOAuthApplication,
create_oauth_access_token_for_user as _create_oauth_access_token_for_user,
+ create_wizard_oauth_access_token_for_user as _create_wizard_oauth_access_token_for_user,
)
from products.tasks.backend.exceptions import OAuthTokenError, TaskInvalidStateError
@@ -16,6 +17,7 @@ __all__ = [
"ARRAY_APP_CLIENT_ID_US",
"create_oauth_access_token",
"create_oauth_access_token_for_user",
+ "create_wizard_oauth_access_token",
]
@@ -45,6 +47,25 @@ def create_oauth_access_token(task: Task, *, scopes: PosthogMcpScopes = "read_on
)
+def create_wizard_oauth_access_token(task: Task) -> str:
+ """Create the OAuth access token the setup wizard uses inside a cloud wizard run.
+
+ Minted under the wizard's own OAuthApplication with the wizard's scopes — kept separate from
+ the sandbox/agent token (`create_oauth_access_token`) so the two scope sets stay independent.
+ """
+ if not task.created_by:
+ raise TaskInvalidStateError(
+ f"Task {task.id} has no created_by user",
+ {"task_id": task.id},
+ cause=RuntimeError(f"Task {task.id} missing created_by field"),
+ )
+
+ try:
+ return _create_wizard_oauth_access_token_for_user(task.created_by, task.team_id)
+ except RuntimeError as err:
+ raise OAuthTokenError(str(err), {"team_id": task.team_id}, cause=err) from err
+
+
def create_oauth_access_token_for_user(
user,
team_id: int,
diff --git a/products/tasks/backend/temporal/process_task/activities/__init__.py b/products/tasks/backend/temporal/process_task/activities/__init__.py
index aa1891cd2afa..b73f679354e9 100644
--- a/products/tasks/backend/temporal/process_task/activities/__init__.py
+++ b/products/tasks/backend/temporal/process_task/activities/__init__.py
@@ -31,6 +31,7 @@ from .refresh_sandbox_credentials import (
refresh_sandbox_credentials,
)
from .relay_sandbox_events import RelaySandboxEventsInput, relay_sandbox_events
+from .run_wizard import RunWizardInput, run_wizard
from .send_followup_to_sandbox import SendFollowupToSandboxInput, send_followup_to_sandbox
from .start_agent_server import (
MarkRepoReadyInput,
@@ -62,6 +63,7 @@ __all__ = [
"PrepareSandboxForRepositoryInput",
"PrepareSandboxForRepositoryOutput",
"ReadSandboxLogsInput",
+ "RunWizardInput",
"RefreshSandboxCredentialsInput",
"RefreshSandboxCredentialsOutput",
"MarkRepoReadyInput",
@@ -87,6 +89,7 @@ __all__ = [
"prepare_sandbox_for_repository",
"read_sandbox_logs",
"refresh_sandbox_credentials",
+ "run_wizard",
"start_agent_server",
"launch_agent_server",
"await_agent_server_ready",
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 1fe3a6f31522..bf84810c7ff2 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -121,6 +121,12 @@ class TaskProcessingContext:
value = (self.state or {}).get("run_source")
return value if isinstance(value, str) else None
+ @property
+ def wizard_config(self) -> dict | None:
+ """Config for the pre-agent setup-wizard step (set at task creation); None for normal runs."""
+ value = (self.state or {}).get("wizard_config")
+ return value if isinstance(value, dict) else None
+
def inactivity_timeout(self) -> timedelta:
"""How long the run may sit idle before the workflow times it out.
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 3caa057addad..f019e13dc9a3 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -19,7 +19,7 @@ from products.tasks.backend.logic.services.connection_token import (
from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import StepTimer, increment_sandbox_created, increment_snapshot_usage
-from products.tasks.backend.temporal.oauth import create_oauth_access_token
+from products.tasks.backend.temporal.oauth import create_oauth_access_token, create_wizard_oauth_access_token
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
from products.tasks.backend.temporal.process_task.sandbox_credentials import set_git_remote_token
from products.tasks.backend.temporal.process_task.utils import (
@@ -228,6 +228,12 @@ def _build_environment_variables(
elif run_state.handoff_resumed:
environment_variables["POSTHOG_RESUME_RUN_ID"] = str(ctx.run_id)
+ # Cloud wizard runs get a SEPARATE token, minted under the wizard's own OAuth app with the
+ # wizard's scopes, so the wizard's access stays independent of the agent's sandbox token above.
+ # The run_wizard activity reads it from POSTHOG_WIZARD_API_KEY in the sandbox env.
+ if ctx.wizard_config is not None:
+ environment_variables["POSTHOG_WIZARD_API_KEY"] = create_wizard_oauth_access_token(task)
+
return environment_variables
diff --git a/products/tasks/backend/temporal/process_task/activities/run_wizard.py b/products/tasks/backend/temporal/process_task/activities/run_wizard.py
new file mode 100644
index 000000000000..236533f76a38
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/activities/run_wizard.py
@@ -0,0 +1,150 @@
+import shlex
+import logging
+from dataclasses import dataclass
+
+from django.conf import settings
+
+from temporalio import activity
+
+from posthog.temporal.common.utils import asyncify
+from posthog.utils import get_instance_region
+
+from products.tasks.backend.logic.services.sandbox import ExecutionResult, Sandbox
+from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
+
+from .get_task_processing_context import TaskProcessingContext
+
+logger = logging.getLogger(__name__)
+
+# Published npm package, pinned to @latest so cloud runs exercise the same build users install.
+WIZARD_PACKAGE = "@posthog/wizard@latest"
+
+# Large repos can take ~45 min to integrate (observed p99.9 of real runs). The Temporal activity's
+# start_to_close_timeout (see workflow._run_wizard_if_configured) must stay above this so the
+# wizard's own timeout is what bounds the run, not the activity wrapper killing it early.
+WIZARD_RUN_TIMEOUT_SECONDS = 45 * 60
+
+# GNU `timeout` exit code when it kills a command. We wrap the wizard in `timeout` (see
+# _build_wizard_command) so an over-budget run comes back as a normal result carrying this code —
+# which we detect below — instead of the sandbox-level TimeoutError that would discard partial output.
+WIZARD_TIMEOUT_EXIT_CODE = 124
+# Sandbox-level backstop, above the shell `timeout` so the clean 124 path fires first; the sandbox
+# only aborts the exec if `timeout` itself wedges.
+_SANDBOX_EXEC_TIMEOUT_SECONDS = WIZARD_RUN_TIMEOUT_SECONDS + 120
+
+# The wizard's console output is written OUTSIDE the cloned repo working tree so it can never be
+# committed to the user's PR by mistake. The downstream agent reads it from this fixed path to
+# understand what the wizard did (and why it failed).
+WIZARD_OUTPUT_DIR = "/tmp/wizard-cloud-run"
+WIZARD_OUTPUT_LOG_PATH = f"{WIZARD_OUTPUT_DIR}/wizard-output.log"
+
+# The wizard's own verbose log — agent-level detail beyond stdout (e.g. which URL a failed API call
+# hit). Fixed path inside the wizard (its src/utils/paths.ts: WIZARD_LOG_FILE). Lives only in the
+# sandbox filesystem, so it's lost once the sandbox is torn down — we surface it in DEBUG below.
+WIZARD_VERBOSE_LOG_PATH = "/tmp/posthog-wizard.log"
+
+
+@dataclass
+class RunWizardInput:
+ context: TaskProcessingContext
+ sandbox_id: str
+ repository: str
+
+
+def _wizard_region() -> str:
+ return "eu" if get_instance_region() == "EU" else "us"
+
+
+def _format_wizard_output(result: ExecutionResult) -> str:
+ sections = [f"PostHog setup wizard output (exit code {result.exit_code})"]
+ if result.stdout:
+ sections += ["", "=== stdout ===", result.stdout]
+ if result.stderr:
+ sections += ["", "=== stderr ===", result.stderr]
+ return "\n".join(sections) + "\n"
+
+
+def _build_wizard_command(repo_path: str, project_id: int) -> str:
+ # The wizard reads its access token from the POSTHOG_WIZARD_API_KEY env var injected into the
+ # sandbox (see provision_sandbox), so the token never appears on the command line.
+ # --headless-DONOTUSE-EXPERIMENTAL runs the published wizard non-interactively.
+ parts = [
+ f"cd {shlex.quote(repo_path)} &&",
+ # Wrap in `timeout` so an over-budget run exits WIZARD_TIMEOUT_EXIT_CODE (124) we can
+ # detect, with partial output preserved. -k 30 escalates to SIGKILL 30s after SIGTERM.
+ f"timeout -k 30 {WIZARD_RUN_TIMEOUT_SECONDS}",
+ f"npx --yes {WIZARD_PACKAGE}",
+ "--headless-DONOTUSE-EXPERIMENTAL",
+ "--install-dir .",
+ f"--region {shlex.quote(_wizard_region())}",
+ f"--project-id {shlex.quote(str(project_id))}",
+ ]
+
+ if settings.DEBUG:
+ # Local dev: pin the wizard to the same PostHog instance the sandbox itself reaches, instead
+ # of letting it infer a cloud region from the access token (which fails for a locally-minted
+ # token). POSTHOG_API_URL is injected into the sandbox env and already carries the provider's
+ # in-container rewrite (e.g. http://host.docker.internal:8000 for the Docker sandbox, since
+ # localhost/:8010 are unreachable from inside it), so expand it inside the container rather
+ # than baking a host-side URL into the command.
+ parts.append('--base-url "$POSTHOG_API_URL"')
+
+ return " ".join(parts)
+
+
+@asyncify
+def run_wizard(input: RunWizardInput) -> None:
+ """Run the PostHog setup wizard in the sandbox before the agent starts.
+
+ The wizard performs the real PostHog integration (modifies source, installs deps, writes
+ posthog-setup-report.md), leaving the changes uncommitted in the working tree. The downstream
+ agent then only has to commit them, open a PR, and keep it green. A non-zero exit fails the run
+ rather than handing a half-integrated tree to the agent.
+ """
+ ctx = input.context
+
+ with log_activity_execution(
+ "run_wizard",
+ sandbox_id=input.sandbox_id,
+ **ctx.to_log_context(),
+ ):
+ org, repo = input.repository.lower().split("/")
+ repo_path = f"/tmp/workspace/repos/{org}/{repo}"
+
+ emit_agent_log(ctx.run_id, "info", "Running the PostHog setup wizard")
+ sandbox = Sandbox.get_by_id(input.sandbox_id)
+ command = _build_wizard_command(repo_path, ctx.team_id)
+
+ result = sandbox.execute(command, timeout_seconds=_SANDBOX_EXEC_TIMEOUT_SECONDS)
+
+ # Persist the wizard's output outside the repo tree so the agent can consult what happened
+ # without any chance of committing it. Written before the exit-code check so a failed run
+ # still leaves a record on disk for post-mortems.
+ sandbox.execute(f"mkdir -p {shlex.quote(WIZARD_OUTPUT_DIR)}")
+ sandbox.write_file(WIZARD_OUTPUT_LOG_PATH, _format_wizard_output(result).encode("utf-8"))
+
+ if settings.DEBUG:
+ # Pull the wizard's verbose log out of the sandbox before the workflow tears it down, so a
+ # failed local run stays debuggable from the run's console log (it never reaches object
+ # storage otherwise). `|| true` keeps a missing file — wizard exited before writing one —
+ # from erroring the activity.
+ verbose = sandbox.execute(f"cat {shlex.quote(WIZARD_VERBOSE_LOG_PATH)} 2>/dev/null || true")
+ if verbose.stdout.strip():
+ emit_agent_log(
+ ctx.run_id, "debug", f"wizard verbose log ({WIZARD_VERBOSE_LOG_PATH}):\n{verbose.stdout}"
+ )
+
+ if result.stdout:
+ emit_agent_log(ctx.run_id, "debug", result.stdout)
+ if result.exit_code == WIZARD_TIMEOUT_EXIT_CODE:
+ minutes = WIZARD_RUN_TIMEOUT_SECONDS // 60
+ emit_agent_log(ctx.run_id, "error", f"PostHog setup wizard timed out after {minutes} minutes")
+ raise RuntimeError(f"PostHog setup wizard timed out after {minutes} minutes")
+ if result.exit_code != 0:
+ emit_agent_log(
+ ctx.run_id, "error", f"PostHog setup wizard failed (exit {result.exit_code}): {result.stderr}"
+ )
+ raise RuntimeError(f"PostHog setup wizard failed with exit code {result.exit_code}")
+
+ emit_agent_log(ctx.run_id, "info", "PostHog setup wizard completed")
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_run_wizard.py b/products/tasks/backend/temporal/process_task/activities/tests/test_run_wizard.py
new file mode 100644
index 000000000000..0a0959780fbd
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_run_wizard.py
@@ -0,0 +1,62 @@
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from products.tasks.backend.logic.services.sandbox import ExecutionResult
+from products.tasks.backend.temporal.process_task.activities.run_wizard import (
+ WIZARD_PACKAGE,
+ WIZARD_RUN_TIMEOUT_SECONDS,
+ _build_wizard_command,
+ _format_wizard_output,
+ _wizard_region,
+)
+
+
+class TestBuildWizardCommand(SimpleTestCase):
+ def test_uses_headless_flag_and_does_not_pass_the_token_on_the_command_line(self) -> None:
+ # --headless-DONOTUSE-EXPERIMENTAL is the published-build non-interactive mode (--ci is
+ # dev/test-only and rejected by published builds), and the token must come from
+ # POSTHOG_WIZARD_API_KEY in the env, never the command line. A regression to --ci or an
+ # inline --api-key would break cloud runs / leak the token.
+ command = _build_wizard_command("/tmp/workspace/repos/acme/app", 123)
+
+ assert "--headless-DONOTUSE-EXPERIMENTAL" in command
+ assert "--ci" not in command
+ assert "--api-key" not in command
+ # Wrapped in `timeout` so an over-budget run exits 124 and run_wizard reports a clean
+ # timeout instead of discarding partial output to a sandbox-level TimeoutError.
+ assert f"timeout -k 30 {WIZARD_RUN_TIMEOUT_SECONDS} npx" in command
+ assert "cd /tmp/workspace/repos/acme/app" in command
+ assert WIZARD_PACKAGE in command
+ assert "--install-dir ." in command
+ assert "--project-id 123" in command
+
+ @parameterized.expand([(True,), (False,)])
+ def test_base_url_pins_local_instance_only_in_debug(self, debug: bool) -> None:
+ # Local dev pins --base-url to the sandbox-reachable POSTHOG_API_URL so the wizard hits the
+ # local instance instead of failing cloud region detection on a locally-minted token. Prod
+ # must keep inferring the region from the token, so the flag must not leak when DEBUG is off.
+ with override_settings(DEBUG=debug):
+ command = _build_wizard_command("/tmp/workspace/repos/a/b", 1)
+
+ assert ('--base-url "$POSTHOG_API_URL"' in command) is debug
+
+ @parameterized.expand([("EU", "eu"), ("US", "us"), (None, "us")])
+ def test_region_maps_from_instance_region(self, instance_region: str | None, expected: str) -> None:
+ with patch(
+ "products.tasks.backend.temporal.process_task.activities.run_wizard.get_instance_region",
+ return_value=instance_region,
+ ):
+ assert _wizard_region() == expected
+ assert f"--region {expected}" in _build_wizard_command("/tmp/workspace/repos/a/b", 1)
+
+ def test_format_wizard_output_captures_exit_code_stdout_and_stderr(self) -> None:
+ # The agent reads this file to understand what the wizard did; dropping stderr (where wizard
+ # errors land) or the exit code would blind it on failed runs.
+ output = _format_wizard_output(ExecutionResult(stdout="installed sdk", stderr="a warning", exit_code=1))
+
+ assert "exit code 1" in output
+ assert "installed sdk" in output
+ assert "a warning" in output
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index a59ae35f363a..ec9b3fdcd830 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -45,6 +45,7 @@ from .activities.provision_sandbox import (
)
from .activities.read_sandbox_logs import ReadSandboxLogsInput, read_sandbox_logs
from .activities.relay_sandbox_events import RelaySandboxEventsInput, relay_sandbox_events
+from .activities.run_wizard import RunWizardInput, run_wizard
from .activities.send_followup_to_sandbox import SendFollowupToSandboxInput, send_followup_to_sandbox
from .activities.start_agent_server import (
MarkRepoReadyInput,
@@ -170,6 +171,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# exception handler onto the right card.
self._current_progress_step: Optional[tuple[str, str, str]] = None
self._pr_fingerprint: Optional[str] = None
+ # Emit the "PR opened / keeping CI green" progress once, the first time we observe a PR — the
+ # agent opens it mid-run and then keeps it green, so without this the UI dead-ends at "Started agent".
+ self._pr_progress_emitted: bool = False
@property
def context(self) -> TaskProcessingContext:
@@ -253,6 +257,30 @@ class ProcessTaskWorkflow(PostHogWorkflow):
await workflow.sleep(CI_FOLLOW_UP_DELAY.total_seconds())
return TaskEvent.CI_FOLLOW_UP
+ def _describe_wait(self, *, warm_idle: bool, ci_follow_up_scheduled: bool, inactivity_timeout: timedelta) -> str:
+ """Human-readable summary of what the loop is blocked on, for the Temporal UI.
+
+ The loop blocks on bare `workflow.sleep` timers (CI follow-up, inactivity), which render
+ as unlabeled Timer events — indistinguishable from a hang at a glance. This names the wait.
+ """
+ if warm_idle:
+ return "⏳ Warm sandbox idle — waiting for the first user message."
+
+ timeout_min = max(1, round(inactivity_timeout.total_seconds() / 60))
+ if not ci_follow_up_scheduled:
+ return f"⏳ Waiting for the agent to finish or send an update (inactivity timeout {timeout_min}m)."
+
+ next_check = CI_FOLLOW_UP_DELAY
+ if self._last_active_time:
+ remaining = CI_FOLLOW_UP_DELAY - (workflow.now() - self._last_active_time)
+ if remaining > timedelta(0):
+ next_check = remaining
+ next_min = max(1, round(next_check.total_seconds() / 60))
+ return (
+ f"⏳ Waiting for the agent, or to re-check the PR's CI in ~{next_min}m "
+ f"(CI follow-up {self._ci_repetitions + 1}/{MAX_CI_REPETITIONS}; inactivity timeout {timeout_min}m)."
+ )
+
async def _wait_for_event(self) -> TaskEvent:
warm_idle = self._prewarmed and not self._first_user_message_received
@@ -278,6 +306,15 @@ class ProcessTaskWorkflow(PostHogWorkflow):
inactivity_timeout = max(base_timeout, ci_follow_up_floor)
else:
inactivity_timeout = base_timeout
+
+ workflow.set_current_details(
+ self._describe_wait(
+ warm_idle=warm_idle,
+ ci_follow_up_scheduled=ci_follow_up_scheduled,
+ inactivity_timeout=inactivity_timeout,
+ )
+ )
+
possible_events: list[asyncio.Task[TaskEvent]] = [
asyncio.create_task(self._wait_for_task_external_event()),
asyncio.create_task(self._wait_for_inactivity(inactivity_timeout)),
@@ -347,6 +384,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):
extra={"run_id": self.context.run_id},
)
return CIFollowUpDecision.NO_PR
+ # First time we observe a PR: surface "Opened pull request" + "Keeping CI green" so the UI moves
+ # past "Started agent". The url rides the "pr" step's detail; the frontend turns it into the CTA.
+ if pr_context.pr_url and not self._pr_progress_emitted:
+ self._pr_progress_emitted = True
+ await self._emit_progress("pr", "completed", "Opened pull request", "setup", detail=pr_context.pr_url)
+ await self._emit_progress("ci", "in_progress", "Keeping CI green", "setup")
if pr_context.pr_state == "closed":
workflow.logger.info(
"PR is closed, skipping CI follow-up",
@@ -429,6 +472,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
if not workflow.patched(_PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING):
await self._post_slack_update()
+ # Run the PostHog setup wizard before the agent, when this is a cloud wizard run.
+ # The wizard integrates PostHog and dirties the working tree; the agent then commits
+ # those changes, opens the PR, and keeps it green (it never implements PostHog itself).
+ await self._run_wizard_if_configured(sandbox_output)
+
# Start agent-server for direct connection from PostHog Code
if sandbox_output.agent_server_launched:
agent_server_output = await self._await_agent_server_ready(sandbox_output)
@@ -481,6 +529,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
follow_up_result = await self._should_run_ci_follow_up()
match follow_up_result:
case CIFollowUpDecision.FIRE:
+ workflow.set_current_details("🔁 Re-checking the PR's CI and nudging the agent.")
await self._dispatch_ci_follow_up()
case CIFollowUpDecision.NO_PR:
# No PR will ever appear — stop the CI loop entirely.
@@ -552,6 +601,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
elif timed_out:
await self._update_task_run_status("completed", error_message="Run timed out due to inactivity")
+ # Close out the keep-it-green step so a finished run doesn't show a still-spinning CI step.
+ if self._pr_progress_emitted:
+ await self._emit_progress("ci", "completed", "Keeping CI green", "setup")
+
await self._post_slack_update()
return ProcessTaskOutput(
@@ -791,6 +844,32 @@ class ProcessTaskWorkflow(PostHogWorkflow):
except Exception as e:
workflow.logger.warning(f"Failed to read sandbox logs: {e}")
+ async def _run_wizard_if_configured(self, sandbox_output: GetSandboxForRepositoryOutput) -> None:
+ """Run the setup wizard in the sandbox before the agent, for cloud wizard runs only.
+
+ Fails the run on a non-zero wizard exit (maximum_attempts=1, and the wizard is non-idempotent
+ once it has modified files), rather than handing a half-integrated tree to the agent.
+ """
+ repository = self.context.repository
+ # `is not None` (not truthiness): an empty config dict still means "this is a wizard run".
+ if self.context.wizard_config is None or not repository:
+ return
+
+ await self._emit_progress("wizard", "in_progress", "Running PostHog setup wizard", "setup")
+ await workflow.execute_activity(
+ run_wizard,
+ RunWizardInput(
+ context=self.context,
+ sandbox_id=sandbox_output.sandbox_id,
+ repository=repository,
+ ),
+ # Above WIZARD_RUN_TIMEOUT_SECONDS (45 min) so the wizard's own timeout bounds the run;
+ # the headroom covers the sandbox lookup and writing the output log.
+ start_to_close_timeout=timedelta(minutes=50),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ await self._emit_progress("wizard", "completed", "Ran PostHog setup wizard", "setup")
+
async def _start_agent_server(self, sandbox_output: GetSandboxForRepositoryOutput) -> StartAgentServerOutput:
return await workflow.execute_activity(
start_agent_server,
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 55f0adc9485c..937808b2d0eb 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -300,6 +300,25 @@ class TestTaskCreatorScoping(BaseTaskAPITest):
self.assertIn(str(mine.id), ids)
self.assertIn(str(scout_task.id), ids)
+ def test_list_onboarding_tasks_owned_by_another_user(self):
+ # Onboarding tasks are the shared getting-started task: team-scoped, so they show
+ # in everyone's Tasks list regardless of which user the task was created under.
+ other_user = self.create_organization_user("onboarding-owner")
+ onboarding_task = Task.objects.create(
+ team=self.team,
+ created_by=other_user,
+ title="Onboarding Task",
+ description="Getting started",
+ origin_product=Task.OriginProduct.ONBOARDING,
+ )
+ mine = self.create_task("Mine", created_by=self.user)
+
+ response = self.client.get("/api/projects/@current/tasks/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ids = {t["id"] for t in response.json()["results"]}
+ self.assertIn(str(mine.id), ids)
+ self.assertIn(str(onboarding_task.id), ids)
+
def test_retrieve_signals_scout_task_owned_by_another_user_is_visible(self):
other_user = self.create_organization_user("scout-owner")
task = Task.objects.create(
@@ -3327,8 +3346,9 @@ class TestTaskRunAPI(BaseTaskAPITest):
)
# A caller cannot escalate to the creator's integration, flip authorship, repoint the
- # credential-propagation target at a sandbox they control, or inflate the run's compute /
- # lifetime to provision an oversized, long-lived sandbox. Non-protected keys still merge.
+ # credential-propagation target at a sandbox they control, inflate the run's compute /
+ # lifetime to provision an oversized, long-lived sandbox, or turn the run into a wizard run
+ # (which would mint a write-scoped wizard token into the sandbox). Non-protected keys merge.
response = self.client.patch(
f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
{
@@ -3340,6 +3360,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"sandbox_memory_gb": 512,
"sandbox_ttl_seconds": 86400,
"inactivity_timeout_seconds": 86400,
+ "wizard_config": {},
"scratch": "ok",
}
},
@@ -3354,6 +3375,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["sandbox_memory_gb"] == 8
assert run.state["sandbox_ttl_seconds"] == 1800
assert run.state["inactivity_timeout_seconds"] == 600
+ assert "wizard_config" not in run.state # caller cannot mark a run as a wizard run
assert run.state["scratch"] == "ok" # non-protected keys still merge
# Nor can a caller remove a protected key to force a fallback or unguarded path.
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 5cdb13dbe622..8abf2f8ff5de 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -18,6 +18,7 @@ from products.tasks.backend.facade import (
warm as warm_facade,
)
from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun
+from products.tasks.backend.prompts import WIZARD_PR_AGENT_PROMPT
FACADE_MODULES = [
"products.tasks.backend.facade.api",
@@ -307,3 +308,16 @@ class TestFacadeReadsAndMappers(TestCase):
self.assertTrue(Task.objects.filter(id=created.task_id).exists())
assert created.latest_run is not None
self.assertEqual(created.latest_run.task_id, created.task_id)
+
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_wizard_cloud_run_seeds_pending_user_message(self, _mock_workflow):
+ Integration.objects.create(team=self.team, kind="github", config={})
+ created = facade.create_wizard_cloud_run(
+ team=self.team,
+ user_id=self.user.id,
+ repository="acme-co/web",
+ )
+ run = TaskRun.objects.get(task_id=created.task_id)
+ # The agent server boots idle; forward_pending_user_message only kicks it off if the run state
+ # carries the prompt. Without this the cloud wizard stalls right after "Started agent".
+ self.assertEqual(run.state.get("pending_user_message"), WIZARD_PR_AGENT_PROMPT)
diff --git a/products/tasks/backend/visibility.py b/products/tasks/backend/visibility.py
index d3c80749e481..be70bebbf118 100644
--- a/products/tasks/backend/visibility.py
+++ b/products/tasks/backend/visibility.py
@@ -9,6 +9,19 @@ from django.db.models import Q
from products.tasks.backend.models import Task
+# Origin products whose tasks are team-scoped rather than personal: every team member
+# can view them regardless of who created them.
+# - SIGNAL_REPORT / SIGNALS_SCOUT: pipeline artifacts attached to a system-picked
+# `created_by` so the agent can mint an OAuth token, but they are not personal.
+# - ONBOARDING: the "Set up PostHog" wizard task. Its `created_by` is the real person who
+# went through onboarding (not a system pick), but we surface it team-wide so anyone on
+# the team can see and pick up the setup, not just whoever happened to start it.
+TEAM_VISIBLE_ORIGIN_PRODUCTS = [
+ Task.OriginProduct.SIGNAL_REPORT,
+ Task.OriginProduct.SIGNALS_SCOUT,
+ Task.OriginProduct.ONBOARDING,
+]
+
def task_visibility_q(user_id: int | None) -> Q:
"""Filter for tasks visible to the given user.
@@ -18,17 +31,10 @@ def task_visibility_q(user_id: int | None) -> Q:
- it has no creator at all (legacy unowned tasks remain visible to any
team member — they cannot be executed in any case because oauth.py
requires `task.created_by` to mint OAuth tokens), or
- - it was generated by the signals pipeline or Signals scout
- (`origin_product=SIGNAL_REPORT` or `origin_product=SIGNALS_SCOUT`).
- Signals tasks are team-scoped artifacts that the pipeline must attach to
- a system-picked `created_by` so the agent can mint an OAuth token, but
- they are not personal — any team member should be able to view them.
+ - its `origin_product` is one of `TEAM_VISIBLE_ORIGIN_PRODUCTS`, i.e. a
+ team-scoped artifact (signals, onboarding) that any team member should see.
"""
- return (
- Q(created_by_id=user_id)
- | Q(created_by__isnull=True)
- | Q(origin_product__in=[Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.SIGNALS_SCOUT])
- )
+ return Q(created_by_id=user_id) | Q(created_by__isnull=True) | Q(origin_product__in=TEAM_VISIBLE_ORIGIN_PRODUCTS)
def task_run_visibility_q(user_id: int | None) -> Q:
@@ -36,5 +42,5 @@ def task_run_visibility_q(user_id: int | None) -> Q:
return (
Q(task__created_by_id=user_id)
| Q(task__created_by__isnull=True)
- | Q(task__origin_product__in=[Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.SIGNALS_SCOUT])
+ | Q(task__origin_product__in=TEAM_VISIBLE_ORIGIN_PRODUCTS)
)
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 05299b49394b..65690bb41b38 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -356,6 +356,7 @@ export interface PaginatedTaskDetailDTOListApi {
}
/**
+ * * `onboarding` - Onboarding
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -371,6 +372,7 @@ export interface PaginatedTaskDetailDTOListApi {
export type OriginProductEnumApi = (typeof OriginProductEnumApi)[keyof typeof OriginProductEnumApi]
export const OriginProductEnumApi = {
+ Onboarding: 'onboarding',
ErrorTracking: 'error_tracking',
EvalClusters: 'eval_clusters',
UserCreated: 'user_created',
@@ -441,6 +443,7 @@ export interface TaskWriteApi {
description?: string
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).
*
+ * * `onboarding` - Onboarding
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -531,6 +534,7 @@ export interface PatchedTaskWriteApi {
description?: string
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).
*
+ * * `onboarding` - Onboarding
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 205b7efad09d..d1886cf875df 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -248,6 +248,7 @@ export const TasksCreateBody = /* @__PURE__ */ zod
.describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
origin_product: zod
.enum([
+ 'onboarding',
'error_tracking',
'eval_clusters',
'user_created',
@@ -261,11 +262,11 @@ export const TasksCreateBody = /* @__PURE__ */ zod
'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
@@ -355,6 +356,7 @@ export const TasksUpdateBody = /* @__PURE__ */ zod
.describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
origin_product: zod
.enum([
+ 'onboarding',
'error_tracking',
'eval_clusters',
'user_created',
@@ -368,11 +370,11 @@ export const TasksUpdateBody = /* @__PURE__ */ zod
'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
@@ -462,6 +464,7 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod
.describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
origin_product: zod
.enum([
+ 'onboarding',
'error_tracking',
'eval_clusters',
'user_created',
@@ -475,11 +478,11 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod
'support_reply',
])
.describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
),
repository: zod
.string()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b11b4dcc8300..f1e3a5bbe9b8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -30603,6 +30603,7 @@ export namespace Schemas {
}
/**
+ * * `onboarding` - Onboarding
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -30619,6 +30620,7 @@ export namespace Schemas {
export const OriginProductEnum = {
+ Onboarding: 'onboarding',
ErrorTracking: 'error_tracking',
EvalClusters: 'eval_clusters',
UserCreated: 'user_created',
@@ -41287,6 +41289,7 @@ export namespace Schemas {
description?: string;
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).
*
+ * * `onboarding` - Onboarding
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
@@ -51878,6 +51881,7 @@ export namespace Schemas {
description?: string;
/** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).
*
+ * * `onboarding` - Onboarding
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.ts
index d9392004d609..e18c444bebc7 100644
--- a/services/mcp/src/lib/instructions.ts
+++ b/services/mcp/src/lib/instructions.ts
@@ -21,14 +21,16 @@ export function buildActiveEnvironmentContextPrompt(
if (org || project) {
const projectName = project?.name ?? 'Unknown'
const projectId = project?.id ?? 'unknown'
+ const projectToken = project?.api_token ?? 'unknown'
+
if (org) {
const orgName = org.name ?? 'Unknown'
const orgId = org.id ?? 'unknown'
lines.push(
- `You are currently in project "${projectName}" (id: ${projectId}) within organization "${orgName}" (id: ${orgId}).`
+ `You are currently in project "${projectName}" (id: ${projectId}, token: ${projectToken}) within organization "${orgName}" (id: ${orgId}).`
)
} else {
- lines.push(`You are currently in project "${projectName}" (id: ${projectId}).`)
+ lines.push(`You are currently in project "${projectName}" (id: ${projectId}, token: ${projectToken}).`)
}
}
if (regionalBaseUrl) {
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index d81d6b5deca3..042eecaf8253 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -334,7 +334,7 @@ For complex investigations, combine multiple query types. For example, use `quer
Defined group types: organization, project
-You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).
+You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).
Project timezone: America/New_York.
The user's name is Jane Doe ([email protected]).
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt
index b9340d5c131f..6ed995a7a334 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt
@@ -1,5 +1,5 @@
Below are tools available in the MCP. Prioritize skills over tools.
-You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).
+You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).
Project timezone: America/New_York.
The user's name is Jane Doe ([email protected]).
Defined group types: organization, project
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
index 0632c8f362ea..9cada8e5a43a 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
@@ -198,7 +198,7 @@ For complex investigations, combine multiple query types. For example, use `quer
Defined group types: organization, project
-You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).
+You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).
Project timezone: America/New_York.
The user's name is Jane Doe ([email protected]).
diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
index 89b21deffbf8..05fe8213fe84 100644
--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
@@ -30,7 +30,7 @@ const STATIC_QUERY_TOOLS: QueryToolInfo[] = [
{ name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' },
]
const STATIC_METADATA = [
- 'You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).',
+ 'You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).',
'Project timezone: America/New_York.',
"The user's name is Jane Doe ([email protected]).",
].join('\n')
diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.ts
index 721d9df39a71..127f3b979cab 100644
--- a/services/mcp/tests/unit/instructions-formatter.test.ts
+++ b/services/mcp/tests/unit/instructions-formatter.test.ts
@@ -24,7 +24,7 @@ const realisticQueryTools: QueryToolInfo[] = [
{ name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion rate' },
]
const realisticMetadata =
- 'You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).\n' +
+ 'You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).\n' +
'Project timezone: America/New_York.\n' +
"The user's name is Jane Doe ([email protected])."
diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.ts
index b77d5e61cd80..370c9f0dd6a1 100644
--- a/services/mcp/tests/unit/instructions.test.ts
+++ b/services/mcp/tests/unit/instructions.test.ts
@@ -231,19 +231,24 @@ describe('QueryToolCatalog', () => {
})
describe('buildActiveEnvironmentContextPrompt', () => {
+ const org = { id: 'org_1', name: 'Acme' } satisfies Partial<CachedOrg> as unknown as CachedOrg
const project = {
id: 1,
name: 'My App',
timezone: 'America/New_York',
+ api_token: 'token_1',
person_on_events_querying_enabled: false,
- } as unknown as CachedProject
- const org = { id: 'org_1', name: 'Acme' } as unknown as CachedOrg
- const user = { first_name: 'Jane', last_name: 'Doe', email: '[email protected]' } as unknown as CachedUser
+ } satisfies Partial<CachedProject> as unknown as CachedProject
+ const user = {
+ first_name: 'Jane',
+ last_name: 'Doe',
+ email: '[email protected]',
+ } satisfies Partial<CachedUser> as unknown as CachedUser
it('renders the full project + org line when both are present', () => {
const result = buildActiveEnvironmentContextPrompt(user, org, project)
expect(result).toContain(
- 'You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).'
+ 'You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).'
)
})
@@ -252,7 +257,7 @@ describe('buildActiveEnvironmentContextPrompt', () => {
// fetch is skipped. The line drops the "within organization …" tail
// rather than rendering a fabricated "Unknown" placeholder.
const result = buildActiveEnvironmentContextPrompt(user, undefined, project)
- expect(result).toContain('You are currently in project "My App" (id: 1).')
+ expect(result).toContain('You are currently in project "My App" (id: 1, token: token_1).')
expect(result).not.toContain('within organization')
expect(result).not.toContain('Unknown')
expect(result).not.toContain('unknown')
@@ -270,7 +275,9 @@ describe('buildActiveEnvironmentContextPrompt', () => {
// Sits right after the project/org context line.
const lines = (result ?? '').split('\n')
expect(lines.indexOf('Base URL: us.posthog.com — add /project/1 for project-scoped paths.')).toBe(
- lines.indexOf('You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).') + 1
+ lines.indexOf(
+ 'You are currently in project "My App" (id: 1, token: token_1) within organization "Acme" (id: org_1).'
+ ) + 1
)
})
@@ -293,7 +300,7 @@ describe('buildActiveEnvironmentContextPrompt', () => {
// The org branch is unchanged — only the no-org branch was added.
const result = buildActiveEnvironmentContextPrompt(user, org, undefined)
expect(result).toContain(
- 'You are currently in project "Unknown" (id: unknown) within organization "Acme" (id: org_1).'
+ 'You are currently in project "Unknown" (id: unknown, token: unknown) within organization "Acme" (id: org_1).'
)
})
})