:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(wizard): persist CLI wizard runs via REST API (#59062)
Fernando Gomes3a46f26c0fac
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 69798d074e8a..ae6321d75bd2 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -229,6 +229,7 @@ rules:|UserInterviewTopic|UserRepoPreference|WebAnalyticsFilterPreset+ |WizardSession)$- focus-metavariable: $SINKpattern-sanitizers:@@ -451,6 +452,7 @@ rules:|UserInterviewTopic|UserRepoPreference|WebAnalyticsFilterPreset+ |WizardSession)$# Exclude when team filter is present- pattern-not: $M.objects. ... .$METHOD2(..., team__project_id=$T, ...)diff --git a/frontend/package.json b/frontend/package.jsonindex 42e545495ef8..69a1a014707c 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -116,6 +116,7 @@"@posthog/products-visual-review": "workspace:*","@posthog/products-warehouse-sources": "workspace:*","@posthog/products-web-analytics": "workspace:*",+ "@posthog/products-wizard": "workspace:*","@posthog/products-workflows": "workspace:*","@posthog/quill": "workspace:*","@posthog/react": "catalog:",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 434fa2f213aa..a3890f0fdd30 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -735,6 +735,9 @@ importers:'@posthog/products-web-analytics':specifier: workspace:*version: link:../products/web_analytics+ '@posthog/products-wizard':+ specifier: workspace:*+ version: link:../products/wizard'@posthog/products-workflows':specifier: workspace:*version: link:../products/workflows@@ -3502,6 +3505,8 @@ importers:specifier: 18.3.1version: 18.3.1+ products/wizard: {}+products/workflows:dependencies:'@posthog/icons':diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex f8274e6c9e08..813ac8911488 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -41,6 +41,7 @@ import products.revenue_analytics.backend.api as revenue_analyticsimport products.business_knowledge.backend.api as business_knowledgeimport products.marketing_analytics.backend.api as marketing_analyticsimport products.early_access_features.backend.api as early_access_feature+import products.wizard.backend.presentation.views as wizard_sessionsimport products.customer_analytics.backend.api.views as customer_analyticsimport products.data_warehouse.backend.api.fix_hogql as fix_hogqlimport products.mcp_store.backend.presentation.views as mcp_store@@ -335,6 +336,12 @@ project_features_router = projects_router.register("project_early_access_feature",["project_id"],)+projects_router.register(+ r"wizard/sessions",+ wizard_sessions.WizardSessionViewSet,+ "project_wizard_sessions",+ ["project_id"],+)# Deployments: DeploymentProject is the top-level entity; Deployment nests under it.# Mirrors `project_tasks_router` → `runs` pattern above for the parent/child URL shape:# /api/projects/{team_id}/deployment_projects/{deployment_project_id}/deployments/...diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 4b8ce0227357..dd0bc1876c1b 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -101,6 +101,7 @@ APIScopeObject = Literal["warehouse_view","web_analytics","webhook",+ "wizard_session",]APIScopeActions = Literal[@@ -125,7 +126,7 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"clickhouse_t# OAuth metadata. Used for alpha / not-yet-public products where a user can# manually paste the scope into a PAT but where we don't want OAuth-based# clients (the consent screen, MCP, third-party apps) to discover it.-OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"replay_scanner"})+OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"replay_scanner", "wizard_session"})PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [("endpoint", "read")]diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex e65c0f4f7a1b..a4484790e1c6 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -80,6 +80,7 @@ PRODUCTS_APPS = ["products.data_tools.backend.apps.DataToolsConfig","products.alerts.backend.apps.AlertsConfig","products.actions.backend.apps.ActionsConfig",+ "products.wizard.backend.apps.WizardConfig",]INSTALLED_APPS = [diff --git a/products/wizard/__init__.py b/products/wizard/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/wizard/backend/__init__.py b/products/wizard/backend/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/wizard/backend/apps.py b/products/wizard/backend/apps.pynew file mode 100644index 000000000000..a4a508b553d1--- /dev/null+++ b/products/wizard/backend/apps.py@@ -0,0 +1,8 @@+"""Django app configuration for wizard."""++from django.apps import AppConfig+++class WizardConfig(AppConfig):+ name = "products.wizard.backend"+ label = "wizard"diff --git a/products/wizard/backend/facade/__init__.py b/products/wizard/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/wizard/backend/facade/api.py b/products/wizard/backend/facade/api.pynew file mode 100644index 000000000000..43709acacd5f--- /dev/null+++ b/products/wizard/backend/facade/api.py@@ -0,0 +1,53 @@+"""+Facade for wizard.++The ONLY module other products are allowed to import.+Accept frozen dataclasses, call logic/, return frozen+dataclasses. Never return ORM instances or import DRF.+"""++from __future__ import annotations++from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardSessionDTO+from products.wizard.backend.logic import sessions+++def upsert(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO, bool]:+ """Upsert a session and report whether the row was newly created.++ Returns `(dto, created)` so consumers can distinguish 201 from 200 in+ their response semantics, and so retry-aware clients can short-circuit+ after the first successful write.+ """+ return sessions.upsert_session(params)+++def get(team_id: int, session_id: str) -> WizardSessionDTO | None:+ return sessions.get_session(team_id, session_id)+++def get_latest(team_id: int, workflow_id: str, skill_id: str) -> WizardSessionDTO | None:+ return sessions.get_latest_session(team_id, workflow_id, skill_id)+++def list_for_team(+ team_id: int,+ workflow_id: str | None = None,+ skill_id: str | None = None,+ *,+ offset: int = 0,+ limit: int | None = None,+) -> list[WizardSessionDTO]:+ """List sessions for a team, ordered by started_at desc.++ `offset`/`limit` are applied at the SQL layer; callers should pass a+ bounded `limit` for any user-facing list endpoint so the read cost stays+ bounded regardless of per-team row count.+ """+ return sessions.list_sessions(+ team_id,+ workflow_id=workflow_id,+ skill_id=skill_id,+ offset=offset,+ limit=limit,+ )diff --git a/products/wizard/backend/facade/contracts.py b/products/wizard/backend/facade/contracts.pynew file mode 100644index 000000000000..6257a157d565--- /dev/null+++ b/products/wizard/backend/facade/contracts.py@@ -0,0 +1,64 @@+"""+Contract types for wizard.++Frozen dataclasses that define what this product exposes.+No Django imports. Used by facade as inputs/outputs.+"""++from dataclasses import dataclass+from datetime import datetime, timedelta+from typing import Any++from .enums import RunPhase, TaskStatus++STALE_AFTER = timedelta(minutes=10)+++@dataclass(frozen=True)+class WizardTaskDTO:+ id: str+ title: str+ status: TaskStatus+++@dataclass(frozen=True)+class WizardSessionDTO:+ session_id: str+ team_id: int+ workflow_id: str+ skill_id: str+ started_at: datetime+ run_phase: RunPhase+ tasks: tuple[WizardTaskDTO, ...]+ event_plan: dict[str, Any] | None+ error: dict[str, Any] | None+ created_at: datetime+ updated_at: datetime+ is_stale: bool+++@dataclass(frozen=True)+class UpsertWizardSessionRequest:+ """What the wizard CLI POSTs. team_id is derived from the URL, not the body."""++ session_id: str+ workflow_id: str+ skill_id: str+ started_at: datetime+ run_phase: RunPhase+ tasks: tuple[WizardTaskDTO, ...]+ event_plan: dict[str, Any] | None = None+ error: dict[str, Any] | None = None+++@dataclass(frozen=True)+class UpsertWizardSessionInput:+ team_id: int+ session_id: str+ workflow_id: str+ skill_id: str+ started_at: datetime+ run_phase: RunPhase+ tasks: tuple[WizardTaskDTO, ...]+ event_plan: dict[str, Any] | None+ error: dict[str, Any] | Nonediff --git a/products/wizard/backend/facade/enums.py b/products/wizard/backend/facade/enums.pynew file mode 100644index 000000000000..1b709c165cc2--- /dev/null+++ b/products/wizard/backend/facade/enums.py@@ -0,0 +1,30 @@+"""+Exported enums for wizard.++If an enum appears in a contract dataclass field, it belongs here.+Internal-only constants (DB magic values, feature flags) stay in+the implementation (logic.py, models.py).+"""++from enum import StrEnum+++class RunPhase(StrEnum):+ """Phase of a run."""++ IDLE = "idle"+ RUNNING = "running"+ COMPLETED = "completed"+ ERROR = "error"+++class TaskStatus(StrEnum):+ """Status of a task."""++ PENDING = "pending"+ IN_PROGRESS = "in_progress"+ COMPLETED = "completed"++ # These are not currently used, but we want to reserve them for future use.+ FAILED = "failed"+ CANCELED = "canceled"diff --git a/products/wizard/backend/logic/__init__.py b/products/wizard/backend/logic/__init__.pynew file mode 100644index 000000000000..96009ccec37b--- /dev/null+++ b/products/wizard/backend/logic/__init__.py@@ -0,0 +1,12 @@+"""Business logic for wizard."""++from __future__ import annotations++from .sessions import get_latest_session, get_session, list_sessions, upsert_session++__all__ = [+ "get_session",+ "get_latest_session",+ "list_sessions",+ "upsert_session",+]diff --git a/products/wizard/backend/logic/sessions.py b/products/wizard/backend/logic/sessions.pynew file mode 100644index 000000000000..89851b91617d--- /dev/null+++ b/products/wizard/backend/logic/sessions.py@@ -0,0 +1,106 @@+"""+Business logic for Wizard sessions.+"""++from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardSessionDTO, WizardTaskDTO+from products.wizard.backend.facade.enums import RunPhase, TaskStatus+from products.wizard.backend.logic.utils import is_stale+from products.wizard.backend.models import WizardSession+++def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO, bool]:+ """Upsert a session row and return (dto, created).++ `defaults=` is applied on both insert AND update — each push is a full+ replacement of `tasks` / `run_phase` / `event_plan` / `error` (matches+ the RFC's "each push is the new source of truth"). Concurrent POSTs for+ a brand-new session_id can race the unique constraint and surface as a+ 500; the CLI's normal HTTP retry handles that on the next attempt.+ """+ instance, created = WizardSession.objects.update_or_create(+ team_id=params.team_id,+ session_id=params.session_id,+ defaults={+ "workflow_id": params.workflow_id,+ "skill_id": params.skill_id,+ "started_at": params.started_at,+ "run_phase": params.run_phase.value,+ "tasks": [+ {+ "id": task.id,+ "title": task.title,+ "status": task.status.value,+ }+ for task in params.tasks+ ],+ "event_plan": params.event_plan,+ "error": params.error,+ },+ )+ return _to_dto(instance), created+++def get_session(team_id: int, session_id: str) -> WizardSessionDTO | None:+ instance = WizardSession.objects.filter(team_id=team_id, session_id=session_id).first()+ return _to_dto(instance) if instance else None+++def get_latest_session(team_id: int, workflow_id: str, skill_id: str) -> WizardSessionDTO | None:+ instance = (+ WizardSession.objects.filter(team_id=team_id, workflow_id=workflow_id, skill_id=skill_id)+ .order_by("-started_at")+ .first()+ )+ return _to_dto(instance) if instance else None+++def list_sessions(+ team_id: int,+ workflow_id: str | None = None,+ skill_id: str | None = None,+ *,+ offset: int = 0,+ limit: int | None = None,+) -> list[WizardSessionDTO]:+ """List sessions for a team, ordered by `started_at` desc.++ `offset`/`limit` are applied at the SQL layer (LIMIT/OFFSET) so the read+ cost stays bounded regardless of how many sessions the team has. The view+ layer should always pass a `limit`.+ """+ qs = WizardSession.objects.filter(team_id=team_id)+ if workflow_id:+ qs = qs.filter(workflow_id=workflow_id)+ if skill_id:+ qs = qs.filter(skill_id=skill_id)+ qs = qs.order_by("-started_at")+ if limit is not None:+ qs = qs[offset : offset + limit]+ elif offset:+ qs = qs[offset:]+ return [_to_dto(instance) for instance in qs]+++def _to_dto(instance: WizardSession) -> WizardSessionDTO:+ run_phase = RunPhase(instance.run_phase)+ return WizardSessionDTO(+ session_id=instance.session_id,+ team_id=instance.team_id,+ workflow_id=instance.workflow_id,+ skill_id=instance.skill_id,+ started_at=instance.started_at,+ run_phase=run_phase,+ is_stale=is_stale(run_phase, instance.updated_at),+ tasks=tuple(+ WizardTaskDTO(+ id=task["id"],+ title=task["title"],+ status=TaskStatus(task["status"]),+ )+ for task in (instance.tasks or [])+ ),+ event_plan=instance.event_plan,+ error=instance.error,+ created_at=instance.created_at,+ updated_at=instance.updated_at,+ )diff --git a/products/wizard/backend/logic/utils.py b/products/wizard/backend/logic/utils.pynew file mode 100644index 000000000000..7872dcb6f271--- /dev/null+++ b/products/wizard/backend/logic/utils.py@@ -0,0 +1,14 @@+from datetime import datetime, timedelta++from django.utils import timezone++from products.wizard.backend.facade.contracts import STALE_AFTER+from products.wizard.backend.facade.enums import RunPhase+++def is_stale(run_phase: RunPhase, updated_at: datetime, stale_after: timedelta = STALE_AFTER) -> bool:+ """Determine if a session is stale based on its last update time."""+ if run_phase in {RunPhase.COMPLETED, RunPhase.ERROR}:+ return False++ return timezone.now() - updated_at > stale_afterdiff --git a/products/wizard/backend/management/__init__.py b/products/wizard/backend/management/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/wizard/backend/management/commands/__init__.py b/products/wizard/backend/management/commands/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/wizard/backend/management/commands/clear_wizard_sessions.py b/products/wizard/backend/management/commands/clear_wizard_sessions.pynew file mode 100644index 000000000000..b75e3935ba08--- /dev/null+++ b/products/wizard/backend/management/commands/clear_wizard_sessions.py@@ -0,0 +1,166 @@+"""Clear wizard session rows from the database.++Usage:+ python manage.py clear_wizard_sessions --team 123+ python manage.py clear_wizard_sessions --user [email protected]+ python manage.py clear_wizard_sessions --user 42 --workflow posthog-integration+ python manage.py clear_wizard_sessions --session-id onboarding-nextjs-2026-05-19T10:00:00Z --team 123+ python manage.py clear_wizard_sessions --user [email protected] --dry-run++`--user` resolves to every team in every organization the user is a member of.+The command refuses to run with no scoping flag.++`--all` clears every WizardSession row in the database and is intended for+dev/test environments only. In production, `--all` requires the operator to+also pass `--yes-i-really-mean-it-in-prod` so a fat-fingered command can't+wipe the table by accident.++`--session-id` requires a team scope (`--team` or `--user`) because session_id+is only unique per team — without one, the same id can match rows in multiple+tenants.+"""++import sys+from argparse import ArgumentParser+from typing import Any++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError+from django.db.models import QuerySet++from posthog.cloud_utils import is_cloud+from posthog.models.team import Team+from posthog.models.user import User++from products.wizard.backend.models import WizardSession+++class Command(BaseCommand):+ help = "Clear wizard session rows for a team, user, or specific session_id."++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument(+ "--user",+ type=str,+ help="User email or numeric ID. Resolves to every team in every org the user belongs to.",+ )+ parser.add_argument("--team", type=int, help="Team (project) ID.")+ parser.add_argument("--workflow", type=str, help="Filter by workflow_id (e.g. posthog-integration).")+ parser.add_argument("--skill", type=str, help="Filter by skill_id.")+ parser.add_argument("--session-id", type=str, help="Delete a single session by session_id.")+ parser.add_argument(+ "--all",+ action="store_true",+ help="Required to wipe every wizard session row. Refused in prod unless --yes-i-really-mean-it-in-prod is also passed.",+ )+ parser.add_argument(+ "--yes-i-really-mean-it-in-prod",+ action="store_true",+ help="Required alongside --all when running against PostHog Cloud / DEBUG=False.",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Print what would be deleted without touching the database.",+ )++ def handle(self, *args: Any, **opts: Any) -> None:+ user_arg: str | None = opts.get("user")+ team_id: int | None = opts.get("team")+ workflow_id: str | None = opts.get("workflow")+ skill_id: str | None = opts.get("skill")+ session_id: str | None = opts.get("session_id")+ clear_all: bool = opts.get("all", False)+ prod_confirm: bool = opts.get("yes_i_really_mean_it_in_prod", False)+ dry_run: bool = opts.get("dry_run", False)++ if not any([user_arg, team_id, session_id, clear_all]):+ raise CommandError(+ "Provide at least one of --user, --team, --session-id, or --all. "+ "Refusing to clear the entire wizard_sessions table by accident."+ )++ # session_id is only unique per team — without a team scope the same id+ # can match rows in multiple tenants. Require an explicit tenant scope+ # so an operator can't quietly cross tenant boundaries by typing the+ # wrong flag.+ if session_id and not (team_id or user_arg or clear_all):+ raise CommandError(+ "--session-id requires --team (or --user, or --all if you really "+ "intend to delete that session id across every tenant). session_id "+ "is unique per team, not globally."+ )++ # Prod guard for --all: PostHog Cloud and any non-DEBUG instance refuse+ # to wipe the table without an explicit acknowledgement.+ if clear_all and not dry_run:+ if is_cloud() or not settings.DEBUG:+ if not prod_confirm:+ raise CommandError(+ "--all on a non-DEBUG / cloud instance requires "+ "--yes-i-really-mean-it-in-prod. Re-run with that flag if "+ "you really intend to delete every wizard session row."+ )+ # Interactive confirmation when stdin is a TTY (scripted runs already+ # opted-in via the prod confirm flag).+ if sys.stdin.isatty():+ answer = input("Type 'delete all wizard sessions' to proceed: ")+ if answer.strip() != "delete all wizard sessions":+ raise CommandError("Confirmation phrase didn't match — aborting.")++ qs: QuerySet[WizardSession] = WizardSession.objects.unscoped().all()++ team_ids: list[int] = []+ if team_id is not None:+ team_ids.append(team_id)+ if user_arg is not None:+ user = self._resolve_user(user_arg)+ user_team_ids = list(Team.objects.filter(organization__members=user).values_list("id", flat=True))+ if not user_team_ids:+ self.stdout.write(self.style.WARNING(f"User {user_arg!r} belongs to no teams; nothing to clear."))+ return+ team_ids.extend(user_team_ids)++ if team_ids:+ qs = qs.filter(team_id__in=team_ids)++ if workflow_id:+ qs = qs.filter(workflow_id=workflow_id)+ if skill_id:+ qs = qs.filter(skill_id=skill_id)+ if session_id:+ qs = qs.filter(session_id=session_id)++ # Materialize counts + identifiers up front so dry-run and the actual+ # delete print the same numbers.+ matches = list(qs.values("session_id", "team_id", "workflow_id", "skill_id", "run_phase"))+ count = len(matches)++ if count == 0:+ self.stdout.write("No matching wizard sessions found.")+ return++ if dry_run:+ self.stdout.write(self.style.NOTICE(f"[dry-run] Would delete {count} wizard session(s):"))+ for row in matches:+ self.stdout.write(+ f" - team={row['team_id']} workflow={row['workflow_id']} skill={row['skill_id']} "+ f"phase={row['run_phase']} session_id={row['session_id']}"+ )+ return++ deleted, _ = qs.delete()+ self.stdout.write(self.style.SUCCESS(f"Deleted {deleted} wizard session row(s)."))++ @staticmethod+ def _resolve_user(value: str) -> User:+ # Numeric → primary key lookup; otherwise treat as email.+ if value.isdigit():+ try:+ return User.objects.get(pk=int(value))+ except User.DoesNotExist as e:+ raise CommandError(f"No user with id={value}") from e+ try:+ return User.objects.get(email=value)+ except User.DoesNotExist as e:+ raise CommandError(f"No user with email={value!r}") from ediff --git a/products/wizard/backend/migrations/0001_initial_wizard_session.py b/products/wizard/backend/migrations/0001_initial_wizard_session.pynew file mode 100644index 000000000000..fe8b8fac9de0--- /dev/null+++ b/products/wizard/backend/migrations/0001_initial_wizard_session.py@@ -0,0 +1,75 @@+# Generated by Django 5.2.13 on 2026-05-19 19:21++import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("posthog", "1177_alter_organization_is_ai_data_processing_approved"),+ ]++ operations = [+ migrations.CreateModel(+ name="WizardSession",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("session_id", models.CharField(max_length=255)),+ ("workflow_id", models.CharField(max_length=255)),+ ("skill_id", models.CharField(max_length=255)),+ ("started_at", models.DateTimeField()),+ (+ "run_phase",+ models.CharField(+ choices=[+ ("idle", "idle"),+ ("running", "running"),+ ("completed", "completed"),+ ("error", "error"),+ ],+ max_length=50,+ ),+ ),+ ("tasks", models.JSONField(default=list)),+ ("event_plan", models.JSONField(blank=True, null=True)),+ ("error", models.JSONField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "abstract": False,+ "indexes": [+ models.Index(+ fields=["team", "workflow_id", "skill_id", "-started_at"],+ name="wizard_wiza_team_id_ddd1dc_idx",+ )+ ],+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "session_id"),+ name="unique_wizard_session_per_team",+ )+ ],+ },+ ),+ ]diff --git a/products/wizard/backend/migrations/__init__.py b/products/wizard/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/wizard/backend/migrations/max_migration.txt b/products/wizard/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..e20801834314--- /dev/null+++ b/products/wizard/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initial_wizard_sessiondiff --git a/products/wizard/backend/models.py b/products/wizard/backend/models.pynew file mode 100644index 000000000000..4415c5ea695e--- /dev/null+++ b/products/wizard/backend/models.py@@ -0,0 +1,43 @@+"""+Django models for wizard.++Keep models thin — business logic belongs in logic/.+Use types from facade/enums.py where applicable.+Avoid ForeignKeys to models outside this app; if needed,+disallow reverse relations with related_name='+'.+"""++from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel++from products.wizard.backend.facade.enums import RunPhase+++class WizardSession(UUIDModel, TeamScopedRootMixin):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")++ session_id = models.CharField(max_length=255)+ workflow_id = models.CharField(max_length=255)+ skill_id = models.CharField(max_length=255)+ started_at = models.DateTimeField()++ run_phase = models.CharField(max_length=50, choices=[(phase.value, phase.value) for phase in RunPhase])++ tasks = models.JSONField(default=list)+ event_plan = models.JSONField(null=True, blank=True)+ error = models.JSONField(null=True, blank=True)++ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta(TeamScopedRootMixin.Meta):+ constraints = [models.UniqueConstraint(fields=["team", "session_id"], name="unique_wizard_session_per_team")]++ indexes = [+ # to optimize fetching the latest session+ models.Index(+ fields=["team", "workflow_id", "skill_id", "-started_at"],+ )+ ]diff --git a/products/wizard/backend/presentation/__init__.py b/products/wizard/backend/presentation/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/wizard/backend/presentation/serializers.py b/products/wizard/backend/presentation/serializers.pynew file mode 100644index 000000000000..f650a3c2a379--- /dev/null+++ b/products/wizard/backend/presentation/serializers.py@@ -0,0 +1,49 @@+"""DRF serializers for wizard. Bound to facade DTOs, not Django models."""++from rest_framework_dataclasses.serializers import DataclassSerializer++from products.wizard.backend.facade.contracts import UpsertWizardSessionRequest, WizardSessionDTO+++class WizardSessionSerializer(DataclassSerializer):+ """Output: serialises a WizardSessionDTO returned by the facade."""++ class Meta:+ dataclass = WizardSessionDTO+++class UpsertWizardSessionRequestSerializer(DataclassSerializer):+ """Input: validates the JSON the wizard CLI posts. team_id is derived from URL."""++ class Meta:+ dataclass = UpsertWizardSessionRequest+ extra_kwargs = {+ "session_id": {+ "max_length": 255,+ "help_text": (+ "Stable identifier the wizard mints for this run "+ "(format: '{workflow_id}-{skill_id}-{started_at_iso}'). "+ "Reposting with the same session_id upserts the existing row."+ ),+ },+ "workflow_id": {+ "max_length": 255,+ "help_text": "High-level workflow being run, e.g. 'onboarding', 'migration', 'audit'.",+ },+ "skill_id": {+ "max_length": 255,+ "help_text": "Specific skill within the workflow, e.g. 'nextjs', 'django', 'laravel'.",+ },+ "started_at": {+ "help_text": "UTC timestamp when the wizard started this run. Matches the timestamp encoded in session_id.",+ },+ "run_phase": {+ "help_text": "Lifecycle stage of the wizard run.",+ },+ "event_plan": {+ "help_text": "Optional structured plan of events the wizard intends to instrument. Schema is workflow-specific.",+ },+ "error": {+ "help_text": "Populated when run_phase='error'. Shape: { type: string, message: string }.",+ },+ }diff --git a/products/wizard/backend/presentation/utils.py b/products/wizard/backend/presentation/utils.pynew file mode 100644index 000000000000..bde9a22d8b52--- /dev/null+++ b/products/wizard/backend/presentation/utils.py@@ -0,0 +1,25 @@+"""Presentation-layer helpers for wizard endpoints."""++from rest_framework.request import Request++# Hard cap so a misbehaving CLI / runaway team can't tank the worker by+# requesting a giant page. DRF's pagination is layered on top of this.+DEFAULT_LIST_LIMIT = 50+MAX_LIST_LIMIT = 200+++def pagination_window(request: Request) -> tuple[int, int]:+ """Read offset / limit from the request, clamped to safe defaults."""++ def _int(name: str, default: int) -> int:+ raw = request.query_params.get(name)+ if raw is None:+ return default+ try:+ return max(0, int(raw))+ except (TypeError, ValueError):+ return default++ offset = _int("offset", 0)+ limit = min(_int("limit", DEFAULT_LIST_LIMIT), MAX_LIST_LIMIT)+ return offset, limitdiff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.pynew file mode 100644index 000000000000..876825805573--- /dev/null+++ b/products/wizard/backend/presentation/views.py@@ -0,0 +1,182 @@+"""+DRF views for wizard.++Validates JSON via serializers, routes everything through the facade,+returns DTO-shaped responses. No model imports.+"""++from typing import Any++import structlog+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema+from rest_framework import status, viewsets+from rest_framework.exceptions import NotFound, ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin++from products.wizard.backend.facade import api as wizard_facade+from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, UpsertWizardSessionRequest+from products.wizard.backend.presentation.serializers import (+ UpsertWizardSessionRequestSerializer,+ WizardSessionSerializer,+)+from products.wizard.backend.presentation.utils import pagination_window++logger = structlog.get_logger(__name__)+++def _log_request_auth(request: Request, *, action: str, team_id: int | None) -> None:+ """Debug-only dump of how the incoming wizard_sessions request authenticated.++ Fires only at DEBUG level — kept around for diagnosing 401/403 chains during+ rollout. Once the wizard CLI auth flow is stable, this can be removed+ entirely.+ """+ if not logger.isEnabledFor(10): # logging.DEBUG+ return++ authenticator = getattr(request, "successful_authenticator", None)+ auth_type = type(authenticator).__name__ if authenticator else "Anonymous"+ user = getattr(request, "user", None)+ user_id = getattr(user, "id", None) if user and not user.is_anonymous else None++ scopes: list[str] = []+ scoped_teams: list[int] = []+ scoped_organizations: list[str] = []++ pak = getattr(authenticator, "personal_api_key", None)+ if pak is not None:+ scopes = list(pak.scopes or [])+ scoped_teams = list(pak.scoped_teams or [])+ scoped_organizations = list(pak.scoped_organizations or [])++ token = getattr(authenticator, "access_token", None)+ if token is not None:+ scope_str: str = getattr(token, "scope", "") or ""+ scopes = list(scope_str.split())+ scoped_teams = list(getattr(token, "scoped_teams", None) or [])+ scoped_organizations = list(getattr(token, "scoped_organizations", None) or [])++ logger.debug(+ "wizard_sessions request",+ action=action,+ method=request.method,+ path=request.path,+ team_id_from_url=team_id,+ auth_type=auth_type,+ user_id=user_id,+ scopes=scopes,+ scoped_teams=scoped_teams,+ scoped_organizations=scoped_organizations,+ )+++class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ scope_object = "wizard_session"+ scope_object_read_actions = ["list", "retrieve"]+ scope_object_write_actions = ["create"]+ http_method_names = ["get", "post", "head", "options"]+ lookup_field = "session_id"+ lookup_value_regex = r"[^/]+"++ def check_permissions(self, request: Request) -> None:+ """Log the auth state before DRF decides allow/deny. Fires for both 200 and 403."""+ # team_id is a cached_property that can raise on malformed URLs — don't+ # let the diagnostic logger mask a clean 4xx with a 500.+ try:+ team_id = self.team_id+ except (KeyError, ValidationError, NotFound, AttributeError):+ team_id = None+ _log_request_auth(request, action=getattr(self, "action", "<unknown>"), team_id=team_id)+ super().check_permissions(request)++ @extend_schema(+ description=(+ "List wizard sessions for the project, ordered by started_at desc. "+ "This should only be called by the PostHog Wizard. "+ "Optional filters: ?workflow_id=<id> and ?skill_id=<id>."+ ),+ parameters=[+ OpenApiParameter(+ name="workflow_id",+ required=False,+ type=str,+ location=OpenApiParameter.QUERY,+ description="Filter to a single workflow (e.g. 'onboarding').",+ ),+ OpenApiParameter(+ name="skill_id",+ required=False,+ type=str,+ location=OpenApiParameter.QUERY,+ description="Filter to a single skill within the workflow (e.g. 'nextjs').",+ ),+ ],+ responses={200: WizardSessionSerializer(many=True)},+ )+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ page_offset, page_limit = pagination_window(request)+ sessions = wizard_facade.list_for_team(+ self.team_id,+ workflow_id=request.query_params.get("workflow_id"),+ skill_id=request.query_params.get("skill_id"),+ offset=page_offset,+ limit=page_limit,+ )+ # `sessions` is already a bounded slice; DRF's paginator can still wrap+ # it so the response shape (count/next/previous) stays consistent.+ page = self.paginate_queryset(sessions)+ if page is not None:+ return self.get_paginated_response(WizardSessionSerializer(page, many=True).data)+ return Response(WizardSessionSerializer(sessions, many=True).data)++ @extend_schema(+ description="Retrieve a single wizard session by its session_id.",+ responses={+ 200: WizardSessionSerializer,+ 404: OpenApiResponse(description="No session with that id for this project."),+ },+ )+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ session_id = kwargs.get("session_id")+ if not session_id:+ return Response({"detail": "session_id is required."}, status=status.HTTP_400_BAD_REQUEST)+ dto = wizard_facade.get(self.team_id, session_id)+ if dto is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(WizardSessionSerializer(dto).data)++ @extend_schema(+ description=(+ "Upsert a wizard session. The `session_id` key is the idempotency anchor — "+ "reposting the same `session_id` replaces the existing row. Returns 201 on "+ "create, 200 on update."+ ),+ request=UpsertWizardSessionRequestSerializer,+ responses={+ 200: WizardSessionSerializer,+ 201: WizardSessionSerializer,+ },+ )+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ serializer = UpsertWizardSessionRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ req: UpsertWizardSessionRequest = serializer.save()++ dto, created = wizard_facade.upsert(+ UpsertWizardSessionInput(+ team_id=self.team_id,+ session_id=req.session_id,+ workflow_id=req.workflow_id,+ skill_id=req.skill_id,+ started_at=req.started_at,+ run_phase=req.run_phase,+ tasks=tuple(req.tasks),+ event_plan=req.event_plan,+ error=req.error,+ )+ )+ response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK+ return Response(WizardSessionSerializer(dto).data, status=response_status)diff --git a/products/wizard/backend/tests/__init__.py b/products/wizard/backend/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/wizard/backend/tests/conftest.py b/products/wizard/backend/tests/conftest.pynew file mode 100644index 000000000000..ae3f00200968--- /dev/null+++ b/products/wizard/backend/tests/conftest.py@@ -0,0 +1,13 @@+import pytest++from posthog.models.scoping import team_scope++[email protected](autouse=True)+def _set_team_scope(request):+ if request.node.get_closest_marker("django_db") is None:+ yield+ return+ team = request.getfixturevalue("team")+ with team_scope(team.id):+ yielddiff --git a/products/wizard/backend/tests/test_logic.py b/products/wizard/backend/tests/test_logic.pynew file mode 100644index 000000000000..3ef52dafbb05--- /dev/null+++ b/products/wizard/backend/tests/test_logic.py@@ -0,0 +1,136 @@+from datetime import UTC, datetime++import pytest++from products.wizard.backend.facade import api as wizard_facade+from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardTaskDTO+from products.wizard.backend.facade.enums import RunPhase, TaskStatus+++def _input(team_id: int, **overrides) -> UpsertWizardSessionInput:+ params: dict = {+ "team_id": team_id,+ "session_id": "onboarding-nextjs-2026-05-19T10:00:00Z",+ "workflow_id": "onboarding",+ "skill_id": "nextjs",+ "started_at": datetime(2026, 5, 19, 10, 0, 0, tzinfo=UTC),+ "run_phase": RunPhase.RUNNING,+ "tasks": (WizardTaskDTO(id="1", title="Install SDK", status=TaskStatus.IN_PROGRESS),),+ "event_plan": None,+ "error": None,+ }+ params.update(overrides)+ return UpsertWizardSessionInput(**params)+++def test_upsert_creates_new_session(team):+ dto, created = wizard_facade.upsert(_input(team.id))++ assert created is True+ assert dto.session_id == "onboarding-nextjs-2026-05-19T10:00:00Z"+ assert dto.team_id == team.id+ assert dto.run_phase == RunPhase.RUNNING+ assert len(dto.tasks) == 1+ assert dto.tasks[0].status == TaskStatus.IN_PROGRESS+++def test_upsert_with_same_session_id_replaces_state(team):+ _, first_created = wizard_facade.upsert(_input(team.id))+ assert first_created is True++ updated, second_created = wizard_facade.upsert(+ _input(+ team.id,+ run_phase=RunPhase.COMPLETED,+ tasks=(WizardTaskDTO(id="1", title="Install SDK", status=TaskStatus.COMPLETED),),+ )+ )++ assert second_created is False+ assert updated.run_phase == RunPhase.COMPLETED+ assert updated.tasks[0].status == TaskStatus.COMPLETED+ assert len(wizard_facade.list_for_team(team.id, limit=100)) == 1+++def test_upsert_with_different_session_id_creates_new_row(team):+ wizard_facade.upsert(_input(team.id, session_id="run-1"))+ wizard_facade.upsert(_input(team.id, session_id="run-2"))++ assert len(wizard_facade.list_for_team(team.id, limit=100)) == 2+++def test_get_session_returns_matching_row(team):+ wizard_facade.upsert(_input(team.id, session_id="run-1"))++ found = wizard_facade.get(team.id, "run-1")+ assert found is not None+ assert found.session_id == "run-1"+++def test_get_session_returns_none_when_missing(team):+ assert wizard_facade.get(team.id, "missing") is None+++def test_get_latest_returns_most_recent_for_workflow_skill_pair(team):+ wizard_facade.upsert(+ _input(+ team.id,+ session_id="onboarding-nextjs-09:00",+ started_at=datetime(2026, 5, 19, 9, 0, 0, tzinfo=UTC),+ )+ )+ wizard_facade.upsert(+ _input(+ team.id,+ session_id="onboarding-nextjs-11:00",+ started_at=datetime(2026, 5, 19, 11, 0, 0, tzinfo=UTC),+ )+ )++ latest = wizard_facade.get_latest(team.id, "onboarding", "nextjs")+ assert latest is not None+ assert latest.session_id == "onboarding-nextjs-11:00"+++def test_get_latest_ignores_other_workflow_skill_pairs(team):+ wizard_facade.upsert(_input(team.id, session_id="onboarding-nextjs-1", workflow_id="onboarding", skill_id="nextjs"))+ wizard_facade.upsert(+ _input(team.id, session_id="migration-amplitude-1", workflow_id="migration", skill_id="amplitude")+ )++ latest = wizard_facade.get_latest(team.id, "onboarding", "nextjs")+ assert latest is not None+ assert latest.session_id == "onboarding-nextjs-1"+++def test_get_latest_returns_none_when_no_match(team):+ assert wizard_facade.get_latest(team.id, "missing", "missing") is None+++def test_list_for_team_returns_sessions_ordered_by_started_at_desc(team):+ wizard_facade.upsert(+ _input(+ team.id,+ session_id="run-early",+ started_at=datetime(2026, 5, 19, 9, 0, 0, tzinfo=UTC),+ )+ )+ wizard_facade.upsert(+ _input(+ team.id,+ session_id="run-late",+ started_at=datetime(2026, 5, 19, 19, 0, 0, tzinfo=UTC),+ )+ )++ sessions = wizard_facade.list_for_team(team.id, limit=100)+ assert [s.session_id for s in sessions] == ["run-late", "run-early"]diff --git a/products/wizard/backend/tests/test_presentation.py b/products/wizard/backend/tests/test_presentation.pynew file mode 100644index 000000000000..a94d87a6268f--- /dev/null+++ b/products/wizard/backend/tests/test_presentation.py@@ -0,0 +1,194 @@+from posthog.test.base import APIBaseTest++from parameterized import parameterized+from rest_framework import status++from posthog.models import Organization++from products.wizard.backend.models import WizardSession+++class TestWizardSessionViewSet(APIBaseTest):+ def _url(self, suffix: str = "") -> str:+ return f"/api/projects/{self.team.id}/wizard/sessions/{suffix}"++ def _payload(self, **overrides) -> dict:+ payload = {+ "session_id": "onboarding-nextjs-2026-05-19T10:00:00Z",+ "workflow_id": "onboarding",+ "skill_id": "nextjs",+ "started_at": "2026-05-19T10:00:00Z",+ "run_phase": "running",+ "tasks": [+ {+ "id": "1",+ "title": "Install Next.js plugin",+ "status": "in_progress",+ },+ {+ "id": "2",+ "title": "Configure plugin with API key",+ "status": "pending",+ },+ ],+ }+ payload.update(overrides)+ return payload++ def test_create_session(self):+ response = self.client.post(self._url(), self._payload(), format="json")++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ data = response.json()+ self.assertEqual(data["session_id"], "onboarding-nextjs-2026-05-19T10:00:00Z")+ self.assertEqual(data["workflow_id"], "onboarding")+ self.assertEqual(data["skill_id"], "nextjs")+ self.assertEqual(data["run_phase"], "running")+ self.assertEqual(len(data["tasks"]), 2)+ self.assertEqual(data["team_id"], self.team.id)++ self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 1)++ def test_repost_same_session_id_upserts(self):+ first = self.client.post(self._url(), self._payload(), format="json")+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)++ response = self.client.post(+ self._url(),+ self._payload(run_phase="completed", tasks=[{"id": "1", "title": "Install SDK", "status": "completed"}]),+ format="json",+ )++ # Second POST against the same session_id is an update, not a create.+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ data = response.json()+ self.assertEqual(data["run_phase"], "completed")+ self.assertEqual(len(data["tasks"]), 1)+ self.assertEqual(data["tasks"][0]["status"], "completed")++ self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 1)++ def test_different_session_id_creates_new_row(self):+ self.client.post(self._url(), self._payload(), format="json")++ self.client.post(+ self._url(),+ self._payload(session_id="onboarding-nextjs-2026-05-19T10:20:39Z"),+ format="json",+ )++ self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 2)++ def test_list_returns_sessions_ordered_by_started_at_desc(self):+ self.client.post(+ self._url(),+ self._payload(+ session_id="onboarding-nextjs-2026-05-19T09:00:00Z",+ started_at="2026-05-19T09:00:00Z",+ ),+ format="json",+ )+ self.client.post(+ self._url(),+ self._payload(+ session_id="onboarding-nextjs-2026-05-19T19:00:00Z",+ started_at="2026-05-19T19:00:00Z",+ ),+ format="json",+ )++ response = self.client.get(self._url())+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = response.json()["results"]+ self.assertEqual(len(results), 2)+ self.assertEqual(results[0]["started_at"], "2026-05-19T19:00:00Z")+ self.assertEqual(results[1]["started_at"], "2026-05-19T09:00:00Z")++ def test_list_filters_by_workflow_and_skill(self):+ self.client.post(+ self._url(),+ self._payload(+ session_id="onboarding-nextjs-1",+ workflow_id="onboarding",+ skill_id="nextjs",+ ),+ format="json",+ )+ self.client.post(+ self._url(),+ self._payload(+ session_id="migration-amplitude-1",+ workflow_id="migration",+ skill_id="amplitude",+ ),+ format="json",+ )++ response = self.client.get(self._url() + "?workflow_id=onboarding")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = response.json()["results"]+ self.assertEqual(len(results), 1)+ self.assertEqual(results[0]["workflow_id"], "onboarding")++ response = self.client.get(self._url() + "?workflow_id=onboarding&skill_id=django")+ self.assertEqual(len(response.json()["results"]), 0)++ def test_retrieve_by_session_id(self):+ self.client.post(self._url(), self._payload(), format="json")++ response = self.client.get(self._url("onboarding-nextjs-2026-05-19T10:00:00Z/"))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["workflow_id"], "onboarding")++ def test_retrieve_unknown_session_returns_404(self):+ response = self.client.get(self._url("does-not-exist/"))+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ @parameterized.expand([("delete",), ("put",)])+ def test_disallowed_verb_returns_405(self, method):+ self.client.post(self._url(), self._payload(), format="json")++ response = getattr(self.client, method)(self._url("onboarding-nextjs-2026-05-19T10:00:00Z/"))++ self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)++ @parameterized.expand(+ [+ ("invalid_task_status", {"tasks": [{"id": "1", "title": "x", "status": "pizza"}]}),+ ("invalid_run_phase", {"run_phase": "exploded"}),+ ]+ )+ def test_invalid_enum_payload_rejected(self, _label, payload_overrides):+ response = self.client.post(self._url(), self._payload(**payload_overrides), format="json")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_other_team_cannot_see_sessions(self):+ # Create a session in self.team's project.+ self.client.post(self._url(), self._payload(), format="json")++ # Spin up a separate org + team. The current user is not a member,+ # so the project endpoint should refuse the request entirely.+ other_org = Organization.objects.create(name="Other Org")+ other_team = self.create_team_with_organization(other_org)++ response = self.client.get(f"/api/projects/{other_team.id}/wizard/sessions/")+ self.assertIn(response.status_code, (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND))++ def test_event_plan_and_error_persisted(self):+ response = self.client.post(+ self._url(),+ self._payload(+ run_phase="error",+ event_plan={"events": [{"name": "$pageview"}]},+ error={"type": "TimeoutError", "message": "Anthropic API timed out"},+ ),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ data = response.json()+ self.assertEqual(data["event_plan"], {"events": [{"name": "$pageview"}]})+ self.assertEqual(data["error"], {"type": "TimeoutError", "message": "Anthropic API timed out"})diff --git a/products/wizard/backend/tests/test_utils.py b/products/wizard/backend/tests/test_utils.pynew file mode 100644index 000000000000..b270ab7672d5--- /dev/null+++ b/products/wizard/backend/tests/test_utils.py@@ -0,0 +1,29 @@+from datetime import UTC, datetime, timedelta++from unittest.mock import patch++from parameterized import parameterized++from products.wizard.backend.facade.contracts import STALE_AFTER+from products.wizard.backend.facade.enums import RunPhase+from products.wizard.backend.logic.utils import is_stale++_NOW = datetime(2026, 5, 19, 12, 0, 0, tzinfo=UTC)+++class TestIsStale:+ @parameterized.expand(+ [+ # (label, run_phase, updated_at_offset_from_now, expected)+ ("running_fresh", RunPhase.RUNNING, timedelta(minutes=1), False),+ ("running_just_under_threshold", RunPhase.RUNNING, STALE_AFTER - timedelta(seconds=1), False),+ ("running_just_over_threshold", RunPhase.RUNNING, STALE_AFTER + timedelta(seconds=1), True),+ ("idle_over_threshold_is_stale", RunPhase.IDLE, STALE_AFTER + timedelta(minutes=5), True),+ ("completed_never_stale", RunPhase.COMPLETED, STALE_AFTER + timedelta(days=30), False),+ ("error_never_stale", RunPhase.ERROR, STALE_AFTER + timedelta(days=30), False),+ ]+ )+ def test_is_stale(self, _label: str, run_phase: RunPhase, age: timedelta, expected: bool) -> None:+ updated_at = _NOW - age+ with patch("products.wizard.backend.logic.utils.timezone.now", return_value=_NOW):+ assert is_stale(run_phase, updated_at) is expecteddiff --git a/products/wizard/frontend/generated/api.schemas.ts b/products/wizard/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..c941b284abf1--- /dev/null+++ b/products/wizard/frontend/generated/api.schemas.ts@@ -0,0 +1,157 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+/**+ * * `idle` - IDLE+ * `running` - RUNNING+ * `completed` - COMPLETED+ * `error` - ERROR+ */+export type RunPhaseEnumApi = (typeof RunPhaseEnumApi)[keyof typeof RunPhaseEnumApi]++export const RunPhaseEnumApi = {+ Idle: 'idle',+ Running: 'running',+ Completed: 'completed',+ Error: 'error',+} as const++/**+ * * `pending` - PENDING+ * `in_progress` - IN_PROGRESS+ * `completed` - COMPLETED+ * `failed` - FAILED+ * `canceled` - CANCELED+ */+export type WizardTaskDTOStatusEnumApi = (typeof WizardTaskDTOStatusEnumApi)[keyof typeof WizardTaskDTOStatusEnumApi]++export const WizardTaskDTOStatusEnumApi = {+ Pending: 'pending',+ InProgress: 'in_progress',+ Completed: 'completed',+ Failed: 'failed',+ Canceled: 'canceled',+} as const++export interface WizardTaskDTOApi {+ id: string+ title: string+ status: WizardTaskDTOStatusEnumApi+}++/**+ * @nullable+ */+export type WizardSessionDTOApiEventPlan = { [key: string]: unknown } | null++/**+ * @nullable+ */+export type WizardSessionDTOApiError = { [key: string]: unknown } | null++/**+ * Output: serialises a WizardSessionDTO returned by the facade.+ */+export interface WizardSessionDTOApi {+ session_id: string+ team_id: number+ workflow_id: string+ skill_id: string+ started_at: string+ run_phase: RunPhaseEnumApi+ tasks: WizardTaskDTOApi[]+ /** @nullable */+ event_plan: WizardSessionDTOApiEventPlan+ /** @nullable */+ error: WizardSessionDTOApiError+ created_at: string+ updated_at: string+ is_stale: boolean+}++export interface PaginatedWizardSessionDTOListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: WizardSessionDTOApi[]+}++/**+ * Optional structured plan of events the wizard intends to instrument. Schema is workflow-specific.+ * @nullable+ */+export type UpsertWizardSessionRequestApiEventPlan = { [key: string]: unknown } | null++/**+ * Populated when run_phase='error'. Shape: { type: string, message: string }.+ * @nullable+ */+export type UpsertWizardSessionRequestApiError = { [key: string]: unknown } | null++/**+ * Input: validates the JSON the wizard CLI posts. team_id is derived from URL.+ */+export interface UpsertWizardSessionRequestApi {+ /**+ * Stable identifier the wizard mints for this run (format: '{workflow_id}-{skill_id}-{started_at_iso}'). Reposting with the same session_id upserts the existing row.+ * @maxLength 255+ */+ session_id: string+ /**+ * High-level workflow being run, e.g. 'onboarding', 'migration', 'audit'.+ * @maxLength 255+ */+ workflow_id: string+ /**+ * Specific skill within the workflow, e.g. 'nextjs', 'django', 'laravel'.+ * @maxLength 255+ */+ skill_id: string+ /** UTC timestamp when the wizard started this run. Matches the timestamp encoded in session_id. */+ started_at: string+ /** Lifecycle stage of the wizard run.++ * `idle` - IDLE+ * `running` - RUNNING+ * `completed` - COMPLETED+ * `error` - ERROR */+ run_phase: RunPhaseEnumApi+ tasks: WizardTaskDTOApi[]+ /**+ * Optional structured plan of events the wizard intends to instrument. Schema is workflow-specific.+ * @nullable+ */+ event_plan?: UpsertWizardSessionRequestApiEventPlan+ /**+ * Populated when run_phase='error'. Shape: { type: string, message: string }.+ * @nullable+ */+ error?: UpsertWizardSessionRequestApiError+}++export type WizardSessionsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Filter to a single skill within the workflow (e.g. 'nextjs').+ */+ skill_id?: string+ /**+ * Filter to a single workflow (e.g. 'onboarding').+ */+ workflow_id?: string+}diff --git a/products/wizard/frontend/generated/api.ts b/products/wizard/frontend/generated/api.tsnew file mode 100644index 000000000000..5a56f28ae06b--- /dev/null+++ b/products/wizard/frontend/generated/api.ts@@ -0,0 +1,84 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ PaginatedWizardSessionDTOListApi,+ UpsertWizardSessionRequestApi,+ WizardSessionDTOApi,+ WizardSessionsListParams,+} from './api.schemas'++export const getWizardSessionsListUrl = (projectId: string, params?: WizardSessionsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/wizard/sessions/?${stringifiedParams}`+ : `/api/projects/${projectId}/wizard/sessions/`+}++/**+ * List wizard sessions for the project, ordered by started_at desc. This should only be called by the PostHog Wizard. Optional filters: ?workflow_id=<id> and ?skill_id=<id>.+ */+export const wizardSessionsList = async (+ projectId: string,+ params?: WizardSessionsListParams,+ options?: RequestInit+): Promise<PaginatedWizardSessionDTOListApi> => {+ return apiMutator<PaginatedWizardSessionDTOListApi>(getWizardSessionsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getWizardSessionsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/wizard/sessions/`+}++/**+ * Upsert a wizard session. The `session_id` key is the idempotency anchor — reposting the same `session_id` replaces the existing row. Returns 201 on create, 200 on update.+ */+export const wizardSessionsCreate = async (+ projectId: string,+ upsertWizardSessionRequestApi: UpsertWizardSessionRequestApi,+ options?: RequestInit+): Promise<WizardSessionDTOApi> => {+ return apiMutator<WizardSessionDTOApi>(getWizardSessionsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(upsertWizardSessionRequestApi),+ })+}++export const getWizardSessionsRetrieveUrl = (projectId: string, sessionId: string) => {+ return `/api/projects/${projectId}/wizard/sessions/${sessionId}/`+}++/**+ * Retrieve a single wizard session by its session_id.+ */+export const wizardSessionsRetrieve = async (+ projectId: string,+ sessionId: string,+ options?: RequestInit+): Promise<WizardSessionDTOApi> => {+ return apiMutator<WizardSessionDTOApi>(getWizardSessionsRetrieveUrl(projectId, sessionId), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/wizard/frontend/generated/api.zod.ts b/products/wizard/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..fde4f9662e55--- /dev/null+++ b/products/wizard/frontend/generated/api.zod.ts@@ -0,0 +1,68 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Upsert a wizard session. The `session_id` key is the idempotency anchor — reposting the same `session_id` replaces the existing row. Returns 201 on create, 200 on update.+ */+export const wizardSessionsCreateBodySessionIdMax = 255++export const wizardSessionsCreateBodyWorkflowIdMax = 255++export const wizardSessionsCreateBodySkillIdMax = 255++export const WizardSessionsCreateBody = /* @__PURE__ */ zod+ .object({+ session_id: zod+ .string()+ .max(wizardSessionsCreateBodySessionIdMax)+ .describe(+ "Stable identifier the wizard mints for this run (format: '{workflow_id}-{skill_id}-{started_at_iso}'). Reposting with the same session_id upserts the existing row."+ ),+ workflow_id: zod+ .string()+ .max(wizardSessionsCreateBodyWorkflowIdMax)+ .describe("High-level workflow being run, e.g. 'onboarding', 'migration', 'audit'."),+ skill_id: zod+ .string()+ .max(wizardSessionsCreateBodySkillIdMax)+ .describe("Specific skill within the workflow, e.g. 'nextjs', 'django', 'laravel'."),+ started_at: zod.iso+ .datetime({ offset: true })+ .describe('UTC timestamp when the wizard started this run. Matches the timestamp encoded in session_id.'),+ run_phase: zod+ .enum(['idle', 'running', 'completed', 'error'])+ .describe('\* `idle` - IDLE\n\* `running` - RUNNING\n\* `completed` - COMPLETED\n\* `error` - ERROR')+ .describe(+ 'Lifecycle stage of the wizard run.\n\n\* `idle` - IDLE\n\* `running` - RUNNING\n\* `completed` - COMPLETED\n\* `error` - ERROR'+ ),+ tasks: zod.array(+ zod.object({+ id: zod.string(),+ title: zod.string(),+ status: zod+ .enum(['pending', 'in_progress', 'completed', 'failed', 'canceled'])+ .describe(+ '\* `pending` - PENDING\n\* `in_progress` - IN_PROGRESS\n\* `completed` - COMPLETED\n\* `failed` - FAILED\n\* `canceled` - CANCELED'+ ),+ })+ ),+ event_plan: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ 'Optional structured plan of events the wizard intends to instrument. Schema is workflow-specific.'+ ),+ error: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe("Populated when run_phase='error'. Shape: { type: string, message: string }."),+ })+ .describe('Input: validates the JSON the wizard CLI posts. team_id is derived from URL.')diff --git a/products/wizard/manifest.tsx b/products/wizard/manifest.tsxnew file mode 100644index 000000000000..fc44473de229--- /dev/null+++ b/products/wizard/manifest.tsx@@ -0,0 +1,23 @@+/**+ * Product manifest for wizard.+ *+ * Defines scenes, routes, URLs, and navigation for this product.+ */+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'Wizard',+ scenes: {+ // Define scenes here+ },+ routes: {+ // Define routes here+ },+ redirects: {},+ urls: {+ // Define URL helpers here+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/wizard/package.json b/products/wizard/package.jsonnew file mode 100644index 000000000000..e0b8544e682c--- /dev/null+++ b/products/wizard/package.json@@ -0,0 +1,7 @@+{+ "name": "@posthog/products-wizard",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",+ "backend:contract-check": "echo 'Contract files unchanged'"+ }+}diff --git a/products/wizard/product.yaml b/products/wizard/product.yamlnew file mode 100644index 000000000000..9d2463e350b5--- /dev/null+++ b/products/wizard/product.yaml@@ -0,0 +1,3 @@+name: Wizard+owners:+ - team-wizarddiff --git a/products/wizard/tsconfig.json b/products/wizard/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/wizard/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/wizard/turbo.json b/products/wizard/turbo.jsonnew file mode 100644index 000000000000..34a16b3d30ce--- /dev/null+++ b/products/wizard/turbo.json@@ -0,0 +1,10 @@+{+ "extends": ["//"],+ "tasks": {+ "backend:contract-check": {+ "inputs": ["backend/facade/**", "backend/presentation/**"],+ "outputs": [],+ "cache": true+ }+ }+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a74b64af6ffc..036f2d5d2b17 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26030,6 +26030,85 @@ export namespace Schemas {results: WebExperimentsAPI[];}+ /**+ * * `idle` - IDLE+ * `running` - RUNNING+ * `completed` - COMPLETED+ * `error` - ERROR+ */+ export type RunPhaseEnum = typeof RunPhaseEnum[keyof typeof RunPhaseEnum];+++ export const RunPhaseEnum = {+ Idle: 'idle',+ Running: 'running',+ Completed: 'completed',+ Error: 'error',+ } as const;++ /**+ * * `pending` - PENDING+ * `in_progress` - IN_PROGRESS+ * `completed` - COMPLETED+ * `failed` - FAILED+ * `canceled` - CANCELED+ */+ export type WizardTaskDTOStatusEnum = typeof WizardTaskDTOStatusEnum[keyof typeof WizardTaskDTOStatusEnum];+++ export const WizardTaskDTOStatusEnum = {+ Pending: 'pending',+ InProgress: 'in_progress',+ Completed: 'completed',+ Failed: 'failed',+ Canceled: 'canceled',+ } as const;++ export interface WizardTaskDTO {+ id: string;+ title: string;+ status: WizardTaskDTOStatusEnum;+ }++ /**+ * @nullable+ */+ export type WizardSessionDTOEventPlan = { [key: string]: unknown } | null;++ /**+ * @nullable+ */+ export type WizardSessionDTOError = { [key: string]: unknown } | null;++ /**+ * Output: serialises a WizardSessionDTO returned by the facade.+ */+ export interface WizardSessionDTO {+ session_id: string;+ team_id: number;+ workflow_id: string;+ skill_id: string;+ started_at: string;+ run_phase: RunPhaseEnum;+ tasks: WizardTaskDTO[];+ /** @nullable */+ event_plan: WizardSessionDTOEventPlan;+ /** @nullable */+ error: WizardSessionDTOError;+ created_at: string;+ updated_at: string;+ is_stale: boolean;+ }++ export interface PaginatedWizardSessionDTOList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: WizardSessionDTO[];+ }+/*** Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id). Defaults to an empty object. Unknown keys are rejected.* @nullable@@ -37071,6 +37150,59 @@ export namespace Schemas {target_language?: string;}+ /**+ * Optional structured plan of events the wizard intends to instrument. Schema is workflow-specific.+ * @nullable+ */+ export type UpsertWizardSessionRequestEventPlan = { [key: string]: unknown } | null;++ /**+ * Populated when run_phase='error'. Shape: { type: string, message: string }.+ * @nullable+ */+ export type UpsertWizardSessionRequestError = { [key: string]: unknown } | null;++ /**+ * Input: validates the JSON the wizard CLI posts. team_id is derived from URL.+ */+ export interface UpsertWizardSessionRequest {+ /**+ * Stable identifier the wizard mints for this run (format: '{workflow_id}-{skill_id}-{started_at_iso}'). Reposting with the same session_id upserts the existing row.+ * @maxLength 255+ */+ session_id: string;+ /**+ * High-level workflow being run, e.g. 'onboarding', 'migration', 'audit'.+ * @maxLength 255+ */+ workflow_id: string;+ /**+ * Specific skill within the workflow, e.g. 'nextjs', 'django', 'laravel'.+ * @maxLength 255+ */+ skill_id: string;+ /** UTC timestamp when the wizard started this run. Matches the timestamp encoded in session_id. */+ started_at: string;+ /** Lifecycle stage of the wizard run.++ * `idle` - IDLE+ * `running` - RUNNING+ * `completed` - COMPLETED+ * `error` - ERROR */+ run_phase: RunPhaseEnum;+ tasks: WizardTaskDTO[];+ /**+ * Optional structured plan of events the wizard intends to instrument. Schema is workflow-specific.+ * @nullable+ */+ event_plan?: UpsertWizardSessionRequestEventPlan;+ /**+ * Populated when run_phase='error'. Shape: { type: string, message: string }.+ * @nullable+ */+ error?: UpsertWizardSessionRequestError;+ }+/*** The release condition to evaluate*/@@ -46522,6 +46654,25 @@ export namespace Schemas {offset?: number;};+ export type WizardSessionsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * Filter to a single skill within the workflow (e.g. 'nextjs').+ */+ skill_id?: string;+ /**+ * Filter to a single workflow (e.g. 'onboarding').+ */+ workflow_id?: string;+ };+export type PublicHogFunctionTemplatesListParams = {/*** Number of results to return per page.diff --git a/tach.toml b/tach.tomlindex 900252171e20..71d1880c990a 100644--- a/tach.toml+++ b/tach.toml@@ -103,6 +103,7 @@ depends_on = ["products.mcp_analytics","products.warehouse_sources_queue","products.web_analytics",+ "products.wizard","products.workflows","products.actions","products.alerts", "products.warehouse_sources", "products.data_tools",@@ -686,3 +687,17 @@ expose = [from = ["products.business_knowledge",]++[[modules]]+path = "products.wizard"+depends_on = ["posthog"]+layer = "modules"++[[interfaces]]+expose = [+ "backend\\.facade.*",+ "backend\\.presentation\\.views.*",+]+from = [+ "products.wizard",+]