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): expose cloud run APIs (#91822)

Fernando Gomese1a6c5a64d85
diff --git a/.gitignore b/.gitignore
index 677843753ea7..d9030ae940aa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -237,3 +237,5 @@ corpora/
# workflow's artifact; it is never committed.
.test_durations
.test_durations.*
+
+/context.md
diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.md
new file mode 100644
index 000000000000..87071c9eb529
--- /dev/null
+++ b/docs/internal/wizard-runs.md
@@ -0,0 +1,116 @@
+# Wizard runs
+
+The Wizard is a setup agent distributed as an npm package.
+A Wizard run records one execution of that agent inside a user-provided workspace.
+
+## Environments and workspaces
+
+V0 supports two configurations:
+
+| Environment | Workspace | Execution |
+| ----------- | ---------------------------------------- | ----------------------------------- |
+| `local` | Local folder with a `project_name` | The user's machine |
+| `cloud` | GitHub repository in `owner/name` format | A PostHog-provisioned Wizard Worker |
+
+The request uses explicit `environment` and `workspace.type` discriminators.
+The backend rejects unsupported combinations before creating a run.
+
+Uploaded archives are not part of V0.
+They will use object-storage references rather than archive bytes in Postgres or Temporal payloads.
+
+## Lifecycle
+
+A local run starts in `running` because the local agent creates it after starting.
+A cloud run starts in `created` before its Temporal workflow is dispatched.
+
+Valid transitions are:
+
+```text
+created -> running
+created -> failed
+created -> cancelled
+running -> completed
+running -> failed
+running -> cancelled
+```
+
+`completed`, `failed`, and `cancelled` are terminal.
+Failed runs can include a typed error code.
+Successful output is represented by Run Artifacts rather than an outcome field.
+
+## API
+
+Run endpoints are scoped to the project in the URL:
+
+```text
+GET /api/projects/{project_id}/wizard/runs/
+POST /api/projects/{project_id}/wizard/runs/
+GET /api/projects/{project_id}/wizard/runs/{run_id}/
+PATCH /api/projects/{project_id}/wizard/runs/{run_id}/
+GET /api/projects/{project_id}/wizard/runs/{run_id}/artifacts/
+```
+
+The PATCH request accepts a terminal `status`: `completed`, `failed`, or `cancelled`.
+Failed runs can also include an `error_code`.
+Local agents can create runs and update runs they created.
+Cloud creation requires a signed-in browser session and enabled cloud execution.
+Cloud lifecycle updates are owned by the Wizard Worker.
+
+Run lookups, transitions, and artifact access verify the project boundary.
+A user cannot update another user's local run.
+
+## Cloud execution
+
+Cloud creation verifies that the project has a GitHub integration with access to the requested repository.
+The check runs again when execution starts because access can change while a run is queued.
+
+After the database transaction commits, the backend starts a Temporal workflow with only the project ID and run ID.
+The provisioning activity marks the run as `running` before it creates the Wizard Worker.
+The handoff activity marks the run as `completed` after it persists the Run Artifacts.
+If a worker activity exhausts its retries or the workflow is canceled, one finalization activity records the terminal state.
+Sandbox cleanup does not change a completed run if cleanup fails.
+
+The Worker:
+
+1. Resolves short-lived GitHub and Wizard credentials inside the activity.
+2. Provisions an isolated sandbox through the generic Tasks sandbox facade.
+3. Clones the repository.
+4. Runs the headless Wizard against the prepared workspace.
+5. Captures a binary Git diff.
+6. Creates a signed commit and opens or reuses a pull request when the workspace changed.
+7. Destroys the sandbox.
+
+Tokens do not enter Temporal inputs, workflow history, run metadata, or logs.
+Wizard owns the Worker command, environment, credentials, resource limits, timeouts, and diff behavior.
+Tasks provides only generic repository-token and sandbox helpers through public facades.
+
+## Deployment configuration
+
+The production rollout depends on the [Wizard Worker chart](https://github.com/PostHog/charts/pull/14662) and [cloud infrastructure](https://github.com/PostHog/posthog-cloud-infra/pull/10081) changes.
+The chart must run a worker that polls `wizard-task-queue` before cloud run creation is enabled.
+`WIZARD_RUN_ARTIFACTS_S3_BUCKET` must identify the provisioned artifact bucket.
+`WIZARD_RUN_CREATE_THROTTLE_RATE` and `WIZARD_RUN_READ_THROTTLE_RATE` can override the default API limits.
+`LOCAL_WIZARD_ROOT` only enables local source uploads when Django runs in debug mode.
+
+## Run Artifacts
+
+V0 stores a non-empty Git diff in object storage.
+The database stores its object-storage path, byte size, SHA-256 hash, type, project, and run relationship.
+The public API returns artifact metadata and does not return diff bytes through Temporal.
+
+No artifact is created when the workspace has no changes.
+For a Git-repository workspace with changes, V0 also stores the pull request URL, number, repository, source branch, and target branch.
+Updated archives remain a future artifact type.
+
+## State synchronization
+
+The existing Wizard session endpoint remains active during migration:
+
+```text
+POST /api/projects/{project_id}/wizard/sessions/
+```
+
+Wizard sessions remain independent from Wizard runs in V0.
+They continue to synchronize the setup agent's legacy workflow and skill state without a run ID.
+
+The existing `/api/wizard/cloud_run` onboarding flow remains Tasks-backed until its TaskRun progress and pull-request UI have a replacement based on Wizard runs and Run Artifacts.
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 37a9eccbbc67..a669071b2edb 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -102,6 +102,7 @@ SANDBOX_AGENT_OTEL_TRACES_URL: str | None = get_from_env("SANDBOX_AGENT_OTEL_TRA
# 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", "")
+LOCAL_WIZARD_ROOT: str | None = get_from_env("LOCAL_WIZARD_ROOT", None, optional=True)
# When True, cloud-to-cloud resume can create legacy Modal filesystem snapshots
# at end-of-run. Modal filesystem image storage is not EU-compliant, so this is
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 20853f05f5ff..ecd782285f28 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -493,6 +493,9 @@ SIGNUP_IP_THROTTLE_RATE = get_from_env("SIGNUP_IP_THROTTLE_RATE", "5/day")
BILLING_EXPORT_THROTTLE_RATE = get_from_env("BILLING_EXPORT_THROTTLE_RATE", "10/minute")
BILLING_EXPORT_CONCURRENT_STREAMS = get_from_env("BILLING_EXPORT_CONCURRENT_STREAMS", 4, type_cast=int)
+WIZARD_RUN_CREATE_THROTTLE_RATE = get_from_env("WIZARD_RUN_CREATE_THROTTLE_RATE", "30/hour")
+WIZARD_RUN_READ_THROTTLE_RATE = get_from_env("WIZARD_RUN_READ_THROTTLE_RATE", "120/minute")
+
# Email domains whose signups are created already-verified (skipping the email round-trip), so
# non-prod deploy smoke-tests can sign up and act immediately. Empty by default — prod verifies
# every signup.
@@ -597,6 +600,7 @@ SPECTACULAR_SETTINGS = {
# The same choice set is declared in more than one product. A shared Choices
# class would cross a product boundary, so the entry names the set centrally.
"RunStatusEnum": ["not_started", "queued", "in_progress", "completed", "failed", "cancelled"],
+ "RunEnvironmentEnum": ["local", "cloud"],
"DiagnosticSeverityEnum": ["error", "warning"],
"InitialPermissionModeEnum": ["default", "acceptEdits", "plan", "bypassPermissions", "auto"],
"NotificationDestinationTypeEnum": ["slack", "webhook", "teams"],
@@ -740,6 +744,15 @@ SPECTACULAR_SETTINGS = {
"user_attachment",
"skill_bundle",
],
+ "ArtifactType2f0Enum": [
+ "slack_message",
+ "slack_canvas",
+ "document",
+ "spreadsheet",
+ "dashboard",
+ "file",
+ "github_pr",
+ ],
"AdapterEnum": ["slack_message", "slack_canvas", "slack_file", "document_connector", "github_pr"],
"ActionStepMatchingEnum": ["contains", "regex", "exact"],
"DetailModeValueEnum": ["minimal", "detailed"],
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 44ccbd624468..750b191e5576 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -131,6 +131,7 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import (
reap_stale_prewarm_heatmaps,
report_stuck_heatmap_screenshots,
)
+from products.wizard.backend.facade.tasks import reconcile_wizard_runs
from products.workflows.backend.tasks.email_sending_tiers import recompute_workflows_email_sending_tiers
from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputation
from products.workflows.backend.tasks.ses_tenant_state import reconcile_ses_tenant_states
@@ -227,6 +228,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="tasks run state metrics",
)
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*/2"),
+ reconcile_wizard_runs.s(),
+ name="reconcile wizard runs",
+ )
+
sender.add_periodic_task(10, redis_heartbeat.s(), name="10 sec heartbeat")
sender.add_periodic_task(
QueryStatusManager.POLL_INTERVAL_SECONDS,
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 09207078f93f..9581ea0defd3 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -3078,10 +3078,9 @@ export interface PaginatedTaskRunDetailDTOListApi {
* * `local` - local
* * `cloud` - cloud
*/
-export type TaskRunBootstrapCreateRequestEnvironmentEnumApi =
- (typeof TaskRunBootstrapCreateRequestEnvironmentEnumApi)[keyof typeof TaskRunBootstrapCreateRequestEnvironmentEnumApi]
+export type RunEnvironmentEnumApi = (typeof RunEnvironmentEnumApi)[keyof typeof RunEnvironmentEnumApi]
-export const TaskRunBootstrapCreateRequestEnvironmentEnumApi = {
+export const RunEnvironmentEnumApi = {
Local: 'local',
Cloud: 'cloud',
} as const
@@ -3104,7 +3103,7 @@ export interface TaskRunBootstrapCreateRequestApi {
*
* * `local` - local
* * `cloud` - cloud */
- environment?: TaskRunBootstrapCreateRequestEnvironmentEnumApi
+ environment?: RunEnvironmentEnumApi
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -4004,9 +4003,9 @@ export interface TaskSessionSyncResponseApi {
* * `file` - file
* * `github_pr` - github_pr
*/
-export type ArtifactTypeEnumApi = (typeof ArtifactTypeEnumApi)[keyof typeof ArtifactTypeEnumApi]
+export type ArtifactType2f0EnumApi = (typeof ArtifactType2f0EnumApi)[keyof typeof ArtifactType2f0EnumApi]
-export const ArtifactTypeEnumApi = {
+export const ArtifactType2f0EnumApi = {
SlackMessage: 'slack_message',
SlackCanvas: 'slack_canvas',
Document: 'document',
@@ -4066,7 +4065,7 @@ export interface TaskRunLivingArtifactResponseApi {
* * `dashboard` - dashboard
* * `file` - file
* * `github_pr` - github_pr */
- artifact_type: ArtifactTypeEnumApi
+ artifact_type: ArtifactType2f0EnumApi
/** Adapter that currently stores or edits the artifact.
*
* * `slack_message` - slack_message
@@ -4125,7 +4124,7 @@ export interface TaskRunLivingArtifactCreateRequestApi {
* * `dashboard` - dashboard
* * `file` - file
* * `github_pr` - github_pr */
- artifact_type?: ArtifactTypeEnumApi
+ artifact_type?: ArtifactType2f0EnumApi
/** Optional preferred external storage or delivery adapter. Slack adapters deliver into the mapped Slack thread; omitted Slack-run documents use Slack canvas, omitted Slack-run files and spreadsheets use Slack file upload, and document_connector uses a connected external document provider.
*
* * `slack_message` - slack_message
@@ -4176,7 +4175,7 @@ export interface TaskRunLivingArtifactOpenResponseApi {
* * `dashboard` - dashboard
* * `file` - file
* * `github_pr` - github_pr */
- artifact_type: ArtifactTypeEnumApi
+ artifact_type: ArtifactType2f0EnumApi
/** Adapter that currently stores or edits the artifact.
*
* * `slack_message` - slack_message
diff --git a/products/wizard/backend/facade/enums.py b/products/wizard/backend/facade/enums.py
index ca917ef96b93..ddad7daaa8f1 100644
--- a/products/wizard/backend/facade/enums.py
+++ b/products/wizard/backend/facade/enums.py
@@ -26,10 +26,6 @@ class WizardSessionTaskStatus(StrEnum):
CANCELED = "canceled"
-RunPhase = WizardSessionRunPhase
-TaskStatus = WizardSessionTaskStatus
-
-
class WizardRunStatus(StrEnum):
CREATED = "created"
RUNNING = "running"
diff --git a/products/wizard/backend/facade/tasks.py b/products/wizard/backend/facade/tasks.py
new file mode 100644
index 000000000000..a1fa877a5511
--- /dev/null
+++ b/products/wizard/backend/facade/tasks.py
@@ -0,0 +1,11 @@
+"""Facade re-export for the wizard Celery task.
+
+Core's beat schedule (``posthog/tasks/scheduled.py``) imports the task object and calls
+``.s()`` on it, so the wiring crosses the boundary as an object, not data. Re-exporting
+the task keeps that coupling at the facade boundary. Its ``name=`` is pinned in
+``tasks/reconciliation.py``, so the registered task identity is independent of the import path.
+"""
+
+from products.wizard.backend.tasks.reconciliation import reconcile_wizard_runs
+
+__all__ = ["reconcile_wizard_runs"]
diff --git a/products/wizard/backend/logic/pubsub.py b/products/wizard/backend/logic/pubsub.py
deleted file mode 100644
index 017f275fd9a2..000000000000
--- a/products/wizard/backend/logic/pubsub.py
+++ /dev/null
@@ -1,147 +0,0 @@
-"""
-Redis pub/sub fanout for wizard session updates.
-
-Publish happens inside `transaction.on_commit` so subscribers never see
-uncommitted state. Subscribers (SSE endpoint) use the async client so each
-idle connection is a coroutine on the event loop, not a thread pinning the
-asgiref pool.
-"""
-
-from __future__ import annotations
-
-import re
-import dataclasses
-from collections.abc import AsyncIterator
-from contextlib import asynccontextmanager
-from datetime import datetime
-from enum import Enum
-from typing import Any
-
-from django.db import transaction
-
-import orjson
-import structlog
-
-from posthog.redis import get_async_client, get_client
-
-from products.wizard.backend.facade.contracts import WizardSessionDTO
-from products.wizard.backend.metrics import WIZARD_PUBSUB_PUBLISH_TOTAL
-
-logger = structlog.get_logger(__name__)
-
-CHANNEL_PREFIX = "wizard_sessions"
-
-# workflow_id / skill_id appear unescaped in Redis channel names / patterns;
-# reject anything that could be a glob metacharacter (`*?[]\`) or the `:` delimiter.
-_SAFE_ID_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,255}$")
-
-
-def _validate_id(value: str, name: str) -> None:
- if not _SAFE_ID_RE.match(value):
- raise ValueError(f"{name} must match {_SAFE_ID_RE.pattern}; got {value!r}")
-
-
-def channel_name(team_id: int, workflow_id: str, skill_id: str) -> str:
- _validate_id(workflow_id, "workflow_id")
- _validate_id(skill_id, "skill_id")
- return f"{CHANNEL_PREFIX}:team:{team_id}:workflow:{workflow_id}:skill:{skill_id}"
-
-
-def channel_pattern(team_id: int, workflow_id: str) -> str:
- """Pattern for subscribing to all skills under a (team, workflow_id)."""
- _validate_id(workflow_id, "workflow_id")
- return f"{CHANNEL_PREFIX}:team:{team_id}:workflow:{workflow_id}:skill:*"
-
-
-def serialize_dto(dto: WizardSessionDTO) -> bytes:
- return orjson.dumps(dto, default=_json_default)
-
-
-def publish_session_update(dto: WizardSessionDTO) -> None:
- """Schedule a Redis publish after the current transaction commits.
-
- Publish failures are logged and swallowed — fanout is best-effort and
- must not fail the already-committed upsert.
- """
- payload = serialize_dto(dto)
- channel = channel_name(dto.team_id, dto.workflow_id, dto.skill_id)
-
- def _publish() -> None:
- try:
- receivers = get_client().publish(channel, payload)
- except Exception:
- WIZARD_PUBSUB_PUBLISH_TOTAL.labels(outcome="failed").inc()
- logger.exception(
- "wizard_sessions publish failed",
- channel=channel,
- session_id=dto.session_id,
- payload_bytes=len(payload),
- )
- return
- WIZARD_PUBSUB_PUBLISH_TOTAL.labels(outcome="published").inc()
- logger.debug(
- "wizard_sessions publish",
- channel=channel,
- session_id=dto.session_id,
- run_phase=dto.run_phase.value,
- payload_bytes=len(payload),
- receivers=receivers,
- )
-
- transaction.on_commit(_publish)
-
-
-@asynccontextmanager
-async def subscribe(team_id: int, workflow_id: str, skill_id: str | None = None) -> AsyncIterator[Any]:
- """Subscribe to wizard-session events.
-
- With `skill_id`, subscribes to the exact `(team, workflow, skill)` channel.
- Without it, pattern-subscribes to every skill under `(team, workflow)`;
- messages arrive as `{type: 'pmessage', ...}` instead of `{type: 'message'}`.
- """
- if skill_id is not None:
- target = channel_name(team_id, workflow_id, skill_id)
- is_pattern = False
- else:
- target = channel_pattern(team_id, workflow_id)
- is_pattern = True
-
- redis = get_async_client()
- pubsub = redis.pubsub(ignore_subscribe_messages=True)
- try:
- if is_pattern:
- await pubsub.psubscribe(target)
- else:
- await pubsub.subscribe(target)
- except Exception:
- try:
- await pubsub.close()
- except Exception:
- pass
- raise
-
- try:
- yield pubsub
- finally:
- try:
- if is_pattern:
- await pubsub.punsubscribe(target)
- else:
- await pubsub.unsubscribe(target)
- except Exception:
- logger.warning("wizard_sessions unsubscribe failed", target=target)
- finally:
- try:
- await pubsub.close()
- except Exception:
- logger.warning("wizard_sessions pubsub close failed", target=target)
-
-
-def _json_default(value: Any) -> Any:
- if dataclasses.is_dataclass(value) and not isinstance(value, type):
- return dataclasses.asdict(value)
- if isinstance(value, Enum):
- return value.value
- if isinstance(value, datetime):
- return value.isoformat()
- raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
diff --git a/products/wizard/backend/logic/reconciliation/config.py b/products/wizard/backend/logic/reconciliation/config.py
new file mode 100644
index 000000000000..6b0214fb0774
--- /dev/null
+++ b/products/wizard/backend/logic/reconciliation/config.py
@@ -0,0 +1,2 @@
+RECONCILIATION_BATCH_SIZE = 100
+RECONCILIATION_DISPATCH_TIME_BUDGET_SECONDS = 30
diff --git a/products/wizard/backend/logic/reconciliation/service.py b/products/wizard/backend/logic/reconciliation/service.py
new file mode 100644
index 000000000000..d5c5618acf74
--- /dev/null
+++ b/products/wizard/backend/logic/reconciliation/service.py
@@ -0,0 +1,181 @@
+import logging
+from time import monotonic
+
+from django.db.models import Q
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+
+from products.wizard.backend.facade.enums import (
+ WizardRunDispatchStatus,
+ WizardRunErrorCode,
+ WizardRunStatus,
+ WizardWorkerCleanupStatus,
+)
+from products.wizard.backend.facade.errors import IllegalStatusTransitionError, WizardRunNotFoundError
+from products.wizard.backend.logic.reconciliation.config import (
+ RECONCILIATION_BATCH_SIZE,
+ RECONCILIATION_DISPATCH_TIME_BUDGET_SECONDS,
+)
+from products.wizard.backend.logic.runs import cancellation, lifecycle
+from products.wizard.backend.logic.runs.config import WORKER_CLEANUP_MAX_ATTEMPTS
+from products.wizard.backend.logic.runs.dispatch import dispatch_created_cloud_wizard_run_to_temporal_worker
+from products.wizard.backend.logic.runs.errors import WizardRunDispatchError, WizardWorkerCleanupError
+from products.wizard.backend.logic.workers import lifecycle as worker_lifecycle
+from products.wizard.backend.models import WizardRun, WizardWorker
+from products.wizard.backend.observability.service import wizard_observability
+
+logger = logging.getLogger(__name__)
+
+
+@frozen
+class ReconciliationSummary:
+ scanned: int
+ reconciled: int
+ failed: int
+ batch_limit_reached: bool
+
+
+def _summary(scanned: int, reconciled: int) -> ReconciliationSummary:
+ return ReconciliationSummary(
+ scanned=scanned,
+ reconciled=reconciled,
+ failed=scanned - reconciled,
+ batch_limit_reached=scanned == RECONCILIATION_BATCH_SIZE,
+ )
+
+
+def reconcile_pending_dispatches() -> ReconciliationSummary:
+ pending = list(
+ WizardRun.objects.unscoped()
+ .filter(
+ status=WizardRunStatus.CREATED.value,
+ dispatch_status=WizardRunDispatchStatus.PENDING.value,
+ )
+ .filter(Q(dispatch_next_attempt_at__isnull=True) | Q(dispatch_next_attempt_at__lte=timezone.now()))
+ .order_by("dispatch_next_attempt_at", "created_at")
+ .values_list("team_id", "id")[:RECONCILIATION_BATCH_SIZE]
+ )
+
+ reconciled = 0
+ scanned = 0
+ started_at = monotonic()
+ for team_id, run_id in pending:
+ if scanned > 0 and monotonic() - started_at >= RECONCILIATION_DISPATCH_TIME_BUDGET_SECONDS:
+ break
+ scanned += 1
+ try:
+ dispatch_created_cloud_wizard_run_to_temporal_worker(team_id, run_id)
+ except WizardRunDispatchError as error:
+ logger.exception(
+ "wizard_run_redispatch_failed",
+ extra={"team_id": team_id, "run_id": str(run_id), "exhausted": error.exhausted},
+ )
+ if error.exhausted:
+ try:
+ lifecycle.fail_run(team_id, run_id, error_code=WizardRunErrorCode.DISPATCH_FAILED.value)
+ except (IllegalStatusTransitionError, WizardRunNotFoundError, ValueError):
+ logger.exception(
+ "wizard_run_dispatch_exhaustion_failed",
+ extra={"team_id": team_id, "run_id": str(run_id)},
+ )
+ continue
+ except (WizardRunNotFoundError, ValueError):
+ logger.exception("wizard_run_redispatch_failed", extra={"team_id": team_id, "run_id": str(run_id)})
+ continue
+ reconciled += 1
+
+ return ReconciliationSummary(
+ scanned=scanned,
+ reconciled=reconciled,
+ failed=scanned - reconciled,
+ batch_limit_reached=scanned == RECONCILIATION_BATCH_SIZE,
+ )
+
+
+def reconcile_pending_cancellations() -> ReconciliationSummary:
+ pending = list(
+ WizardRun.objects.unscoped()
+ .filter(
+ status__in=(WizardRunStatus.CANCELLED.value, WizardRunStatus.FAILED.value),
+ cancellation_requested_at__isnull=False,
+ cancellation_dispatched_at__isnull=True,
+ )
+ .values_list("team_id", "id")[:RECONCILIATION_BATCH_SIZE]
+ )
+
+ reconciled = 0
+ for team_id, run_id in pending:
+ try:
+ reconciled += cancellation.dispatch_cancellation(team_id, run_id)
+ except (WizardRunNotFoundError, ValueError):
+ logger.exception(
+ "wizard_run_cancellation_reconciliation_failed",
+ extra={"team_id": team_id, "run_id": str(run_id)},
+ )
+
+ return _summary(len(pending), reconciled)
+
+
+def reconcile_expired_runs() -> ReconciliationSummary:
+ expired = list(
+ WizardRun.objects.unscoped()
+ .filter(
+ status__in=(WizardRunStatus.CREATED.value, WizardRunStatus.RUNNING.value),
+ deadline_at__lte=timezone.now(),
+ )
+ .values_list("team_id", "id", "workflow_id")[:RECONCILIATION_BATCH_SIZE]
+ )
+
+ reconciled = 0
+ for team_id, run_id, workflow_id in expired:
+ try:
+ run = lifecycle.fail_run(team_id, run_id, error_code=WizardRunErrorCode.TIMEOUT)
+ except (IllegalStatusTransitionError, WizardRunNotFoundError, ValueError):
+ logger.exception("wizard_run_expiration_failed", extra={"team_id": team_id, "run_id": str(run_id)})
+ continue
+ wizard_observability.run_past_deadline(run)
+ if workflow_id is not None:
+ lifecycle.request_cloud_run_cancellation(team_id, run_id)
+ reconciled += 1
+
+ return _summary(len(expired), reconciled)
+
+
+def reconcile_pending_worker_cleanup() -> ReconciliationSummary:
+ now = timezone.now()
+ pending = list(
+ WizardWorker.objects.unscoped()
+ .filter(
+ cleanup_status__in=(
+ WizardWorkerCleanupStatus.ACTIVE.value,
+ WizardWorkerCleanupStatus.PENDING.value,
+ ),
+ cleanup_attempts__lt=WORKER_CLEANUP_MAX_ATTEMPTS,
+ sandbox_id__isnull=False,
+ )
+ .filter(
+ Q(
+ run__status__in=(
+ WizardRunStatus.COMPLETED.value,
+ WizardRunStatus.FAILED.value,
+ WizardRunStatus.CANCELLED.value,
+ )
+ )
+ | Q(run__deadline_at__lte=now)
+ )
+ .values_list("team_id", "run_id", "sandbox_id")[:RECONCILIATION_BATCH_SIZE]
+ )
+
+ reconciled = 0
+ for team_id, run_id, sandbox_id in pending:
+ if sandbox_id is None:
+ continue
+ try:
+ worker_lifecycle.cleanup_worker(team_id, run_id, sandbox_id)
+ except WizardWorkerCleanupError:
+ logger.exception("wizard_worker_reconciliation_failed", extra={"team_id": team_id, "run_id": str(run_id)})
+ continue
+ reconciled += 1
+
+ return _summary(len(pending), reconciled)
diff --git a/products/wizard/backend/logic/utils.py b/products/wizard/backend/logic/utils.py
deleted file mode 100644
index 7872dcb6f271..000000000000
--- a/products/wizard/backend/logic/utils.py
+++ /dev/null
@@ -1,14 +0,0 @@
-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_after
diff --git a/products/wizard/backend/presentation/artifacts/__init__.py b/products/wizard/backend/presentation/artifacts/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/wizard/backend/presentation/artifacts/pagination.py b/products/wizard/backend/presentation/artifacts/pagination.py
new file mode 100644
index 000000000000..9d83bcdf73c8
--- /dev/null
+++ b/products/wizard/backend/presentation/artifacts/pagination.py
@@ -0,0 +1,6 @@
+from rest_framework.pagination import LimitOffsetPagination
+
+
+class WizardRunArtifactPagination(LimitOffsetPagination):
+ default_limit = 100
+ max_limit = 100
diff --git a/products/wizard/backend/presentation/artifacts/serializers.py b/products/wizard/backend/presentation/artifacts/serializers.py
new file mode 100644
index 000000000000..00f8e2dbd014
--- /dev/null
+++ b/products/wizard/backend/presentation/artifacts/serializers.py
@@ -0,0 +1,67 @@
+from typing import cast
+
+from drf_spectacular.utils import PolymorphicProxySerializer
+from rest_framework import serializers
+
+from products.wizard.backend.facade.contracts import (
+ WizardRunArtifactDTO,
+ WizardRunGitDiffArtifactDTO,
+ WizardRunPullRequestArtifactDTO,
+)
+from products.wizard.backend.facade.enums import WizardRunArtifactType
+
+
+class WizardRunArtifactSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique ID of the run artifact.")
+ team_id = serializers.IntegerField(read_only=True, help_text="Project that owns the run artifact.")
+ run_id = serializers.UUIDField(read_only=True, help_text="Wizard run that produced the artifact.")
+
+
+class WizardRunGitDiffArtifactSerializer(WizardRunArtifactSerializer):
+ artifact_type = serializers.ChoiceField(
+ read_only=True,
+ choices=[WizardRunArtifactType.GIT_DIFF.value],
+ help_text="Format of the changes produced by the run.",
+ )
+ size_bytes = serializers.IntegerField(read_only=True, help_text="Stored artifact size in bytes.")
+ content_hash = serializers.CharField(read_only=True, help_text="SHA-256 hash of the stored artifact content.")
+ additions = serializers.IntegerField(
+ read_only=True, allow_null=True, help_text="Number of added lines in the diff."
+ )
+ removals = serializers.IntegerField(
+ read_only=True, allow_null=True, help_text="Number of removed lines in the diff."
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="Time when the artifact was stored.")
+
+
+class WizardRunPullRequestArtifactSerializer(WizardRunArtifactSerializer):
+ artifact_type = serializers.ChoiceField(
+ read_only=True,
+ choices=[WizardRunArtifactType.PULL_REQUEST.value],
+ help_text="Format of the changes produced by the run.",
+ )
+ url = serializers.URLField(read_only=True, help_text="GitHub URL of the pull request.")
+ number = serializers.IntegerField(read_only=True, help_text="Repository-local pull request number.")
+ repository = serializers.CharField(read_only=True, help_text="GitHub repository in owner/name format.")
+ head_branch = serializers.CharField(read_only=True, help_text="Branch containing the setup agent's changes.")
+ base_branch = serializers.CharField(read_only=True, help_text="Branch that the pull request targets.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="Time when the artifact was stored.")
+
+
+WizardRunArtifactSchema = PolymorphicProxySerializer(
+ component_name="WizardRunArtifact",
+ serializers={
+ WizardRunArtifactType.GIT_DIFF.value: WizardRunGitDiffArtifactSerializer,
+ WizardRunArtifactType.PULL_REQUEST.value: WizardRunPullRequestArtifactSerializer,
+ },
+ resource_type_field_name="artifact_type",
+ many=True,
+)
+
+
+def serialize_wizard_run_artifact(artifact: WizardRunArtifactDTO) -> dict[str, object]:
+ if isinstance(artifact, WizardRunGitDiffArtifactDTO):
+ return cast(dict[str, object], WizardRunGitDiffArtifactSerializer(artifact).data)
+ if isinstance(artifact, WizardRunPullRequestArtifactDTO):
+ return cast(dict[str, object], WizardRunPullRequestArtifactSerializer(artifact).data)
+ raise TypeError("Unsupported Wizard run artifact")
diff --git a/products/wizard/backend/presentation/artifacts/views.py b/products/wizard/backend/presentation/artifacts/views.py
new file mode 100644
index 000000000000..2fe7c818bd01
--- /dev/null
+++ b/products/wizard/backend/presentation/artifacts/views.py
@@ -0,0 +1,100 @@
+from typing import cast
+from uuid import UUID
+
+from django.http import HttpResponse
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import APIException, NotFound
+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.config import WIZARD_GIT_DIFF_CONTENT_TYPE
+from products.wizard.backend.facade.errors import (
+ WizardRunArtifactNotFoundError,
+ WizardRunArtifactTooLargeError,
+ WizardRunNotFoundError,
+)
+from products.wizard.backend.presentation.artifacts.pagination import WizardRunArtifactPagination
+from products.wizard.backend.presentation.artifacts.serializers import (
+ WizardRunArtifactSchema,
+ WizardRunArtifactSerializer,
+ serialize_wizard_run_artifact,
+)
+from products.wizard.backend.presentation.permissions import WizardRunSessionAuthenticationRequired
+from products.wizard.backend.presentation.runs.serializers import WizardRunErrorSerializer
+
+
+class WizardRunArtifactTooLarge(APIException):
+ status_code = 413
+ default_detail = "This diff is too large to download. Open the pull request to review the full change."
+ default_code = "wizard_run_artifact_too_large"
+
+
+class WizardRunArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ permission_classes = [WizardRunSessionAuthenticationRequired]
+ scope_object = "wizard_session"
+ scope_object_read_actions = ["list", "content"]
+ http_method_names = ["get", "head", "options"]
+ pagination_class = WizardRunArtifactPagination
+ serializer_class = WizardRunArtifactSerializer
+
+ @extend_schema(
+ responses={
+ 200: WizardRunArtifactSchema,
+ 404: OpenApiResponse(response=WizardRunErrorSerializer),
+ },
+ description="List metadata for artifacts produced by a Wizard run.",
+ )
+ # GET /projects/:projectId/wizard/runs/:runId/artifacts
+ def list(self, request: Request, *args: object, **kwargs: object) -> Response:
+ try:
+ artifacts = wizard_facade.list_run_artifacts(self.team_id, self._run_id())
+
+ except WizardRunNotFoundError:
+ raise NotFound("No Wizard run was found for this project.")
+
+ page = self.paginate_queryset(artifacts)
+
+ if page is None:
+ raise ValueError("Pagination returned None")
+
+ return self.get_paginated_response([serialize_wizard_run_artifact(artifact) for artifact in page])
+
+ @extend_schema(
+ operation_id="wizard_runs_artifacts_content_retrieve",
+ responses={
+ (200, "text/x-diff"): OpenApiTypes.STR,
+ 404: OpenApiResponse(response=WizardRunErrorSerializer),
+ 413: OpenApiResponse(response=WizardRunErrorSerializer),
+ },
+ description="Get the unified git diff stored for a Wizard run artifact.",
+ )
+ @action(detail=True, methods=["get"], pagination_class=None)
+ def content(self, request: Request, *args: object, **kwargs: object) -> HttpResponse:
+ try:
+ content = wizard_facade.get_git_diff_artifact_content(
+ self.team_id,
+ self._run_id(),
+ self._artifact_id(),
+ )
+ except (WizardRunArtifactNotFoundError, WizardRunNotFoundError):
+ raise NotFound("No git diff artifact was found for this Wizard run.")
+ except WizardRunArtifactTooLargeError:
+ raise WizardRunArtifactTooLarge from None
+
+ response = HttpResponse(content, content_type=WIZARD_GIT_DIFF_CONTENT_TYPE)
+ response["Cache-Control"] = "private, no-store"
+ response["X-Content-Type-Options"] = "nosniff"
+ return response
+
+ def _run_id(self) -> UUID:
+ return UUID(cast(str, self.kwargs["parent_lookup_run_id"]))
+
+ def _artifact_id(self) -> UUID:
+ return UUID(cast(str, self.kwargs["pk"]))
diff --git a/products/wizard/backend/presentation/permissions.py b/products/wizard/backend/presentation/permissions.py
new file mode 100644
index 000000000000..4f42dad9a3e1
--- /dev/null
+++ b/products/wizard/backend/presentation/permissions.py
@@ -0,0 +1,12 @@
+from rest_framework.permissions import BasePermission
+from rest_framework.request import Request
+from rest_framework.views import APIView
+
+from posthog.auth import SessionAuthentication
+
+
+class WizardRunSessionAuthenticationRequired(BasePermission):
+ message = "Sign in to use Wizard runs."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ return isinstance(request.successful_authenticator, SessionAuthentication)
diff --git a/products/wizard/backend/presentation/registry/__init__.py b/products/wizard/backend/presentation/registry/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/wizard/backend/presentation/registry/pagination.py b/products/wizard/backend/presentation/registry/pagination.py
new file mode 100644
index 000000000000..a8fd39b3fcc9
--- /dev/null
+++ b/products/wizard/backend/presentation/registry/pagination.py
@@ -0,0 +1,6 @@
+from rest_framework.pagination import LimitOffsetPagination
+
+
+class WizardRegistryPagination(LimitOffsetPagination):
+ default_limit = 100
+ max_limit = 100
diff --git a/products/wizard/backend/presentation/registry/serializers.py b/products/wizard/backend/presentation/registry/serializers.py
new file mode 100644
index 000000000000..720be89bb039
--- /dev/null
+++ b/products/wizard/backend/presentation/registry/serializers.py
@@ -0,0 +1,32 @@
+from rest_framework import serializers
+
+from products.wizard.backend.facade.enums import WizardRunEnvironment
+
+
+class WizardProgramSerializer(serializers.Serializer):
+ id = serializers.CharField(read_only=True, help_text="Stable identifier used to select the program.")
+ name = serializers.CharField(read_only=True, help_text="Display name of the program.")
+ description = serializers.CharField(read_only=True, help_text="What the program does.")
+ wizard_version = serializers.CharField(
+ read_only=True, help_text="Exact Wizard package version used by the program."
+ )
+ command = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text="Wizard CLI arguments used to start the program.",
+ )
+ tags = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text="Labels that categorize the program.",
+ )
+ required_programs = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text="Programs that should run before this program.",
+ )
+ supported_environments = serializers.ListField(
+ child=serializers.ChoiceField(choices=[environment.value for environment in WizardRunEnvironment]),
+ read_only=True,
+ help_text="Environments where the program can run.",
+ )
diff --git a/products/wizard/backend/presentation/registry/views.py b/products/wizard/backend/presentation/registry/views.py
new file mode 100644
index 000000000000..9c3a0b848c6c
--- /dev/null
+++ b/products/wizard/backend/presentation/registry/views.py
@@ -0,0 +1,38 @@
+from typing import cast
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import viewsets
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import User
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.presentation.permissions import WizardRunSessionAuthenticationRequired
+from products.wizard.backend.presentation.registry.pagination import WizardRegistryPagination
+from products.wizard.backend.presentation.registry.serializers import WizardProgramSerializer
+
+
+class WizardRegistryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ permission_classes = [WizardRunSessionAuthenticationRequired]
+ scope_object = "wizard_session"
+ scope_object_read_actions = ["list"]
+ http_method_names = ["get", "head", "options"]
+ pagination_class = WizardRegistryPagination
+
+ @extend_schema(
+ responses={200: WizardProgramSerializer(many=True)},
+ description="List Wizard programs available for this project.",
+ )
+ def list(self, request: Request, *args: object, **kwargs: object) -> Response:
+ # GET /projects/:projectId/wizard/registry
+ user = cast(User, request.user)
+ programs = wizard_facade.get_registry(
+ distinct_id=cast(str, user.distinct_id),
+ organization_id=str(self.team.organization_id),
+ )
+ page = self.paginate_queryset(programs)
+ if page is None:
+ raise ValueError("Pagination returned None")
+ return self.get_paginated_response(WizardProgramSerializer(page, many=True).data)
diff --git a/products/wizard/backend/presentation/runs/__init__.py b/products/wizard/backend/presentation/runs/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/products/wizard/backend/presentation/runs/__init__.py
@@ -0,0 +1 @@
+
diff --git a/products/wizard/backend/presentation/runs/errors.py b/products/wizard/backend/presentation/runs/errors.py
new file mode 100644
index 000000000000..d82025ca56ed
--- /dev/null
+++ b/products/wizard/backend/presentation/runs/errors.py
@@ -0,0 +1,77 @@
+from typing import Never
+
+from rest_framework.exceptions import APIException, Throttled, ValidationError
+
+from posthog.exceptions import Conflict
+
+from products.wizard.backend.facade.errors import (
+ ActiveWizardRunError,
+ InvalidRepositoryError,
+ InvalidWorkspaceEnvironmentError,
+ MissingGitHubIntegrationError,
+ RepositoryNotAccessibleError,
+ WizardProgramEnvironmentNotSupportedError,
+ WizardProgramNotAvailableError,
+ WizardRunDailyLimitError,
+ WizardRunHourlyLimitError,
+ WizardRunIdempotencyConflictError,
+)
+
+WizardRunCreationError = (
+ ActiveWizardRunError
+ | InvalidRepositoryError
+ | InvalidWorkspaceEnvironmentError
+ | MissingGitHubIntegrationError
+ | RepositoryNotAccessibleError
+ | WizardProgramEnvironmentNotSupportedError
+ | WizardProgramNotAvailableError
+ | WizardRunDailyLimitError
+ | WizardRunHourlyLimitError
+ | WizardRunIdempotencyConflictError
+)
+
+WIZARD_RUN_CREATION_ERRORS = (
+ ActiveWizardRunError,
+ InvalidRepositoryError,
+ InvalidWorkspaceEnvironmentError,
+ MissingGitHubIntegrationError,
+ RepositoryNotAccessibleError,
+ WizardProgramEnvironmentNotSupportedError,
+ WizardProgramNotAvailableError,
+ WizardRunDailyLimitError,
+ WizardRunHourlyLimitError,
+ WizardRunIdempotencyConflictError,
+)
+
+
+def run_creation_api_error(error: WizardRunCreationError) -> APIException:
+ match error:
+ case InvalidWorkspaceEnvironmentError():
+ return ValidationError({"detail": "Choose a workspace supported by this run environment."})
+ case InvalidRepositoryError():
+ return ValidationError({"detail": "Enter a repository in owner/name format."})
+ case WizardProgramNotAvailableError():
+ return ValidationError({"detail": "Choose an available Wizard program."})
+ case WizardProgramEnvironmentNotSupportedError():
+ return ValidationError({"detail": "Choose a Wizard program supported by this run environment."})
+ case WizardRunIdempotencyConflictError():
+ return Conflict(
+ "This idempotency key was already used for a different Wizard run.",
+ code="idempotency_conflict",
+ )
+ case ActiveWizardRunError():
+ return Throttled(
+ detail="A cloud Wizard run is already active. Wait for it to finish or cancel it before starting another."
+ )
+ case WizardRunHourlyLimitError():
+ return Throttled(detail="You've reached the hourly cloud run limit. Try again in an hour.")
+ case WizardRunDailyLimitError():
+ return Throttled(detail="You've reached the daily cloud run limit. Try again tomorrow.")
+ case MissingGitHubIntegrationError() | RepositoryNotAccessibleError():
+ return ValidationError({"detail": "Connect GitHub with access to this repository, then try again."})
+
+ _unexpected_run_creation_error(error)
+
+
+def _unexpected_run_creation_error(error: Never) -> Never:
+ raise AssertionError(f"Unexpected Wizard run creation error: {error!r}")
diff --git a/products/wizard/backend/presentation/runs/pagination.py b/products/wizard/backend/presentation/runs/pagination.py
new file mode 100644
index 000000000000..2c206820737e
--- /dev/null
+++ b/products/wizard/backend/presentation/runs/pagination.py
@@ -0,0 +1,23 @@
+from rest_framework.pagination import LimitOffsetPagination
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import ListWizardRunsInput
+from products.wizard.backend.presentation.runs.serializers import WizardRunSerializer
+
+
+class WizardRunPagination(LimitOffsetPagination):
+ default_limit = 100
+ max_limit = 100
+
+ def paginate_runs(self, request: Request, *, team_id: int) -> Response:
+ limit = self.get_limit(request)
+ assert limit is not None
+ offset = self.get_offset(request)
+ page = wizard_facade.list_runs(ListWizardRunsInput(team_id=team_id, offset=offset, limit=limit))
+ self.request = request
+ self.limit = limit
+ self.offset = offset
+ self.count = page.count
+ return self.get_paginated_response(WizardRunSerializer(page.results, many=True).data)
diff --git a/products/wizard/backend/presentation/runs/serializers.py b/products/wizard/backend/presentation/runs/serializers.py
new file mode 100644
index 000000000000..6ac306c590f0
--- /dev/null
+++ b/products/wizard/backend/presentation/runs/serializers.py
@@ -0,0 +1,261 @@
+from collections.abc import Mapping
+from typing import cast
+
+from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
+from rest_framework import serializers
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import (
+ CreateWizardRunInput,
+ GitRepositoryWorkspace,
+ LocalFolderWorkspace,
+ WizardWorkspace,
+)
+from products.wizard.backend.facade.enums import (
+ WizardRunEnvironment,
+ WizardRunErrorCode,
+ WizardRunStage,
+ WizardRunStatus,
+ WizardWorkspaceType,
+)
+from products.wizard.backend.facade.errors import InvalidRepositoryError
+from products.wizard.backend.facade.validation import is_wizard_error_code
+from products.wizard.backend.presentation.registry.serializers import WizardProgramSerializer
+
+
+class WizardWorkspaceTypeField(serializers.CharField):
+ workspace_type: WizardWorkspaceType
+
+ def to_internal_value(self, data: object) -> str:
+ value = super().to_internal_value(cast(str, data))
+ if value != self.workspace_type.value:
+ self.fail("invalid")
+ return value
+
+
+@extend_schema_field({"type": "string", "const": WizardWorkspaceType.LOCAL_FOLDER.value})
+class LocalFolderWorkspaceTypeField(WizardWorkspaceTypeField):
+ workspace_type = WizardWorkspaceType.LOCAL_FOLDER
+
+
+@extend_schema_field({"type": "string", "const": WizardWorkspaceType.GIT_REPOSITORY.value})
+class GitRepositoryWorkspaceTypeField(WizardWorkspaceTypeField):
+ workspace_type = WizardWorkspaceType.GIT_REPOSITORY
+
+
+class LocalFolderWorkspaceSerializer(serializers.Serializer):
+ type = LocalFolderWorkspaceTypeField(
+ help_text="Selects a folder on the user's machine as the workspace.",
+ )
+ project_name = serializers.CharField(
+ allow_blank=False,
+ max_length=255,
+ help_text="Name of the project in the local folder.",
+ )
+
+
+class GitRepositoryWorkspaceSerializer(serializers.Serializer):
+ type = GitRepositoryWorkspaceTypeField(
+ help_text="Selects a GitHub repository as the workspace.",
+ )
+ repository = serializers.CharField(
+ allow_blank=False,
+ max_length=255,
+ help_text="GitHub repository in owner/name format.",
+ )
+
+ def validate_repository(self, value: str) -> str:
+ repository = value.strip()
+ try:
+ wizard_facade.validate_git_repository(repository)
+ except InvalidRepositoryError:
+ raise serializers.ValidationError("Enter a repository in owner/name format.")
+ return repository
+
+
+WizardWorkspaceSchema = PolymorphicProxySerializer(
+ component_name="WizardWorkspace",
+ serializers={
+ WizardWorkspaceType.LOCAL_FOLDER.value: LocalFolderWorkspaceSerializer,
+ WizardWorkspaceType.GIT_REPOSITORY.value: GitRepositoryWorkspaceSerializer,
+ },
+ resource_type_field_name="type",
+)
+
+
+@extend_schema_field(WizardWorkspaceSchema)
+class WizardWorkspaceField(serializers.Field):
+ def to_internal_value(self, data: object) -> WizardWorkspace:
+ if not isinstance(data, Mapping):
+ raise serializers.ValidationError("Enter a workspace object.")
+
+ workspace_data = cast(Mapping[str, object], data)
+ workspace_type = workspace_data.get("type")
+ if workspace_type == WizardWorkspaceType.LOCAL_FOLDER.value:
+ local_serializer = LocalFolderWorkspaceSerializer(data=workspace_data)
+ local_serializer.is_valid(raise_exception=True)
+ return LocalFolderWorkspace(project_name=cast(str, local_serializer.validated_data["project_name"]))
+ if workspace_type == WizardWorkspaceType.GIT_REPOSITORY.value:
+ repository_serializer = GitRepositoryWorkspaceSerializer(data=workspace_data)
+ repository_serializer.is_valid(raise_exception=True)
+ return GitRepositoryWorkspace(repository=cast(str, repository_serializer.validated_data["repository"]))
+ if "type" not in workspace_data:
+ raise serializers.ValidationError({"type": ["This field is required."]})
+ raise serializers.ValidationError({"type": ["Select a valid workspace type."]})
+
+ def to_representation(self, value: WizardWorkspace) -> dict[str, object]:
+ if isinstance(value, LocalFolderWorkspace):
+ return cast(dict[str, object], LocalFolderWorkspaceSerializer(value).data)
+ if isinstance(value, GitRepositoryWorkspace):
+ return cast(dict[str, object], GitRepositoryWorkspaceSerializer(value).data)
+ raise TypeError("Unsupported Wizard workspace")
+
+
+class WizardRunCreateRequestSerializer(serializers.Serializer):
+ program_id = serializers.RegexField(
+ regex=r"^[a-z0-9]+(?:-[a-z0-9]+)*$",
+ help_text="Registry program to run.",
+ )
+ environment = serializers.ChoiceField(
+ choices=[environment.value for environment in WizardRunEnvironment],
+ help_text="Where the setup agent runs.",
+ )
+ workspace = WizardWorkspaceField(
+ help_text="Project that the setup agent works on.",
+ )
+ idempotency_key = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ max_length=255,
+ help_text="Unique key that makes cloud run creation safe to retry.",
+ )
+ wizard_version = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ help_text="Wizard package version to run. Defaults to the backend pin and accepts latest explicitly.",
+ )
+
+ def validate_wizard_version(self, value: str) -> str:
+ try:
+ return wizard_facade.validate_wizard_version(value)
+ except ValueError:
+ raise serializers.ValidationError("Enter an exact semantic version or latest.")
+
+ def validate(self, attrs: dict[str, object]) -> dict[str, object]:
+ if attrs.get("environment") == WizardRunEnvironment.CLOUD.value and not attrs.get("idempotency_key"):
+ raise serializers.ValidationError({"idempotency_key": "This field is required for cloud runs."})
+ return attrs
+
+ def to_contract(self, *, team_id: int, created_by_id: int) -> CreateWizardRunInput:
+ return CreateWizardRunInput(
+ team_id=team_id,
+ created_by_id=created_by_id,
+ environment=WizardRunEnvironment(cast(str, self.validated_data["environment"])),
+ workspace=cast(WizardWorkspace, self.validated_data["workspace"]),
+ program_id=cast(str, self.validated_data["program_id"]),
+ wizard_version=cast(str | None, self.validated_data.get("wizard_version")),
+ idempotency_key=cast(str | None, self.validated_data.get("idempotency_key")),
+ )
+
+
+class WizardRunStatusUpdateRequestSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=[
+ WizardRunStatus.COMPLETED.value,
+ WizardRunStatus.FAILED.value,
+ WizardRunStatus.CANCELLED.value,
+ ],
+ help_text="New terminal status for the Wizard run.",
+ )
+ error_code = serializers.CharField(
+ required=False,
+ allow_null=True,
+ max_length=50,
+ help_text="Machine-readable reason the Wizard run failed.",
+ )
+
+ def validate_error_code(self, value: str | None) -> str | None:
+ if value is None or is_wizard_error_code(value):
+ return value
+ try:
+ WizardRunErrorCode(value)
+ except ValueError as error:
+ raise serializers.ValidationError("Enter a valid Wizard run error code.") from error
+ return value
+
+ def validate(self, attrs: dict[str, object]) -> dict[str, object]:
+ if attrs.get("error_code") is not None and attrs["status"] != WizardRunStatus.FAILED.value:
+ raise serializers.ValidationError({"error_code": "Only failed runs can have an error code."})
+ return attrs
+
+ def to_status(self) -> WizardRunStatus:
+ return WizardRunStatus(cast(str, self.validated_data["status"]))
+
+ def to_error_code(self) -> str | None:
+ return cast(str | None, self.validated_data.get("error_code"))
+
+
+class WizardRunSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique ID of the Wizard run.")
+ team_id = serializers.IntegerField(read_only=True, help_text="Project that owns the Wizard run.")
+ created_by_id = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="User who created the Wizard run, or null if that user no longer exists.",
+ )
+ environment = serializers.ChoiceField(
+ read_only=True,
+ choices=[environment.value for environment in WizardRunEnvironment],
+ help_text="Where the setup agent runs.",
+ )
+ workspace = WizardWorkspaceField(read_only=True, help_text="Project that the setup agent works on.")
+ program = WizardProgramSerializer(read_only=True, help_text="Registry program selected for this run.")
+ status = serializers.ChoiceField(
+ read_only=True,
+ choices=[run_status.value for run_status in WizardRunStatus],
+ help_text="Current lifecycle status of the Wizard run.",
+ )
+ error_code = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Machine-readable failure reason, or null if the run has not failed.",
+ )
+ error_message = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Safe failure explanation, or null if the run has not failed.",
+ )
+ stage = serializers.ChoiceField(
+ read_only=True,
+ allow_null=True,
+ choices=[stage.value for stage in WizardRunStage],
+ help_text="Current cloud worker stage, or null outside active cloud execution.",
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the Wizard run was created.")
+ updated_at = serializers.DateTimeField(read_only=True, allow_null=True, help_text="When the run last changed.")
+ started_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="When execution started, or null while queued.",
+ )
+ finished_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="When execution reached a terminal status, or null while active.",
+ )
+ deadline_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="Cloud execution deadline, or null for local runs.",
+ )
+
+
+class WizardRunErrorSerializer(serializers.Serializer):
+ type = serializers.CharField(read_only=True, help_text="Error category.")
+ code = serializers.CharField(read_only=True, help_text="Machine-readable error code.")
+ detail = serializers.CharField(read_only=True, help_text="What happened and how to continue.")
+ attr = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Request field associated with the error, when available.",
+ )
diff --git a/products/wizard/backend/presentation/runs/views.py b/products/wizard/backend/presentation/runs/views.py
new file mode 100644
index 000000000000..00f6adbd2629
--- /dev/null
+++ b/products/wizard/backend/presentation/runs/views.py
@@ -0,0 +1,169 @@
+from typing import cast
+from uuid import UUID
+
+from django.conf import settings
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import status, viewsets
+from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import SessionAuthentication
+from posthog.exceptions import Conflict
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import WizardRunDTO
+from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStatus
+from products.wizard.backend.facade.errors import IllegalStatusTransitionError, WizardRunNotFoundError
+from products.wizard.backend.presentation.permissions import WizardRunSessionAuthenticationRequired
+from products.wizard.backend.presentation.runs.errors import (
+ WIZARD_RUN_CREATION_ERRORS,
+ WizardRunCreationError,
+ run_creation_api_error,
+)
+from products.wizard.backend.presentation.runs.pagination import WizardRunPagination
+from products.wizard.backend.presentation.runs.serializers import (
+ WizardRunCreateRequestSerializer,
+ WizardRunErrorSerializer,
+ WizardRunSerializer,
+ WizardRunStatusUpdateRequestSerializer,
+)
+from products.wizard.backend.presentation.throttles import WizardRunCreateThrottle, WizardRunReadThrottle
+
+
+class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ permission_classes = [WizardRunSessionAuthenticationRequired]
+ scope_object = "wizard_session"
+ scope_object_read_actions = ["list", "retrieve"]
+ scope_object_write_actions = ["create", "partial_update"]
+ http_method_names = ["get", "post", "patch", "head", "options"]
+ lookup_field = "run_id"
+ lookup_value_regex = "[0-9a-fA-F-]{36}"
+ pagination_class = WizardRunPagination
+
+ def get_throttles(self) -> list:
+ if self.action == "create":
+ return [WizardRunCreateThrottle()]
+ return [WizardRunReadThrottle()]
+
+ @extend_schema(
+ responses={200: WizardRunSerializer(many=True)},
+ description="List Wizard runs for this project, ordered from newest to oldest.",
+ )
+ def list(self, request: Request, *args: object, **kwargs: object) -> Response:
+ # GET /projects/:projectId/wizard/runs
+ paginator = cast(WizardRunPagination, self.paginator)
+ return paginator.paginate_runs(request, team_id=self.team_id)
+
+ @extend_schema(
+ request=WizardRunCreateRequestSerializer,
+ responses={
+ 201: WizardRunSerializer,
+ 400: OpenApiResponse(response=WizardRunErrorSerializer),
+ 403: OpenApiResponse(response=WizardRunErrorSerializer),
+ 404: OpenApiResponse(response=WizardRunErrorSerializer),
+ 429: OpenApiResponse(response=WizardRunErrorSerializer),
+ },
+ description="Create a local or cloud Wizard run for a project workspace.",
+ )
+ def create(self, request: Request, *args: object, **kwargs: object) -> Response:
+ # POST /projects/:projectId/wizard/runs
+ serializer = WizardRunCreateRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ params = serializer.to_contract(team_id=self.team_id, created_by_id=cast(int, request.user.id))
+ if params.environment == WizardRunEnvironment.CLOUD:
+ self._validate_cloud_creation(request)
+ try:
+ result = wizard_facade.create_run_with_result(params)
+ except WIZARD_RUN_CREATION_ERRORS as error:
+ raise run_creation_api_error(cast(WizardRunCreationError, error))
+
+ response_status = status.HTTP_201_CREATED if result.created else status.HTTP_200_OK
+
+ return Response(WizardRunSerializer(result.run).data, status=response_status)
+
+ @staticmethod
+ def _validate_cloud_creation(request: Request) -> None:
+ if not settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID:
+ raise NotFound("Running the Wizard in the cloud is not available.")
+ if not isinstance(request.successful_authenticator, SessionAuthentication):
+ raise PermissionDenied("Sign in to start a cloud Wizard run.")
+
+ @extend_schema(
+ responses={
+ 200: WizardRunSerializer,
+ 404: OpenApiResponse(response=WizardRunErrorSerializer),
+ },
+ description="Retrieve a Wizard run in this project.",
+ )
+ # GET /projects/:projectId/wizard/runs/:runId
+ def retrieve(self, request: Request, *args: object, **kwargs: object) -> Response:
+ run = self._get_run()
+ return Response(WizardRunSerializer(run).data)
+
+ @extend_schema(
+ request=WizardRunStatusUpdateRequestSerializer,
+ responses={
+ 200: WizardRunSerializer,
+ 400: OpenApiResponse(response=WizardRunErrorSerializer),
+ 403: OpenApiResponse(response=WizardRunErrorSerializer),
+ 404: OpenApiResponse(response=WizardRunErrorSerializer),
+ 409: OpenApiResponse(response=WizardRunErrorSerializer),
+ },
+ description="Change the terminal status of a local Wizard run.",
+ )
+ # PATCH /projects/:projectId/wizard/runs/:runId
+ def partial_update(self, request: Request, *args: object, **kwargs: object) -> Response:
+ serializer = WizardRunStatusUpdateRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ next_status = serializer.to_status()
+
+ try:
+ current = self._get_owned_run()
+
+ if current.environment == WizardRunEnvironment.CLOUD:
+ if next_status != WizardRunStatus.CANCELLED:
+ raise Conflict(
+ "Only cancellation can be requested for a cloud Wizard run.", code="cloud_run_managed"
+ )
+
+ run = wizard_facade.cancel_run(self.team_id, current.id)
+
+ elif next_status == WizardRunStatus.CANCELLED:
+ run = wizard_facade.cancel_run(self.team_id, current.id)
+
+ else:
+ # todo: once we have the state sync system, all transitions should be handled by it
+ run = wizard_facade.update_run_status(
+ self.team_id,
+ current.id,
+ next_status,
+ error_code=serializer.to_error_code(),
+ )
+
+ except IllegalStatusTransitionError:
+ raise Conflict(
+ f"This Wizard run cannot be {next_status.value} from its current status.",
+ code="invalid_transition",
+ )
+
+ return Response(WizardRunSerializer(run).data)
+
+ def _get_run(self) -> WizardRunDTO:
+ try:
+ return wizard_facade.get_run(self.team_id, self._run_id())
+ except WizardRunNotFoundError:
+ raise NotFound("No Wizard run was found for this project.")
+
+ def _run_id(self) -> UUID:
+ return UUID(cast(str, self.kwargs["run_id"]))
+
+ def _get_owned_run(self) -> WizardRunDTO:
+ run = self._get_run()
+
+ if run.created_by_id != self.request.user.id:
+ raise PermissionDenied("Only the user who started this Wizard run can update it.")
+
+ return run
diff --git a/products/wizard/backend/presentation/serializers.py b/products/wizard/backend/presentation/serializers.py
deleted file mode 100644
index d25752940b6b..000000000000
--- a/products/wizard/backend/presentation/serializers.py
+++ /dev/null
@@ -1,145 +0,0 @@
-"""DRF serializers for wizard. Bound to facade DTOs, not Django models."""
-
-from typing import Any
-
-from rest_framework import serializers
-from rest_framework_dataclasses.serializers import DataclassSerializer
-
-from products.wizard.backend.facade.contracts import UpsertWizardSessionRequest, WizardSessionDTO
-
-# Bounds on the pending question. A prompt is a terminal question, not a document, and the wizard
-# asks one thing at a time; the caps keep a malformed or hostile push from growing the row that the
-# app-wide widget reads on every page load.
-MAX_PROMPT_LENGTH = 2000
-MAX_PROMPTS = 10
-
-# Bound on the handoff doc. It IS a document (the wizard's setup report, a few KB of markdown in
-# practice), but the row is streamed over SSE and republished on every later upsert, so cap it well
-# below anything a hostile push could use to balloon the channel. The CLI truncates to the same cap.
-MAX_HANDOFF_TEXT_LENGTH = 64 * 1024
-
-
-class PendingInputSerializer(serializers.Serializer):
- """The in-flight `wizard_ask` question. Typed rather than a free-form dict so the shape the
- widget renders is enforced at the edge instead of trusted from the producer."""
-
- id = serializers.CharField(
- max_length=255,
- help_text="Identifier the wizard mints for this question. Changes when a new question is asked.",
- )
- asked_at = serializers.DateTimeField(
- required=False,
- help_text="UTC timestamp when the wizard asked. Defaults to the session's update time when absent.",
- )
- question_count = serializers.IntegerField(
- required=False,
- min_value=1,
- max_value=100,
- help_text="How many questions this single ask covers.",
- )
- sensitive = serializers.BooleanField(
- required=False,
- default=False,
- help_text="Whether the answer is a secret. Sensitive questions never carry prompt text.",
- )
- prompts = serializers.ListField(
- required=False,
- max_length=MAX_PROMPTS,
- child=serializers.CharField(max_length=MAX_PROMPT_LENGTH, allow_blank=True),
- help_text="The question text shown to the user. Always empty for sensitive questions.",
- )
-
- def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
- # Redact here rather than in the client: the sensitive contract has to hold for every
- # producer, and past this point the value is persisted, streamed over SSE, and logged.
- if attrs.get("sensitive"):
- attrs.pop("prompts", None)
- asked_at = attrs.get("asked_at")
- if asked_at is not None:
- # The field is a JSONField on the model, which can't hold a datetime.
- attrs["asked_at"] = asked_at.isoformat()
- return attrs
-
-
-class WizardSessionSerializer(DataclassSerializer):
- """Output: serialises a WizardSessionDTO returned by the facade."""
-
- pending_input = PendingInputSerializer(
- allow_null=True,
- help_text="The question the wizard is currently blocked on, or null when nothing is pending.",
- )
-
- class Meta:
- dataclass = WizardSessionDTO
- extra_kwargs = {
- "created_by": {
- "help_text": (
- "The user who initiated this wizard run (null for runs created before "
- "attribution existed). Lets the UI name whose run it is."
- ),
- },
- "handoff_text": {
- "help_text": (
- "Markdown handoff doc the wizard produced for this run (its setup report), "
- "or null while the run hasn't written one. Sticky once set."
- ),
- },
- }
-
-
-class UpsertWizardSessionRequestSerializer(DataclassSerializer):
- """Input: validates the JSON the wizard CLI posts. team_id is derived from URL."""
-
- pending_input = PendingInputSerializer(
- required=False,
- allow_null=True,
- help_text=(
- "Populated while the wizard is blocked on a question in the terminal. "
- "Null/absent means no input is pending; a push without it clears the previous prompt."
- ),
- )
- # trim_whitespace would mangle markdown that opens with indentation (e.g. a code block).
- handoff_text = serializers.CharField(
- required=False,
- allow_null=True,
- allow_blank=True,
- trim_whitespace=False,
- max_length=MAX_HANDOFF_TEXT_LENGTH,
- help_text=(
- "Markdown handoff doc for the run (the wizard's setup report). Send it once the run "
- "has produced one; omitting it on later pushes keeps the stored value."
- ),
- )
-
- 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/throttles.py b/products/wizard/backend/presentation/throttles.py
new file mode 100644
index 000000000000..1a93f435673f
--- /dev/null
+++ b/products/wizard/backend/presentation/throttles.py
@@ -0,0 +1,17 @@
+from django.conf import settings
+
+from rest_framework.throttling import UserRateThrottle
+
+
+class WizardRunReadThrottle(UserRateThrottle):
+ scope = "wizard_run_read"
+
+ def get_rate(self) -> str:
+ return settings.WIZARD_RUN_READ_THROTTLE_RATE
+
+
+class WizardRunCreateThrottle(UserRateThrottle):
+ scope = "wizard_run_create"
+
+ def get_rate(self) -> str:
+ return settings.WIZARD_RUN_CREATE_THROTTLE_RATE
diff --git a/products/wizard/backend/presentation/utils.py b/products/wizard/backend/presentation/utils.py
deleted file mode 100644
index bde9a22d8b52..000000000000
--- a/products/wizard/backend/presentation/utils.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""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, limit
diff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.py
deleted file mode 100644
index 6def87bdd993..000000000000
--- a/products/wizard/backend/presentation/views.py
+++ /dev/null
@@ -1,420 +0,0 @@
-"""
-DRF views for wizard.
-
-Validates JSON via serializers, routes everything through the facade,
-returns DTO-shaped responses. No model imports.
-"""
-
-import time
-from collections.abc import AsyncIterator, Mapping
-from typing import Any
-
-from django.conf import settings
-from django.http import HttpResponse
-from django.http.response import HttpResponseBase
-
-import structlog
-import posthoganalytics
-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
-from rest_framework import status, viewsets
-from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
-from rest_framework.renderers import BaseRenderer
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.streaming import sse_streaming_response
-from posthog.models.scoping import team_scope
-from posthog.sync import database_sync_to_async
-
-from products.wizard.backend.facade import api as wizard_facade
-from products.wizard.backend.facade.contracts import (
- UpsertWizardSessionInput,
- UpsertWizardSessionRequest,
- WizardSessionDTO,
- WizardSessionOwnershipError,
-)
-from products.wizard.backend.facade.enums import RunPhase
-from products.wizard.backend.presentation.serializers import (
- UpsertWizardSessionRequestSerializer,
- WizardSessionSerializer,
-)
-from products.wizard.backend.presentation.utils import pagination_window
-
-logger = structlog.get_logger(__name__)
-
-
-class EventStreamRenderer(BaseRenderer):
- """Satisfies DRF content negotiation for `Accept: text/event-stream`; never actually invoked."""
-
- media_type = "text/event-stream"
- format = "event-stream"
- charset = "utf-8"
-
- def render(self, data: Any, accepted_media_type: str | None = None, renderer_context: Any = None) -> bytes:
- return data if isinstance(data, bytes) else b""
-
-
-def _log_request_auth(request: Request, *, action: str, team_id: int | None) -> None:
- 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,
- )
-
-
-SSE_HEARTBEAT_INTERVAL_SECONDS = 15.0
-SSE_POLL_TIMEOUT_SECONDS = 1.0
-# Long-lived connections pin worker processes during recycle-drain; the
-# `event: end` close makes EventSource reconnect, so the cap is near-invisible to
-# users (the progress tracker may show a brief "reconnecting" blip per rotation).
-SSE_MAX_DURATION_SECONDS = 15 * 60
-
-WIZARD_SYNC_KILLSWITCH_FLAG = "onboarding-wizard-sync-killswitch"
-
-
-def _wizard_sync_killswitch_enabled(distinct_id: str) -> bool:
- # Local-only eval: no per-request network/decide call on this hot endpoint.
- # Flag definitions are served via HyperCache (posthog/apps.py). Fail-open:
- # if the flag can't be evaluated locally, the stream behaves normally.
- return bool(
- posthoganalytics.feature_enabled(
- WIZARD_SYNC_KILLSWITCH_FLAG,
- distinct_id,
- only_evaluate_locally=True,
- send_feature_flag_events=False,
- )
- )
-
-
-class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
- scope_object = "wizard_session"
- scope_object_read_actions = ["list", "retrieve", "stream", "latest"]
- scope_object_write_actions = ["create"]
- http_method_names = ["get", "post", "head", "options"]
- lookup_field = "session_id"
- # Negative lookahead so a session_id of `stream` or `latest` can't collide
- # with the `@action(url_path=...)` detail-vs-action routes.
- lookup_value_regex = r"(?!(?:stream|latest)$)[^/]+"
-
- def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
- if (
- self.action == "create"
- and isinstance(request.data, Mapping)
- and request.data.get("run_phase") == RunPhase.COMPLETED.value
- ):
- return ["wizard_session:write", "event_definition:write"]
- return None
-
- def check_permissions(self, request: Request) -> None:
- 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") or None,
- offset=page_offset,
- limit=page_limit,
- )
- 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)
-
- def _killswitch_active(self, request: Request) -> bool:
- # Shared by `latest` and `stream` so flipping the incident flag quiets both the
- # SSE stream and the 60s REST poll — otherwise the fleet keeps hitting `latest`.
- user = getattr(request, "user", None)
- distinct_id = (
- str(user.distinct_id)
- if user is not None and not user.is_anonymous and getattr(user, "distinct_id", None)
- else f"team:{self.team_id}"
- )
- return _wizard_sync_killswitch_enabled(distinct_id)
-
- @extend_schema(
- description=(
- "Return the single most-recent wizard session for a workflow (and "
- "optional skill), or 204 if none exists. Unlike `list`, this is a "
- "point lookup the app shell uses to decide whether to open the live "
- "SSE stream — it never returns a collection, and 'no run' is a 204 "
- "rather than a 404 so clients don't conflate it with a missing "
- "endpoint."
- ),
- parameters=[
- OpenApiParameter(
- name="workflow_id",
- required=True,
- type=str,
- location=OpenApiParameter.QUERY,
- description="Filter to a single workflow (e.g. 'posthog-integration').",
- ),
- 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,
- 204: OpenApiResponse(description="No session for this workflow/skill in this project."),
- },
- )
- @action(detail=False, methods=["get"], url_path="latest")
- def latest(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- # Killswitch parity with `stream`: a 204 makes the client treat this as "no run"
- # and wind the detector down, so flipping the flag in an incident also stops the
- # 60s poll (and skips the DB read entirely), not just the SSE stream.
- poll_source = request.headers.get("X-Wizard-Poll-Source")
- if self._killswitch_active(request):
- wizard_facade.record_latest_session_poll(poll_source, "killswitch")
- return Response(status=status.HTTP_204_NO_CONTENT)
- workflow_id = request.query_params.get("workflow_id")
- if not workflow_id:
- raise ValidationError({"detail": "workflow_id is required."})
- skill_id = request.query_params.get("skill_id") or None
- dto = wizard_facade.get_latest(self.team_id, workflow_id, skill_id)
- if dto is None:
- wizard_facade.record_latest_session_poll(poll_source, "empty")
- return Response(status=status.HTTP_204_NO_CONTENT)
- wizard_facade.record_latest_session_poll(poll_source, "hit")
- 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,
- 403: OpenApiResponse(description="The session belongs to a different user."),
- },
- )
- 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()
-
- user = getattr(request, "user", None)
- created_by_id = user.id if user is not None and not user.is_anonymous else None
-
- try:
- 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,
- pending_input=req.pending_input,
- handoff_text=req.handoff_text,
- created_by_id=created_by_id,
- )
- )
- except WizardSessionOwnershipError:
- raise PermissionDenied("This wizard session belongs to a different user.")
- response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OK
- return Response(WizardSessionSerializer(dto).data, status=response_status)
-
- @extend_schema(
- description=(
- "Server-Sent Events stream of wizard session updates for a "
- "(workflow_id, skill_id) pair. On connect, the current latest "
- "session (if any) is emitted as the first event; subsequent "
- "upserts are streamed in real time. The server closes the "
- f"connection after {SSE_MAX_DURATION_SECONDS} seconds with an "
- "`event: end` line so the client (EventSource) can reconnect.\n\n"
- "**SDK consumers**: do not call the generated fetch wrapper for "
- "this path — it will buffer the entire infinite stream. Use the "
- "URL builder (`getWizardSessionsStreamRetrieveUrl`) with the "
- "browser's `EventSource` API instead."
- ),
- parameters=[
- OpenApiParameter(
- name="workflow_id",
- required=True,
- type=str,
- location=OpenApiParameter.QUERY,
- ),
- OpenApiParameter(
- name="skill_id",
- required=False,
- type=str,
- location=OpenApiParameter.QUERY,
- ),
- ],
- responses={
- (200, "text/event-stream"): {
- "type": "string",
- "description": "SSE stream of WizardSession events.",
- }
- },
- )
- @action(detail=False, methods=["get"], url_path="stream", renderer_classes=[EventStreamRenderer])
- def stream(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponseBase:
- # Killswitch first, before any other work: a 204 tells EventSource to stop
- # reconnecting, severing the self-reconnect loop for already-open tabs.
- if self._killswitch_active(request):
- return HttpResponse(status=204)
-
- workflow_id = request.query_params.get("workflow_id")
- skill_id = request.query_params.get("skill_id") or None
- if not workflow_id:
- raise ValidationError({"detail": "workflow_id is required."})
-
- # The generator is `async def` — WSGI can't consume an async iterator.
- if getattr(settings, "SERVER_GATEWAY_INTERFACE", "ASGI") != "ASGI":
- raise RuntimeError("wizard_sessions.stream requires ASGI.")
-
- generator = _wizard_session_event_stream(
- team_id=self.team_id,
- workflow_id=workflow_id,
- skill_id=skill_id,
- request=request,
- )
- # Releases the request-thread DB connection (auth, team resolution) before
- # the long-lived stream begins — see sse_streaming_response.
- return sse_streaming_response(generator, endpoint="wizard_session")
-
-
-async def _wizard_session_event_stream(
- team_id: int,
- workflow_id: str,
- skill_id: str | None,
- request: Request | None = None,
-) -> AsyncIterator[bytes]:
- """Stream SSE bytes for a wizard session subscription.
-
- Subscribes first, then fetches initial state, so publishes that race the
- snapshot are buffered on the pubsub socket and drained on the next tick.
- """
- started_at = time.monotonic()
-
- async with wizard_facade.subscribe_to_updates(team_id, workflow_id, skill_id) as pubsub:
-
- def _get_initial() -> WizardSessionDTO | None:
- with team_scope(team_id):
- return wizard_facade.get_latest(team_id, workflow_id, skill_id)
-
- # database_sync_to_async releases the DB connection after the read so it
- # isn't pinned for the whole SSE stream (CONN_MAX_AGE=0; loop is Redis-only).
- latest = await database_sync_to_async(_get_initial, thread_sensitive=False)()
- if latest is not None:
- yield b"data: " + wizard_facade.serialize_dto(latest) + b"\n\n"
-
- last_heartbeat = time.monotonic()
- while True:
- if time.monotonic() - started_at >= SSE_MAX_DURATION_SECONDS:
- yield b"event: end\ndata: reconnect\n\n"
- return
-
- if request is not None:
- is_disconnected = getattr(request, "is_disconnected", None)
- if is_disconnected is not None:
- try:
- if await is_disconnected():
- return
- except Exception:
- pass
-
- message = await pubsub.get_message(timeout=SSE_POLL_TIMEOUT_SECONDS)
- now = time.monotonic()
-
- # `pmessage` arrives via pattern subscribe; `message` via exact.
- if message and message.get("type") in ("message", "pmessage"):
- yield b"data: " + message["data"] + b"\n\n"
- last_heartbeat = now
- continue
-
- if now - last_heartbeat >= SSE_HEARTBEAT_INTERVAL_SECONDS:
- yield b": ping\n\n"
- last_heartbeat = now
diff --git a/products/wizard/backend/routes.py b/products/wizard/backend/routes.py
index fadf261d7885..3136ea64a0f3 100644
--- a/products/wizard/backend/routes.py
+++ b/products/wizard/backend/routes.py
@@ -1,7 +1,20 @@
from posthog.api.routing import RouterRegistry
-from products.wizard.backend.presentation.views import WizardSessionViewSet
+from products.wizard.backend.presentation.artifacts.views import WizardRunArtifactViewSet
+from products.wizard.backend.presentation.registry.views import WizardRegistryViewSet
+from products.wizard.backend.presentation.runs.views import WizardRunViewSet
+from products.wizard.backend.presentation.sessions.views import WizardSessionViewSet
def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(r"wizard/sessions", WizardSessionViewSet, "project_wizard_sessions", ["project_id"])
+ wizard_runs_router = routers.projects.register(
+ r"wizard/runs", WizardRunViewSet, "project_wizard_runs", ["project_id"]
+ )
+ wizard_runs_router.register(
+ r"artifacts",
+ WizardRunArtifactViewSet,
+ "project_wizard_run_artifacts",
+ ["project_id", "run_id"],
+ )
+ routers.projects.register(r"wizard/registry", WizardRegistryViewSet, "project_wizard_registry", ["project_id"])
diff --git a/products/wizard/backend/tasks/__init__.py b/products/wizard/backend/tasks/__init__.py
index 385a5c3da34b..aaaf40b1e5ba 100644
--- a/products/wizard/backend/tasks/__init__.py
+++ b/products/wizard/backend/tasks/__init__.py
@@ -1,5 +1,7 @@
+from products.wizard.backend.tasks.reconciliation import reconcile_wizard_runs
from products.wizard.backend.tasks.tasks import sync_wizard_event_definitions
__all__ = [
+ "reconcile_wizard_runs",
"sync_wizard_event_definitions",
]
diff --git a/products/wizard/backend/tasks/reconciliation.py b/products/wizard/backend/tasks/reconciliation.py
new file mode 100644
index 000000000000..a2d2c8e2561f
--- /dev/null
+++ b/products/wizard/backend/tasks/reconciliation.py
@@ -0,0 +1,59 @@
+import logging
+from time import monotonic
+
+from celery import shared_task
+from prometheus_client import Gauge
+
+from posthog.celery_queues import CeleryQueue
+from posthog.tasks.utils import PushGatewayTask
+
+from products.wizard.backend.logic.reconciliation import service as reconciliation
+from products.wizard.backend.tasks.config import RECONCILE_WIZARD_RUNS_TASK
+
+logger = logging.getLogger(__name__)
+
+
+@shared_task(
+ bind=True,
+ base=PushGatewayTask,
+ ignore_result=True,
+ name=RECONCILE_WIZARD_RUNS_TASK,
+ queue=CeleryQueue.DEFAULT.value,
+)
+def reconcile_wizard_runs(self: PushGatewayTask) -> None:
+ started_at = monotonic()
+
+ results = {
+ "dispatch": reconciliation.reconcile_pending_dispatches(),
+ "cancellation": reconciliation.reconcile_pending_cancellations(),
+ "expiration": reconciliation.reconcile_expired_runs(),
+ "cleanup": reconciliation.reconcile_pending_worker_cleanup(),
+ }
+
+ logger.info(
+ "wizard_run_reconciliation_completed",
+ extra={
+ "duration_seconds": round(monotonic() - started_at, 3),
+ "operations": {
+ operation: {
+ "scanned": result.scanned,
+ "reconciled": result.reconciled,
+ "failed": result.failed,
+ "batch_limit_reached": result.batch_limit_reached,
+ }
+ for operation, result in results.items()
+ },
+ },
+ )
+
+ if self.metrics_registry is None:
+ return
+
+ reconciled = Gauge(
+ "posthog_wizard_run_reconciled_total",
+ "Wizard run records recovered by the reconciliation sweep",
+ labelnames=["operation"],
+ registry=self.metrics_registry,
+ )
+ for operation, result in results.items():
+ reconciled.labels(operation=operation).set(result.reconciled)
diff --git a/products/wizard/backend/tests/runs/test_presentation.py b/products/wizard/backend/tests/runs/test_presentation.py
new file mode 100644
index 000000000000..4be0046e889d
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_presentation.py
@@ -0,0 +1,741 @@
+from hashlib import sha256
+from uuid import UUID
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.conf import settings
+from django.core.cache import cache
+from django.test import override_settings
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import PersonalAPIKey, Team, User
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.config import DEFAULT_WIZARD_VERSION
+from products.wizard.backend.facade.contracts import (
+ CreatePullRequestArtifactInput,
+ CreateWizardRunInput,
+ LocalFolderWorkspace,
+)
+from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStatus
+from products.wizard.backend.models import WizardRun, WizardRunArtifact
+
+
+@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")
+class TestWizardRunViewSet(APIBaseTest):
+ def _url(self, run_id: str = "") -> str:
+ return f"/api/projects/{self.team.id}/wizard/runs/{run_id}"
+
+ def _authenticate_personal_api_key(self, scopes: list[str]) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Wizard run test key",
+ user=self.user,
+ secure_value=hash_key_value(token),
+ scopes=scopes,
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ def _cloud_payload(self, *, repository: str = "posthog/posthog", idempotency_key: str | None = None) -> dict:
+ payload = {
+ "program_id": "posthog-integration",
+ "environment": "cloud",
+ "workspace": {"type": "git_repository", "repository": repository},
+ }
+ if idempotency_key is not None:
+ payload["idempotency_key"] = idempotency_key
+ return payload
+
+ def test_create_local_run(self) -> None:
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(
+ response.json(),
+ {
+ "id": response.json()["id"],
+ "team_id": self.team.id,
+ "created_by_id": self.user.id,
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ "program": {
+ "id": "posthog-integration",
+ "name": "PostHog integration",
+ "description": "Set up PostHog SDK integration",
+ "wizard_version": DEFAULT_WIZARD_VERSION,
+ "command": [],
+ "tags": [],
+ "required_programs": [],
+ "supported_environments": ["local", "cloud"],
+ },
+ "status": "running",
+ "error_code": None,
+ "error_message": None,
+ "stage": None,
+ "created_at": response.json()["created_at"],
+ "updated_at": response.json()["updated_at"],
+ "started_at": response.json()["started_at"],
+ "finished_at": None,
+ "deadline_at": None,
+ },
+ )
+
+ @override_settings(WIZARD_RUN_CREATE_THROTTLE_RATE="1/hour")
+ def test_create_is_rate_limited_per_user(self) -> None:
+ cache.clear()
+
+ first = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "rate-limit-project"},
+ },
+ format="json",
+ )
+ second = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "rate-limit-project-two"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(second.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ @override_settings(WIZARD_RUN_READ_THROTTLE_RATE="1/minute")
+ def test_list_is_rate_limited_per_user(self) -> None:
+ cache.clear()
+
+ first = self.client.get(self._url())
+ second = self.client.get(self._url())
+
+ self.assertEqual(first.status_code, status.HTTP_200_OK)
+ self.assertEqual(second.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ def test_create_requires_program_id(self) -> None:
+ response = self.client.post(
+ self._url(),
+ {
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "program_id")
+ self.assertEqual(response.json()["code"], "required")
+
+ def test_create_accepts_explicit_wizard_version(self) -> None:
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "wizard_version": "latest",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["program"]["wizard_version"], "latest")
+
+ def test_create_rejects_invalid_wizard_version(self) -> None:
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "wizard_version": "next",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "wizard_version")
+
+ def test_create_rejects_unavailable_program(self) -> None:
+ with patch("posthoganalytics.get_feature_flag_payload", return_value={"version": 1, "programs": []}):
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "unavailable-program",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["detail"], "Choose an available Wizard program.")
+ self.assertFalse(WizardRun.objects.for_team(self.team.id).exists())
+
+ def test_retrieve_run(self) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+
+ response = self.client.get(self._url(created["id"]))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), created)
+
+ def test_retrieve_does_not_disclose_another_teams_run(self) -> None:
+ other_team = Team.objects.create(
+ organization=self.team.organization,
+ project=self.team.project,
+ name="Other environment",
+ )
+ other_run = wizard_facade.create_run(
+ CreateWizardRunInput(
+ team_id=other_team.id,
+ created_by_id=self.user.id,
+ program_id="posthog-integration",
+ environment=WizardRunEnvironment.LOCAL,
+ workspace=LocalFolderWorkspace(project_name="other-project"),
+ )
+ )
+
+ response = self.client.get(self._url(str(other_run.id)))
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_create_rejects_unknown_workspace_without_writing(self) -> None:
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "unknown"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(WizardRun.objects.unscoped().filter(team_id=self.team.id).exists())
+
+ def test_create_rejects_environment_workspace_mismatch(self) -> None:
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "git_repository", "repository": "posthog/posthog"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["detail"], "Choose a workspace supported by this run environment.")
+
+ @parameterized.expand(("missing_integration", "inaccessible_repository"))
+ def test_cloud_repository_admission_has_one_public_error(self, scenario: str) -> None:
+ integration_id = None if scenario == "missing_integration" else 123
+ with (
+ patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",
+ return_value=integration_id,
+ ),
+ patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",
+ return_value=False,
+ ),
+ ):
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "cloud",
+ "idempotency_key": f"repository-admission-{scenario}",
+ "workspace": {"type": "git_repository", "repository": "posthog/posthog"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["detail"], "Connect GitHub with access to this repository, then try again.")
+
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",
+ return_value=True,
+ )
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",
+ return_value=123,
+ )
+ def test_cloud_run_rejects_a_second_active_run(self, _resolve_integration, _repository_accessible) -> None:
+ first = self.client.post(self._url(), self._cloud_payload(idempotency_key="first-run"), format="json")
+
+ response = self.client.post(self._url(), self._cloud_payload(idempotency_key="second-run"), format="json")
+
+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+ self.assertEqual(
+ response.json()["detail"],
+ "A cloud Wizard run is already active. Wait for it to finish or cancel it before starting another.",
+ )
+
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",
+ return_value=True,
+ )
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",
+ return_value=123,
+ )
+ @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="")
+ def test_cloud_run_rejects_disabled_cloud_execution(self, _resolve_integration, _repository_accessible) -> None:
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "cloud",
+ "idempotency_key": "disabled-cloud-execution",
+ "workspace": {"type": "git_repository", "repository": "posthog/posthog"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertFalse(WizardRun.objects.for_team(self.team.id).exists())
+
+ def test_personal_api_key_cannot_access_wizard_runs(self) -> None:
+ run = wizard_facade.create_run(
+ CreateWizardRunInput(
+ team_id=self.team.id,
+ created_by_id=self.user.id,
+ program_id="posthog-integration",
+ environment=WizardRunEnvironment.LOCAL,
+ workspace=LocalFolderWorkspace(project_name="example-project"),
+ )
+ )
+
+ self._authenticate_personal_api_key(["wizard_session:read", "wizard_session:write"])
+
+ for url in (
+ self._url(),
+ self._url(str(run.id)),
+ self._url(f"{run.id}/artifacts/"),
+ self._url(f"{run.id}/artifacts/00000000-0000-0000-0000-000000000000/content/"),
+ ):
+ with self.subTest(url=url):
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ response = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "another-project"},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(WizardRun.objects.for_team(self.team.id).count(), 1)
+
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",
+ return_value=True,
+ )
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",
+ return_value=123,
+ )
+ def test_cloud_run_requires_idempotency_key(self, _resolve_integration, _repository_accessible) -> None:
+ response = self.client.post(self._url(), self._cloud_payload(), format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "idempotency_key")
+ self.assertFalse(WizardRun.objects.for_team(self.team.id).exists())
+
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",
+ return_value=True,
+ )
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",
+ return_value=123,
+ )
+ def test_cloud_run_replays_matching_idempotent_request(self, _resolve_integration, _repository_accessible) -> None:
+ payload = self._cloud_payload(idempotency_key="create-posthog-run")
+
+ first = self.client.post(self._url(), payload, format="json")
+ replay = self.client.post(self._url(), payload, format="json")
+
+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(replay.status_code, status.HTTP_200_OK)
+ self.assertEqual(replay.json(), first.json())
+ self.assertEqual(WizardRun.objects.for_team(self.team.id).count(), 1)
+
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",
+ return_value=True,
+ )
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",
+ return_value=123,
+ )
+ def test_cloud_run_rejects_reused_idempotency_key_for_different_request(
+ self, _resolve_integration, _repository_accessible
+ ) -> None:
+ first = self.client.post(
+ self._url(),
+ self._cloud_payload(idempotency_key="create-posthog-run"),
+ format="json",
+ )
+ replay = self.client.post(
+ self._url(),
+ self._cloud_payload(repository="posthog/posthog-js", idempotency_key="create-posthog-run"),
+ format="json",
+ )
+
+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(replay.status_code, status.HTTP_409_CONFLICT)
+ self.assertEqual(replay.json()["code"], "idempotency_conflict")
+ self.assertEqual(WizardRun.objects.for_team(self.team.id).count(), 1)
+
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",
+ return_value=True,
+ )
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",
+ return_value=123,
+ )
+ def test_cloud_run_can_be_cancelled(self, _resolve_integration, _repository_accessible) -> None:
+ created = self.client.post(
+ self._url(),
+ self._cloud_payload(idempotency_key="cancel-posthog-run"),
+ format="json",
+ ).json()
+ WizardRun.objects.for_team(self.team.id).filter(id=created["id"]).update(workflow_id="wizard-workflow")
+
+ with patch(
+ "products.wizard.backend.temporal.client.cancel_wizard_run_workflow",
+ create=True,
+ ) as cancel_workflow:
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.patch(self._url(created["id"]), {"status": "cancelled"}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["status"], "cancelled")
+ cancel_workflow.assert_called_once_with(UUID(created["id"]))
+
+ @patch("products.wizard.backend.logic.artifacts.service.object_storage.write")
+ def test_list_run_artifacts(self, _write) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+ wizard_facade.create_git_diff_artifact(self.team.id, UUID(created["id"]), b"diff")
+
+ response = self.client.get(self._url(f"{created['id']}/artifacts/"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["count"], 1)
+ self.assertEqual(response.json()["results"][0]["run_id"], created["id"])
+ self.assertEqual(response.json()["results"][0]["artifact_type"], "git_diff")
+
+ def test_get_git_diff_content(self) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+ diff = b"diff --git a/app.py b/app.py\n-old\n+new\n"
+
+ with (
+ patch("products.wizard.backend.logic.artifacts.service.object_storage.write"),
+ patch(
+ "products.wizard.backend.logic.artifacts.service.object_storage.read_bytes", return_value=diff
+ ) as read_bytes,
+ ):
+ artifact = wizard_facade.create_git_diff_artifact(self.team.id, UUID(created["id"]), diff)
+ assert artifact is not None
+
+ response = self.client.get(self._url(f"{created['id']}/artifacts/{artifact.id}/content/"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.content, diff)
+ self.assertEqual(response["Content-Type"], "text/x-diff; charset=utf-8")
+ self.assertEqual(response["Cache-Control"], "private, no-store")
+ read_bytes.assert_called_once_with(
+ f"projects/{self.team.id}/wizard-runs/{created['id']}/artifacts/git-diff-{sha256(diff).hexdigest()}.patch",
+ bucket=settings.WIZARD_RUN_ARTIFACTS_S3_BUCKET,
+ missing_ok=True,
+ )
+
+ def test_get_git_diff_content_rejects_oversized_artifact_before_download(self) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.write"):
+ artifact = wizard_facade.create_git_diff_artifact(self.team.id, UUID(created["id"]), b"diff")
+ assert artifact is not None
+ WizardRunArtifact.objects.for_team(self.team.id).filter(id=artifact.id).update(size_bytes=2 * 1024 * 1024 + 1)
+
+ with patch("products.wizard.backend.logic.artifacts.service.object_storage.read_bytes") as read_bytes:
+ response = self.client.get(self._url(f"{created['id']}/artifacts/{artifact.id}/content/"))
+
+ self.assertEqual(response.status_code, status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
+ read_bytes.assert_not_called()
+
+ def test_get_git_diff_content_is_scoped_to_nested_run(self) -> None:
+ first = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "first-project"},
+ },
+ format="json",
+ ).json()
+ second = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "second-project"},
+ },
+ format="json",
+ ).json()
+
+ with (
+ patch("products.wizard.backend.logic.artifacts.service.object_storage.write"),
+ patch("products.wizard.backend.logic.artifacts.service.object_storage.read_bytes") as read_bytes,
+ ):
+ artifact = wizard_facade.create_git_diff_artifact(self.team.id, UUID(first["id"]), b"diff")
+ assert artifact is not None
+
+ response = self.client.get(self._url(f"{second['id']}/artifacts/{artifact.id}/content/"))
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ read_bytes.assert_not_called()
+
+ def test_list_pull_request_artifact(self) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+ wizard_facade.create_pull_request_artifact(
+ CreatePullRequestArtifactInput(
+ team_id=self.team.id,
+ run_id=UUID(created["id"]),
+ url="https://github.com/posthog/posthog/pull/123",
+ number=123,
+ repository="posthog/posthog",
+ head_branch="posthog/wizard-123",
+ base_branch="master",
+ )
+ )
+
+ response = self.client.get(self._url(f"{created['id']}/artifacts/"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ artifact = response.json()["results"][0]
+ self.assertEqual(
+ response.json(),
+ {
+ "count": 1,
+ "next": None,
+ "previous": None,
+ "results": [
+ {
+ "id": artifact["id"],
+ "team_id": self.team.id,
+ "run_id": created["id"],
+ "artifact_type": "pull_request",
+ "url": "https://github.com/posthog/posthog/pull/123",
+ "number": 123,
+ "repository": "posthog/posthog",
+ "head_branch": "posthog/wizard-123",
+ "base_branch": "master",
+ "created_at": artifact["created_at"],
+ }
+ ],
+ },
+ )
+
+ @parameterized.expand(
+ (
+ ({"status": "completed"}, WizardRunStatus.COMPLETED, None),
+ ({"status": "failed", "error_code": "timeout"}, WizardRunStatus.FAILED, "timeout"),
+ (
+ {"status": "failed", "error_code": "PHW_DETECT_NO_POSTHOG_SDK"},
+ WizardRunStatus.FAILED,
+ "PHW_DETECT_NO_POSTHOG_SDK",
+ ),
+ ({"status": "cancelled"}, WizardRunStatus.CANCELLED, None),
+ )
+ )
+ def test_transition_local_run(
+ self,
+ payload: dict[str, str],
+ expected_status: WizardRunStatus,
+ expected_error_code: str | None,
+ ) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+
+ response = self.client.patch(self._url(created["id"]), payload, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["status"], expected_status.value)
+ self.assertEqual(response.json()["error_code"], expected_error_code)
+
+ def test_transition_rejects_invalid_error_code(self) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+
+ response = self.client.patch(
+ self._url(created["id"]),
+ {"status": "failed", "error_code": "arbitrary-error"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_transition_rejects_terminal_run(self) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+ self.client.patch(self._url(created["id"]), {"status": "completed"}, format="json")
+
+ response = self.client.patch(self._url(created["id"]), {"status": "cancelled"}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
+ self.assertEqual(response.json()["code"], "invalid_transition")
+
+ def test_transition_rejects_another_user(self) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ format="json",
+ ).json()
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.client.force_login(other_user)
+
+ response = self.client.patch(self._url(created["id"]), {"status": "completed"}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(wizard_facade.get_run(self.team.id, UUID(created["id"])).status, WizardRunStatus.RUNNING)
+
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.repository_accessible_via_integration",
+ return_value=True,
+ )
+ @patch(
+ "products.wizard.backend.logic.runs.repository_access.repo_selection.resolve_team_github_integration_id",
+ return_value=123,
+ )
+ def test_cloud_run_rejects_non_cancellation_transition(self, _resolve_integration, _repository_accessible) -> None:
+ created = self.client.post(
+ self._url(),
+ {
+ "program_id": "posthog-integration",
+ "environment": "cloud",
+ "idempotency_key": "reject-cloud-completion",
+ "workspace": {"type": "git_repository", "repository": "posthog/posthog"},
+ },
+ format="json",
+ ).json()
+
+ response = self.client.patch(self._url(created["id"]), {"status": "completed"}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
+ self.assertEqual(response.json()["code"], "cloud_run_managed")
+ self.assertEqual(wizard_facade.get_run(self.team.id, UUID(created["id"])).status, WizardRunStatus.CREATED)
+
+ def test_transition_does_not_disclose_another_teams_run(self) -> None:
+ other_team = Team.objects.create(
+ organization=self.team.organization,
+ project=self.team.project,
+ name="Other environment",
+ )
+ other_run = wizard_facade.create_run(
+ CreateWizardRunInput(
+ team_id=other_team.id,
+ created_by_id=self.user.id,
+ program_id="posthog-integration",
+ environment=WizardRunEnvironment.LOCAL,
+ workspace=LocalFolderWorkspace(project_name="other-project"),
+ )
+ )
+
+ response = self.client.patch(self._url(str(other_run.id)), {"status": "completed"}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(wizard_facade.get_run(other_team.id, other_run.id).status, WizardRunStatus.RUNNING)
diff --git a/products/wizard/backend/tests/runs/test_reconciliation.py b/products/wizard/backend/tests/runs/test_reconciliation.py
new file mode 100644
index 000000000000..88571cfc4964
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_reconciliation.py
@@ -0,0 +1,249 @@
+from datetime import timedelta
+
+import pytest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from products.wizard.backend.facade.enums import (
+ WizardRunDispatchStatus,
+ WizardRunEnvironment,
+ WizardRunErrorCode,
+ WizardRunStatus,
+ WizardWorkerCleanupStatus,
+ WizardWorkspaceType,
+)
+from products.wizard.backend.logic.programs import program_to_mapping
+from products.wizard.backend.logic.reconciliation import service as reconciliation
+from products.wizard.backend.logic.registry.config import POSTHOG_INTEGRATION_PROGRAM
+from products.wizard.backend.logic.runs import lifecycle
+from products.wizard.backend.logic.runs.errors import WizardRunDispatchError
+from products.wizard.backend.models import WizardRun, WizardWorker
+from products.wizard.backend.temporal.errors import WizardTemporalError
+
+
+def _create_cloud_run(team_id: int, user_id: int, **values: object) -> WizardRun:
+ defaults = {
+ "team_id": team_id,
+ "created_by_id": user_id,
+ "environment": WizardRunEnvironment.CLOUD.value,
+ "workspace_type": WizardWorkspaceType.GIT_REPOSITORY.value,
+ "workspace": {"repository": "posthog/posthog"},
+ "program": program_to_mapping(POSTHOG_INTEGRATION_PROGRAM),
+ "status": WizardRunStatus.CREATED.value,
+ "dispatch_status": WizardRunDispatchStatus.PENDING.value,
+ "deadline_at": timezone.now() + timedelta(hours=1),
+ }
+ defaults.update(values)
+ return WizardRun.objects.for_team(team_id).create(**defaults)
+
+
+def test_reconciliation_redispatches_pending_run(team, user) -> None:
+ run = _create_cloud_run(team.id, user.id)
+
+ with patch(
+ "products.wizard.backend.logic.reconciliation.service.dispatch_created_cloud_wizard_run_to_temporal_worker"
+ ) as dispatch_wizard_run:
+ result = reconciliation.reconcile_pending_dispatches()
+
+ assert result == reconciliation.ReconciliationSummary(
+ scanned=1,
+ reconciled=1,
+ failed=0,
+ batch_limit_reached=False,
+ )
+ dispatch_wizard_run.assert_called_once_with(team.id, run.id)
+
+
+ ("exhausted", "expected_status"),
+ [(False, WizardRunStatus.CREATED), (True, WizardRunStatus.FAILED)],
+)
+def test_reconciliation_continues_after_expected_dispatch_failure(
+ team, user, exhausted: bool, expected_status: WizardRunStatus
+) -> None:
+ run = _create_cloud_run(team.id, user.id)
+
+ with patch(
+ "products.wizard.backend.logic.reconciliation.service.dispatch_created_cloud_wizard_run_to_temporal_worker",
+ side_effect=WizardRunDispatchError(is_exhausted=exhausted),
+ ):
+ result = reconciliation.reconcile_pending_dispatches()
+
+ assert result == reconciliation.ReconciliationSummary(
+ scanned=1,
+ reconciled=0,
+ failed=1,
+ batch_limit_reached=False,
+ )
+ run.refresh_from_db()
+ assert run.status == expected_status.value
+ assert run.error_code == (WizardRunErrorCode.DISPATCH_FAILED.value if exhausted else None)
+
+
+def test_reconciliation_fails_run_after_dispatch_attempt_limit(team, user) -> None:
+ run = _create_cloud_run(team.id, user.id, dispatch_attempts=4)
+
+ with patch(
+ "products.wizard.backend.logic.runs.dispatch.temporal_client.start_wizard_run_workflow",
+ side_effect=WizardTemporalError,
+ ):
+ result = reconciliation.reconcile_pending_dispatches()
+
+ assert result.failed == 1
+ run.refresh_from_db()
+ assert run.status == WizardRunStatus.FAILED.value
+ assert run.error_code == WizardRunErrorCode.DISPATCH_FAILED.value
+ assert run.dispatch_attempts == 5
+ assert run.dispatch_next_attempt_at is None
+
+
+def test_reconciliation_skips_dispatches_that_are_not_ready_for_retry(team, user) -> None:
+ ready_run = _create_cloud_run(team.id, user.id)
+ _create_cloud_run(team.id, user.id, dispatch_next_attempt_at=timezone.now() + timedelta(minutes=1))
+
+ with patch(
+ "products.wizard.backend.logic.reconciliation.service.dispatch_created_cloud_wizard_run_to_temporal_worker"
+ ) as dispatch_wizard_run:
+ result = reconciliation.reconcile_pending_dispatches()
+
+ assert result == reconciliation.ReconciliationSummary(
+ scanned=1,
+ reconciled=1,
+ failed=0,
+ batch_limit_reached=False,
+ )
+ dispatch_wizard_run.assert_called_once_with(team.id, ready_run.id)
+
+
+def test_reconciliation_surfaces_unexpected_dispatch_failure(team, user) -> None:
+ _create_cloud_run(team.id, user.id)
+
+ with (
+ patch(
+ "products.wizard.backend.logic.reconciliation.service.dispatch_created_cloud_wizard_run_to_temporal_worker",
+ side_effect=RuntimeError("bug"),
+ ),
+ pytest.raises(RuntimeError, match="bug"),
+ ):
+ reconciliation.reconcile_pending_dispatches()
+
+
+def test_cloud_cancellation_survives_temporal_failure(team, user) -> None:
+ run = _create_cloud_run(
+ team.id,
+ user.id,
+ status=WizardRunStatus.RUNNING.value,
+ dispatch_status=WizardRunDispatchStatus.DISPATCHED.value,
+ workflow_id="wizard-run-id",
+ )
+
+ with patch(
+ "products.wizard.backend.logic.runs.cancellation.temporal_client.cancel_wizard_run_workflow",
+ side_effect=WizardTemporalError,
+ ):
+ cancelled = lifecycle.cancel_run(team.id, run.id)
+
+ record = WizardRun.objects.for_team(team.id).get(id=run.id)
+ assert cancelled.status == WizardRunStatus.CANCELLED
+ assert record.cancellation_requested_at is not None
+ assert record.cancellation_dispatched_at is None
+
+
+def test_reconciliation_retries_pending_cancellation(team, user) -> None:
+ run = _create_cloud_run(
+ team.id,
+ user.id,
+ status=WizardRunStatus.CANCELLED.value,
+ dispatch_status=WizardRunDispatchStatus.DISPATCHED.value,
+ workflow_id="wizard-run-id",
+ cancellation_requested_at=timezone.now(),
+ )
+
+ with patch("products.wizard.backend.logic.runs.cancellation.temporal_client.cancel_wizard_run_workflow") as cancel:
+ result = reconciliation.reconcile_pending_cancellations()
+
+ assert result == reconciliation.ReconciliationSummary(
+ scanned=1,
+ reconciled=1,
+ failed=0,
+ batch_limit_reached=False,
+ )
+ cancel.assert_called_once_with(run.id)
+ run.refresh_from_db()
+ assert run.cancellation_dispatched_at is not None
+
+
+def test_reconciliation_fails_expired_run(team, user) -> None:
+ run = _create_cloud_run(team.id, user.id, deadline_at=timezone.now() - timedelta(seconds=1))
+
+ result = reconciliation.reconcile_expired_runs()
+
+ assert result == reconciliation.ReconciliationSummary(
+ scanned=1,
+ reconciled=1,
+ failed=0,
+ batch_limit_reached=False,
+ )
+ run.refresh_from_db()
+ assert run.status == WizardRunStatus.FAILED.value
+ assert run.error_code == WizardRunErrorCode.TIMEOUT.value
+
+
+def test_reconciliation_destroys_orphaned_active_worker(team, user) -> None:
+ run = _create_cloud_run(team.id, user.id, status=WizardRunStatus.COMPLETED.value)
+ worker = WizardWorker.objects.for_team(team.id).create(
+ team_id=team.id,
+ run=run,
+ sandbox_id="sandbox-id",
+ cleanup_status=WizardWorkerCleanupStatus.ACTIVE.value,
+ )
+
+ with (
+ patch(
+ "products.wizard.backend.logic.workers.lifecycle.cloud_worker.measure_worker_usage",
+ return_value=None,
+ ),
+ patch("products.wizard.backend.logic.workers.lifecycle.cloud_worker.destroy_worker") as destroy,
+ ):
+ result = reconciliation.reconcile_pending_worker_cleanup()
+
+ assert result == reconciliation.ReconciliationSummary(
+ scanned=1,
+ reconciled=1,
+ failed=0,
+ batch_limit_reached=False,
+ )
+ destroy.assert_called_once_with("sandbox-id")
+ worker.refresh_from_db()
+ assert worker.cleanup_status == WizardWorkerCleanupStatus.CLEANED.value
+
+
+def test_reconciliation_stops_after_worker_cleanup_attempt_limit(team, user) -> None:
+ run = _create_cloud_run(team.id, user.id, status=WizardRunStatus.COMPLETED.value)
+ WizardWorker.objects.for_team(team.id).create(
+ team_id=team.id,
+ run=run,
+ sandbox_id="sandbox-id",
+ cleanup_status=WizardWorkerCleanupStatus.PENDING.value,
+ cleanup_attempts=5,
+ )
+
+ result = reconciliation.reconcile_pending_worker_cleanup()
+
+ assert result == reconciliation.ReconciliationSummary(
+ scanned=0,
+ reconciled=0,
+ failed=0,
+ batch_limit_reached=False,
+ )
diff --git a/products/wizard/backend/tests/runs/test_serializers.py b/products/wizard/backend/tests/runs/test_serializers.py
new file mode 100644
index 000000000000..f364d810cf2a
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_serializers.py
@@ -0,0 +1,74 @@
+import pytest
+
+from products.wizard.backend.facade.contracts import GitRepositoryWorkspace, LocalFolderWorkspace
+from products.wizard.backend.facade.enums import WizardRunEnvironment
+from products.wizard.backend.presentation.runs.serializers import WizardRunCreateRequestSerializer
+
+
+ "payload, expected_environment, expected_workspace",
+ (
+ (
+ {
+ "program_id": "posthog-integration",
+ "environment": "local",
+ "workspace": {"type": "local_folder", "project_name": "example-project"},
+ },
+ WizardRunEnvironment.LOCAL,
+ LocalFolderWorkspace(project_name="example-project"),
+ ),
+ (
+ {
+ "program_id": "posthog-integration",
+ "environment": "cloud",
+ "idempotency_key": "serialize-cloud-run",
+ "workspace": {"type": "git_repository", "repository": "posthog/posthog"},
+ },
+ WizardRunEnvironment.CLOUD,
+ GitRepositoryWorkspace(repository="posthog/posthog"),
+ ),
+ ),
+)
+def test_create_request_discriminates_workspace(
+ payload: dict[str, object],
+ expected_environment: WizardRunEnvironment,
+ expected_workspace: LocalFolderWorkspace | GitRepositoryWorkspace,
+) -> None:
+ serializer = WizardRunCreateRequestSerializer(data=payload)
+
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.to_contract(team_id=123, created_by_id=456).program_id == "posthog-integration"
+ assert serializer.to_contract(team_id=123, created_by_id=456).environment == expected_environment
+ assert serializer.to_contract(team_id=123, created_by_id=456).workspace == expected_workspace
+
+
+ "workspace",
+ (
+ {},
+ {"type": "unknown"},
+ {"type": "local_folder"},
+ {"type": "git_repository"},
+ ),
+)
+def test_create_request_rejects_invalid_workspace(workspace: dict[str, object]) -> None:
+ serializer = WizardRunCreateRequestSerializer(
+ data={"program_id": "posthog-integration", "environment": "local", "workspace": workspace}
+ )
+
+ assert not serializer.is_valid()
+ assert "workspace" in serializer.errors
+
+
[email protected]("repository", ("posthog", "/posthog", "posthog/", "posthog/posthog/extra"))
+def test_create_request_rejects_invalid_repository(repository: str) -> None:
+ serializer = WizardRunCreateRequestSerializer(
+ data={
+ "program_id": "posthog-integration",
+ "environment": "cloud",
+ "workspace": {"type": "git_repository", "repository": repository},
+ }
+ )
+
+ assert not serializer.is_valid()
+ assert "workspace" in serializer.errors
diff --git a/products/wizard/backend/tests/runs/test_temporal_registration.py b/products/wizard/backend/tests/runs/test_temporal_registration.py
new file mode 100644
index 000000000000..4296fb574647
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_temporal_registration.py
@@ -0,0 +1,20 @@
+from products.wizard.backend.facade.temporal import ACTIVITIES, WORKFLOWS
+from products.wizard.backend.temporal.activities.execution import execute_wizard
+from products.wizard.backend.temporal.activities.handoff import create_run_artifacts
+from products.wizard.backend.temporal.activities.lifecycle import finalize_run
+from products.wizard.backend.temporal.activities.local_package import prepare_local_wizard
+from products.wizard.backend.temporal.activities.workspace import clone_repository, destroy_worker, provision_worker
+from products.wizard.backend.temporal.workflows.execute_run import ExecuteWizardRunWorkflow
+
+
+def test_wizard_temporal_registry_exposes_cloud_run_components() -> None:
+ assert WORKFLOWS == [ExecuteWizardRunWorkflow]
+ assert ACTIVITIES == [
+ provision_worker,
+ prepare_local_wizard,
+ clone_repository,
+ execute_wizard,
+ create_run_artifacts,
+ destroy_worker,
+ finalize_run,
+ ]
diff --git a/products/wizard/backend/tests/sessions/test_session_presentation.py b/products/wizard/backend/tests/sessions/test_session_presentation.py
index c505a0c6489f..cd4f9eadbcb3 100644
--- a/products/wizard/backend/tests/sessions/test_session_presentation.py
+++ b/products/wizard/backend/tests/sessions/test_session_presentation.py
@@ -217,6 +217,11 @@ class TestWizardSessionViewSet(APIBaseTest):
response = self.client.get(self._url() + "?workflow_id=onboarding&skill_id=django")
self.assertEqual(len(response.json()["results"]), 0)
+ def test_list_rejects_invalid_pagination(self):
+ response = self.client.get(self._url() + "?limit=invalid")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
def test_list_empty_skill_id_is_ignored(self):
# An empty skill_id is treated as no filter, so the session still shows up.
self.client.post(
diff --git a/products/wizard/backend/tests/test_presentation.py b/products/wizard/backend/tests/test_presentation.py
deleted file mode 100644
index 6b0d536cd0b1..000000000000
--- a/products/wizard/backend/tests/test_presentation.py
+++ /dev/null
@@ -1,484 +0,0 @@
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.models import Organization, PersonalAPIKey, User
-from posthog.models.utils import generate_random_token_personal, hash_key_value
-
-from products.wizard.backend.models import WizardSession
-from products.wizard.backend.presentation.views import _wizard_sync_killswitch_enabled
-
-
-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 _authenticate_personal_api_key(self, scopes: list[str]) -> None:
- token = generate_random_token_personal()
- PersonalAPIKey.objects.create(
- label="Wizard test key",
- user=self.user,
- secure_value=hash_key_value(token),
- scopes=scopes,
- )
- self.client.logout()
- self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
-
- 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_create_session_attributes_run_to_authenticated_user(self):
- response = self.client.post(self._url(), self._payload(), format="json")
-
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- created_by = response.json()["created_by"]
- self.assertEqual(created_by["id"], self.user.id)
- self.assertEqual(created_by["email"], self.user.email)
- self.assertEqual(created_by["first_name"], self.user.first_name)
-
- def test_completed_session_requires_event_definition_write_scope(self):
- self._authenticate_personal_api_key(["wizard_session:write"])
-
- response = self.client.post(
- self._url(),
- self._payload(run_phase="completed"),
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
-
- def test_running_session_accepts_wizard_write_scope(self):
- self._authenticate_personal_api_key(["wizard_session:write"])
-
- response = self.client.post(
- self._url(),
- self._payload(run_phase="running"),
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-
- @patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async")
- def test_completed_session_accepts_event_definition_write_scope(self, _mock_sync):
- self._authenticate_personal_api_key(["wizard_session:write", "event_definition:write"])
-
- response = self.client.post(
- self._url(),
- self._payload(run_phase="completed"),
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-
- @patch("products.wizard.backend.logic.sessions.lifecycle.sync_wizard_event_definitions.apply_async")
- def test_repost_same_session_id_upserts(self, _mock_sync):
- 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_repost_by_a_different_user_is_forbidden(self):
- first = self.client.post(self._url(), self._payload(), format="json")
- self.assertEqual(first.status_code, status.HTTP_201_CREATED)
-
- other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
- self.client.force_login(other_user)
-
- response = self.client.post(
- self._url(),
- self._payload(run_phase="completed"),
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
-
- 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_list_empty_skill_id_is_ignored(self):
- # An empty skill_id is treated as no filter, so the session still shows up.
- self.client.post(
- self._url(),
- self._payload(workflow_id="onboarding", skill_id="nextjs"),
- format="json",
- )
-
- response = self.client.get(self._url() + "?workflow_id=onboarding&skill_id=")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(len(response.json()["results"]), 1)
-
- 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)
-
- def test_latest_returns_most_recent_session_for_workflow(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("latest/") + "?workflow_id=onboarding")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- body = response.json()
- self.assertEqual(body["started_at"], "2026-05-19T19:00:00Z")
- # A bare object, not a paginated `{results: [...]}` envelope.
- self.assertNotIn("results", body)
- self.assertEqual(body["session_id"], "onboarding-nextjs-2026-05-19T19:00:00Z")
-
- def test_latest_breaks_started_at_ties_by_created_at(self):
- # Same started_at; the row POSTed second has the later created_at and wins.
- self.client.post(
- self._url(),
- self._payload(
- session_id="onboarding-nextjs-first",
- started_at="2026-05-19T10:00:00Z",
- ),
- format="json",
- )
- self.client.post(
- self._url(),
- self._payload(
- session_id="onboarding-nextjs-second",
- started_at="2026-05-19T10:00:00Z",
- ),
- format="json",
- )
-
- response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["session_id"], "onboarding-nextjs-second")
-
- def test_latest_skill_id_narrows_the_match(self):
- self.client.post(
- self._url(),
- self._payload(session_id="onboarding-nextjs-1", skill_id="nextjs"),
- format="json",
- )
-
- response = self.client.get(self._url("latest/") + "?workflow_id=onboarding&skill_id=django")
- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
-
- def test_latest_without_a_session_returns_204_not_404(self):
- # 204, not 404: the detector treats 404 as a missing endpoint and stops polling.
- response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
-
- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
- self.assertEqual(response.content, b"")
-
- def test_latest_requires_workflow_id(self):
- response = self.client.get(self._url("latest/"))
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-
- def test_latest_does_not_collide_with_session_id_lookup(self):
- # lookup_value_regex excludes "latest", so the action wins over a retrieve
- # of a session whose id is literally "latest".
- self.client.post(
- self._url(),
- self._payload(session_id="latest", started_at="2026-05-19T10:00:00Z"),
- format="json",
- )
-
- response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- @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_latest_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/latest/?workflow_id=onboarding")
- 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"})
-
- def test_handoff_text_persists_across_pushes_without_it(self):
- # Leading indentation must survive validation: the doc is markdown, where it is syntax.
- doc = " indented code block\n\n# Setup report"
- response = self.client.post(self._url(), self._payload(handoff_text=doc), format="json")
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertEqual(response.json()["handoff_text"], doc)
-
- response = self.client.post(self._url(), self._payload(), format="json")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["handoff_text"], doc)
-
- def test_stream_requires_workflow_id(self):
- # No params → 400 from the view-level validation (workflow_id is the
- # only required query param; skill_id is optional for pattern subscribe).
- response = self.client.get(f"{self._url()}stream/")
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-
- @patch("products.wizard.backend.presentation.views.posthoganalytics.feature_enabled", return_value=True)
- def test_stream_killswitch_returns_204(self, _mock_feature_enabled):
- # When the killswitch flag is on, the endpoint short-circuits with a 204
- # before any stream work — a 204 tells EventSource to stop reconnecting.
- response = self.client.get(f"{self._url()}stream/?workflow_id=onboarding")
- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
-
- @patch("products.wizard.backend.presentation.views.posthoganalytics.feature_enabled", return_value=True)
- def test_latest_killswitch_returns_204_even_with_a_live_session(self, _mock_feature_enabled):
- # Parity with stream: with the killswitch on, `latest` short-circuits to a 204
- # even though a real session exists, so the detector's 60s poll winds down too
- # (the client treats 204 as "no run") rather than only the SSE stream closing.
- self.client.post(self._url(), self._payload(), format="json")
-
- response = self.client.get(self._url("latest/") + "?workflow_id=onboarding")
- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
-
- @parameterized.expand([("on", True, True), ("off", False, False), ("unresolved", None, False)])
- def test_wizard_sync_killswitch_helper(self, _label, flag_value, expected):
- with patch(
- "products.wizard.backend.presentation.views.posthoganalytics.feature_enabled",
- return_value=flag_value,
- ):
- self.assertEqual(_wizard_sync_killswitch_enabled("distinct-id"), expected)
-
- def test_sensitive_pending_input_is_stored_without_prompt_text(self):
- # Redaction has to happen before the row is written, since the same value is streamed over
- # SSE and logged — a client that sends the text anyway must not get it persisted.
- response = self.client.post(
- self._url(),
- self._payload(
- pending_input={
- "id": "ask-1",
- "asked_at": "2026-05-19T10:05:00Z",
- "question_count": 1,
- "sensitive": True,
- "prompts": ["Paste your API key"],
- }
- ),
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- self.assertNotIn("prompts", response.json()["pending_input"])
-
- session = WizardSession.objects.unscoped().get(team=self.team)
- stored = session.pending_input
- assert stored is not None
- self.assertNotIn("prompts", stored)
- self.assertTrue(stored["sensitive"])
-
- def test_pending_input_with_asked_at_survives_every_read_path(self):
- # asked_at is validated as a datetime but stored as a string, since the column is JSON.
- # Every read serializes that string back out through the same DateTimeField.
- create = self.client.post(
- self._url(),
- self._payload(pending_input={"id": "ask-1", "asked_at": "2026-05-19T10:05:00Z"}),
- format="json",
- )
- self.assertEqual(create.status_code, status.HTTP_201_CREATED)
-
- for label, url in [
- ("latest", self._url("latest/") + "?workflow_id=onboarding"),
- ("retrieve", self._url("onboarding-nextjs-2026-05-19T10:00:00Z/")),
- ("list", self._url()),
- ]:
- with self.subTest(read=label):
- response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- body = response.json()
- payload = body["results"][0] if label == "list" else body
- self.assertEqual(payload["pending_input"]["id"], "ask-1")
- self.assertIn("asked_at", payload["pending_input"])
-
- @parameterized.expand(
- [
- ("prompt_not_a_string", {"prompts": [{}]}),
- ("prompt_too_long", {"prompts": ["x" * 2001]}),
- ("too_many_prompts", {"prompts": ["q"] * 11}),
- ("missing_id", {"id": None}),
- ("question_count_out_of_range", {"question_count": 0}),
- ]
- )
- def test_malformed_pending_input_is_rejected(self, _label, overrides):
- pending_input = {"id": "ask-1", "sensitive": False, "prompts": ["Which region?"]}
- pending_input.update(overrides)
-
- response = self.client.post(self._url(), self._payload(pending_input=pending_input), format="json")
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 0)
diff --git a/products/wizard/backend/tests/test_pubsub.py b/products/wizard/backend/tests/test_pubsub.py
deleted file mode 100644
index 24bec1615f61..000000000000
--- a/products/wizard/backend/tests/test_pubsub.py
+++ /dev/null
@@ -1,96 +0,0 @@
-from datetime import UTC, datetime
-
-import pytest
-from unittest.mock import MagicMock, patch
-
-from django.db import transaction
-
-from products.wizard.backend.facade.contracts import WizardSessionDTO, WizardTaskDTO
-from products.wizard.backend.facade.enums import RunPhase, TaskStatus
-from products.wizard.backend.logic.pubsub import channel_name, publish_session_update
-
-
-def _dto(team_id: int = 1) -> WizardSessionDTO:
- now = datetime(2026, 5, 19, 10, 0, 0, tzinfo=UTC)
- return WizardSessionDTO(
- # session_id has no colons because channel_name validates the safe-id
- # alphabet on workflow_id/skill_id. session_id itself isn't part of
- # the channel name, but we still keep the format safe for downstream
- # consumers.
- session_id="onboarding-nextjs-2026-05-19T10-00-00Z",
- team_id=team_id,
- workflow_id="onboarding",
- skill_id="nextjs",
- started_at=now,
- run_phase=RunPhase.RUNNING,
- is_stale=False,
- tasks=(WizardTaskDTO(id="1", title="Install SDK", status=TaskStatus.IN_PROGRESS),),
- event_plan=None,
- error=None,
- pending_input=None,
- handoff_text=None,
- created_by=None,
- created_at=now,
- updated_at=now,
- )
-
-
-def test_channel_name_is_deterministic():
- assert channel_name(1, "onboarding", "nextjs") == "wizard_sessions:team:1:workflow:onboarding:skill:nextjs"
-
-
-def test_channel_name_rejects_unsafe_ids():
- """workflow_id / skill_id can't smuggle Redis glob metacharacters or `:`."""
- with pytest.raises(ValueError):
- channel_name(1, "onboarding", "next*")
- with pytest.raises(ValueError):
- channel_name(1, "*", "nextjs")
- with pytest.raises(ValueError):
- channel_name(1, "onboarding:malicious", "nextjs")
- with pytest.raises(ValueError):
- channel_name(1, "onboarding", "next[js]")
-
-
[email protected]_db(transaction=True)
-def test_publish_session_update_publishes_after_commit():
- """In transaction.atomic, the publish should defer to on_commit."""
- redis_mock = MagicMock()
- with patch("products.wizard.backend.logic.pubsub.get_client", return_value=redis_mock):
- with transaction.atomic():
- publish_session_update(_dto())
- assert redis_mock.publish.call_count == 0 # not yet committed
-
- # After atomic block exits, on_commit hooks fire.
- assert redis_mock.publish.call_count == 1
- channel, payload = redis_mock.publish.call_args.args
- assert channel == "wizard_sessions:team:1:workflow:onboarding:skill:nextjs"
- assert b'"session_id":"onboarding-nextjs-2026-05-19T10-00-00Z"' in payload
- assert b'"run_phase":"running"' in payload
- assert b'"status":"in_progress"' in payload
-
-
-def test_publish_session_update_does_not_publish_on_rollback():
- redis_mock = MagicMock()
- with patch("products.wizard.backend.logic.pubsub.get_client", return_value=redis_mock):
- try:
- with transaction.atomic():
- publish_session_update(_dto())
- raise RuntimeError("force rollback")
- except RuntimeError:
- pass
-
- assert redis_mock.publish.call_count == 0
-
-
[email protected]_db(transaction=True)
-def test_publish_session_update_swallows_redis_errors():
- """Redis publish failure must not fail the upsert request."""
- redis_mock = MagicMock()
- redis_mock.publish.side_effect = ConnectionError("redis is down")
-
- with patch("products.wizard.backend.logic.pubsub.get_client", return_value=redis_mock):
- with transaction.atomic():
- publish_session_update(_dto())
- # If the exception escaped on_commit, this assertion wouldn't run.
- assert redis_mock.publish.call_count == 1
diff --git a/products/wizard/backend/tests/test_registry_presentation.py b/products/wizard/backend/tests/test_registry_presentation.py
new file mode 100644
index 000000000000..bcc025cf3d33
--- /dev/null
+++ b/products/wizard/backend/tests/test_registry_presentation.py
@@ -0,0 +1,91 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+
+from posthog.models import Organization, PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+
+class TestWizardRegistryViewSet(APIBaseTest):
+ def _url(self) -> str:
+ return f"/api/projects/{self.team.id}/wizard/registry/"
+
+ def test_list_returns_personalized_paginated_registry(self) -> None:
+ programs = [
+ {
+ "id": "posthog-integration",
+ "name": "PostHog integration",
+ "description": "Set up the PostHog SDK integration",
+ "wizard_version": "2.60.0",
+ "command": [],
+ "tags": ["setup", "product-analytics"],
+ "required_programs": [],
+ "supported_environments": ["local", "cloud"],
+ },
+ {
+ "id": "web-analytics-audit",
+ "name": "Web analytics audit",
+ "description": "Audit a project's web analytics setup",
+ "wizard_version": "2.60.0",
+ "command": ["audit", "web-analytics"],
+ "tags": ["audit", "web-analytics"],
+ "required_programs": ["posthog-integration"],
+ "supported_environments": ["local"],
+ },
+ ]
+ payload = {"version": 1, "programs": programs}
+
+ with patch("posthoganalytics.get_feature_flag_payload", return_value=payload) as get_payload:
+ response = self.client.get(f"{self._url()}?limit=1&offset=1")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json(),
+ {
+ "count": 2,
+ "next": None,
+ "previous": f"http://testserver{self._url()}?limit=1",
+ "results": [programs[1]],
+ },
+ )
+ get_payload.assert_called_once_with(
+ "wizard-program-registry",
+ distinct_id=self.user.distinct_id,
+ groups={"organization": str(self.team.organization_id)},
+ group_properties={"organization": {"id": str(self.team.organization_id)}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+
+ def test_list_requires_authentication(self) -> None:
+ self.client.logout()
+
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
+ def test_list_rejects_personal_api_key(self) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Wizard registry test key",
+ user=self.user,
+ secure_value=hash_key_value(token),
+ scopes=["wizard_session:read"],
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ response = self.client.get(self._url())
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_list_rejects_another_organizations_project(self) -> None:
+ organization = Organization.objects.create(name="Other organization")
+ team = self.create_team_with_organization(organization)
+
+ with patch("posthoganalytics.get_feature_flag_payload") as get_payload:
+ response = self.client.get(f"/api/projects/{team.id}/wizard/registry/")
+
+ self.assertIn(response.status_code, (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND))
+ get_payload.assert_not_called()
diff --git a/products/wizard/backend/tests/test_stream.py b/products/wizard/backend/tests/test_stream.py
deleted file mode 100644
index c2fc37aad8b1..000000000000
--- a/products/wizard/backend/tests/test_stream.py
+++ /dev/null
@@ -1,188 +0,0 @@
-from contextlib import asynccontextmanager
-from datetime import UTC, datetime
-
-import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
-
-from asgiref.sync import sync_to_async
-
-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
-from products.wizard.backend.presentation.views import _wizard_session_event_stream
-
-
-class _StopStream(Exception):
- """Helper to break the infinite generator after we've collected what we want."""
-
-
-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,
- "pending_input": None,
- }
- params.update(overrides)
- return UpsertWizardSessionInput(**params)
-
-
-async def _drain(generator, max_events: int):
- """Pull up to max_events from the async generator, stopping early on _StopStream."""
- events = []
- try:
- for _ in range(max_events):
- events.append(await anext(generator))
- except (_StopStream, StopAsyncIteration):
- pass
- finally:
- # Close the generator so its `async with` runs cleanup (closes the
- # Redis subscription). Without this, leaked subscriptions would pass
- # the tests silently.
- await generator.aclose()
- return events
-
-
-def _async_subscribe_cm(pubsub_mock):
- """Build an async context manager that yields the given pubsub mock.
-
- Tracks enter/exit calls on the returned tuple `(cm_factory, exit_marker)`
- so tests can assert cleanup ran.
- """
- exit_marker = MagicMock(name="exit_marker")
-
- @asynccontextmanager
- async def _cm(team_id, workflow_id, skill_id):
- try:
- yield pubsub_mock
- finally:
- exit_marker(team_id, workflow_id, skill_id)
-
- return _cm, exit_marker
-
-
-def _patch_subscribe(pubsub_mock):
- """Patch the facade's `subscribe_to_updates` async context manager.
-
- Returns the patch object plus a sentinel that records cleanup so tests
- can confirm the Redis subscription's `__aexit__` ran.
- """
- cm_factory, exit_marker = _async_subscribe_cm(pubsub_mock)
- return (
- patch(
- "products.wizard.backend.presentation.views.wizard_facade.subscribe_to_updates",
- cm_factory,
- ),
- exit_marker,
- )
-
-
-def _async_get_message(side_effects):
- return AsyncMock(side_effect=side_effects)
-
-
[email protected]_db(transaction=True)
-async def test_stream_emits_initial_state_when_session_exists(team):
- await sync_to_async(wizard_facade.upsert)(_input(team.id))
-
- pubsub_mock = MagicMock()
- pubsub_mock.get_message = _async_get_message([_StopStream()])
-
- patcher, exit_marker = _patch_subscribe(pubsub_mock)
- with patcher:
- gen = _wizard_session_event_stream(team_id=team.id, workflow_id="onboarding", skill_id="nextjs")
- events = await _drain(gen, max_events=2)
-
- assert len(events) == 1
- assert events[0].startswith(b"data: ")
- assert b'"session_id":"onboarding-nextjs-2026-05-19T10-00-00Z"' in events[0]
- assert events[0].endswith(b"\n\n")
- # Cleanup must run — otherwise we'd leak Redis subscriptions on every
- # client disconnect.
- exit_marker.assert_called_once_with(team.id, "onboarding", "nextjs")
-
-
[email protected]_db(transaction=True)
-async def test_stream_skips_initial_event_when_no_session(team):
- pubsub_mock = MagicMock()
- pubsub_mock.get_message = _async_get_message([_StopStream()])
-
- patcher, exit_marker = _patch_subscribe(pubsub_mock)
- with patcher:
- gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")
- events = await _drain(gen, max_events=2)
-
- assert events == []
- exit_marker.assert_called_once()
-
-
[email protected]_db(transaction=True)
-async def test_stream_forwards_pubsub_messages(team):
- pubsub_mock = MagicMock()
- pubsub_mock.get_message = _async_get_message(
- [
- {"type": "message", "data": b'{"session_id":"a"}'},
- {"type": "message", "data": b'{"session_id":"b"}'},
- _StopStream(),
- ]
- )
-
- patcher, exit_marker = _patch_subscribe(pubsub_mock)
- with patcher:
- gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")
- events = await _drain(gen, max_events=5)
-
- assert events == [
- b'data: {"session_id":"a"}\n\n',
- b'data: {"session_id":"b"}\n\n',
- ]
- exit_marker.assert_called_once()
-
-
[email protected]_db(transaction=True)
-async def test_stream_emits_heartbeat_when_idle(team):
- pubsub_mock = MagicMock()
- pubsub_mock.get_message = _async_get_message([None, None, _StopStream()])
-
- patcher, exit_marker = _patch_subscribe(pubsub_mock)
- # Force heartbeat threshold to zero so any idle tick emits one.
- with (
- patcher,
- patch("products.wizard.backend.presentation.views.SSE_HEARTBEAT_INTERVAL_SECONDS", 0.0),
- ):
- gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")
- events = await _drain(gen, max_events=4)
-
- assert events == [b": ping\n\n", b": ping\n\n"]
- exit_marker.assert_called_once()
-
-
[email protected]_db(transaction=True)
-async def test_stream_terminates_on_max_duration(team):
- """SSE_MAX_DURATION_SECONDS=0 -> first loop tick emits `event: end` and exits."""
- pubsub_mock = MagicMock()
- pubsub_mock.get_message = _async_get_message([None] * 10)
-
- patcher, exit_marker = _patch_subscribe(pubsub_mock)
- with (
- patcher,
- patch("products.wizard.backend.presentation.views.SSE_MAX_DURATION_SECONDS", 0),
- ):
- gen = _wizard_session_event_stream(team_id=team.id, workflow_id="missing", skill_id="missing")
- events = await _drain(gen, max_events=5)
-
- # Generator emits `event: end` then returns — clean close, no leaked
- # subscription.
- assert events == [b"event: end\ndata: reconnect\n\n"]
- exit_marker.assert_called_once()
diff --git a/products/wizard/backend/tests/test_utils.py b/products/wizard/backend/tests/test_utils.py
deleted file mode 100644
index b270ab7672d5..000000000000
--- a/products/wizard/backend/tests/test_utils.py
+++ /dev/null
@@ -1,29 +0,0 @@
-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 expected
diff --git a/products/wizard/docs/local-development.md b/products/wizard/docs/local-development.md
new file mode 100644
index 000000000000..779ac7359d76
--- /dev/null
+++ b/products/wizard/docs/local-development.md
@@ -0,0 +1,13 @@
+# Local Wizard Development
+
+Set this variable before you start PostHog:
+
+```text
+LOCAL_WIZARD_ROOT=/Users/fcgomes/posthog-dev/wizard
+```
+
+This option works only when Django debug mode is active.
+
+For each cloud run, the Temporal worker copies the local Wizard source into the sandbox. The sandbox installs the dependencies and builds the Wizard before execution.
+
+Restart the PostHog backend and Temporal worker after you change the variable. You do not need to restart them after you change Wizard source files.
diff --git a/products/wizard/docs/reliability.md b/products/wizard/docs/reliability.md
new file mode 100644
index 000000000000..16577ad64cd9
--- /dev/null
+++ b/products/wizard/docs/reliability.md
@@ -0,0 +1,24 @@
+# Wizard Cloud Run Reliability
+
+These are internal targets. They are not a customer SLA.
+
+Measure each SLI over one calendar month.
+
+| SLI | Definition | Initial SLO |
+| --------------------------- | ------------------------------------------------------------------------------- | ------------ |
+| Dispatch success | Accepted cloud runs that start a Temporal workflow. | 99.0% |
+| Worker provisioning success | Dispatched runs that provision a Wizard Worker. | 99.0% |
+| Platform failure rate | Runs that fail because of PostHog, Temporal, a sandbox, or artifact publishing. | At most 2.0% |
+| Artifact handoff success | Successful Wizard executions that create the expected artifact. | 99.0% |
+| Worker cleanup success | Worker cleanup attempts that destroy the Wizard Worker. | 99.5% |
+| Deadline breach rate | Cloud runs detected after their deadline. | At most 0.1% |
+
+Do not count user input failures as platform failures. Examples include an inaccessible repository and an invalid repository configuration.
+
+## Failure codes
+
+The Wizard writes a final `phw-error:` record to standard error when a program fails. The worker stores its `PHW_*` code on the Wizard run.
+
+The backend stores only the code. The UI owns the user message and recovery steps. If the record is absent or invalid, use the platform error for the failed stage.
+
+Collect latency data before you set latency SLOs. Review these targets after 30 to 60 days of production data.
diff --git a/products/wizard/frontend/generated/api.schemas.ts b/products/wizard/frontend/generated/api.schemas.ts
index 42492345605e..2374b8301903 100644
--- a/products/wizard/frontend/generated/api.schemas.ts
+++ b/products/wizard/frontend/generated/api.schemas.ts
@@ -7,6 +7,352 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `local` - local
+ * * `cloud` - cloud
+ */
+export type RunEnvironmentEnumApi = (typeof RunEnvironmentEnumApi)[keyof typeof RunEnvironmentEnumApi]
+
+export const RunEnvironmentEnumApi = {
+ Local: 'local',
+ Cloud: 'cloud',
+} as const
+
+export interface WizardProgramApi {
+ /** Stable identifier used to select the program. */
+ readonly id: string
+ /** Display name of the program. */
+ readonly name: string
+ /** What the program does. */
+ readonly description: string
+ /** Exact Wizard package version used by the program. */
+ readonly wizard_version: string
+ /** Wizard CLI arguments used to start the program. */
+ readonly command: readonly string[]
+ /** Labels that categorize the program. */
+ readonly tags: readonly string[]
+ /** Programs that should run before this program. */
+ readonly required_programs: readonly string[]
+ /** Environments where the program can run. */
+ readonly supported_environments: readonly RunEnvironmentEnumApi[]
+}
+
+export interface PaginatedWizardProgramListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WizardProgramApi[]
+}
+
+/**
+ * Selects a folder on the user's machine as the workspace.
+ */
+export type LocalFolderWorkspaceApiType = (typeof LocalFolderWorkspaceApiType)[keyof typeof LocalFolderWorkspaceApiType]
+
+export const LocalFolderWorkspaceApiType = {
+ LocalFolder: 'local_folder',
+} as const
+
+export interface LocalFolderWorkspaceApi {
+ /** Selects a folder on the user's machine as the workspace. */
+ type: LocalFolderWorkspaceApiType
+ /**
+ * Name of the project in the local folder.
+ * @maxLength 255
+ */
+ project_name: string
+}
+
+/**
+ * Selects a GitHub repository as the workspace.
+ */
+export type GitRepositoryWorkspaceApiType =
+ (typeof GitRepositoryWorkspaceApiType)[keyof typeof GitRepositoryWorkspaceApiType]
+
+export const GitRepositoryWorkspaceApiType = {
+ GitRepository: 'git_repository',
+} as const
+
+export interface GitRepositoryWorkspaceApi {
+ /** Selects a GitHub repository as the workspace. */
+ type: GitRepositoryWorkspaceApiType
+ /**
+ * GitHub repository in owner/name format.
+ * @maxLength 255
+ */
+ repository: string
+}
+
+export type WizardWorkspaceApi = LocalFolderWorkspaceApi | GitRepositoryWorkspaceApi
+
+/**
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled
+ */
+export type WizardRunStatusEnumApi = (typeof WizardRunStatusEnumApi)[keyof typeof WizardRunStatusEnumApi]
+
+export const WizardRunStatusEnumApi = {
+ Created: 'created',
+ Running: 'running',
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+} as const
+
+/**
+ * * `dispatching` - dispatching
+ * * `provisioning` - provisioning
+ * * `preparing_workspace` - preparing_workspace
+ * * `executing_wizard` - executing_wizard
+ * * `creating_artifacts` - creating_artifacts
+ */
+export type WizardRunStageEnumApi = (typeof WizardRunStageEnumApi)[keyof typeof WizardRunStageEnumApi]
+
+export const WizardRunStageEnumApi = {
+ Dispatching: 'dispatching',
+ Provisioning: 'provisioning',
+ PreparingWorkspace: 'preparing_workspace',
+ ExecutingWizard: 'executing_wizard',
+ CreatingArtifacts: 'creating_artifacts',
+} as const
+
+export interface WizardRunApi {
+ /** Unique ID of the Wizard run. */
+ readonly id: string
+ /** Project that owns the Wizard run. */
+ readonly team_id: number
+ /**
+ * User who created the Wizard run, or null if that user no longer exists.
+ * @nullable
+ */
+ readonly created_by_id: number | null
+ /** Where the setup agent runs.
+ *
+ * * `local` - local
+ * * `cloud` - cloud */
+ readonly environment: RunEnvironmentEnumApi
+ /** Project that the setup agent works on. */
+ readonly workspace: WizardWorkspaceApi
+ /** Registry program selected for this run. */
+ readonly program: WizardProgramApi
+ /** Current lifecycle status of the Wizard run.
+ *
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ readonly status: WizardRunStatusEnumApi
+ /**
+ * Machine-readable failure reason, or null if the run has not failed.
+ * @nullable
+ */
+ readonly error_code: string | null
+ /**
+ * Safe failure explanation, or null if the run has not failed.
+ * @nullable
+ */
+ readonly error_message: string | null
+ /** Current cloud worker stage, or null outside active cloud execution.
+ *
+ * * `dispatching` - dispatching
+ * * `provisioning` - provisioning
+ * * `preparing_workspace` - preparing_workspace
+ * * `executing_wizard` - executing_wizard
+ * * `creating_artifacts` - creating_artifacts */
+ readonly stage: WizardRunStageEnumApi | null
+ /** When the Wizard run was created. */
+ readonly created_at: string
+ /**
+ * When the run last changed.
+ * @nullable
+ */
+ readonly updated_at: string | null
+ /**
+ * When execution started, or null while queued.
+ * @nullable
+ */
+ readonly started_at: string | null
+ /**
+ * When execution reached a terminal status, or null while active.
+ * @nullable
+ */
+ readonly finished_at: string | null
+ /**
+ * Cloud execution deadline, or null for local runs.
+ * @nullable
+ */
+ readonly deadline_at: string | null
+}
+
+export interface PaginatedWizardRunListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WizardRunApi[]
+}
+
+export interface WizardRunCreateRequestApi {
+ /**
+ * Registry program to run.
+ * @pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$
+ */
+ program_id: string
+ /** Where the setup agent runs.
+ *
+ * * `local` - local
+ * * `cloud` - cloud */
+ environment: RunEnvironmentEnumApi
+ /** Project that the setup agent works on. */
+ workspace: WizardWorkspaceApi
+ /**
+ * Unique key that makes cloud run creation safe to retry.
+ * @maxLength 255
+ */
+ idempotency_key?: string
+ /** Wizard package version to run. Defaults to the backend pin and accepts latest explicitly. */
+ wizard_version?: string
+}
+
+export interface WizardRunErrorApi {
+ /** Error category. */
+ readonly type: string
+ /** Machine-readable error code. */
+ readonly code: string
+ /** What happened and how to continue. */
+ readonly detail: string
+ /**
+ * Request field associated with the error, when available.
+ * @nullable
+ */
+ readonly attr: string | null
+}
+
+/**
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled
+ */
+export type WizardRunStatusUpdateRequestStatusEnumApi =
+ (typeof WizardRunStatusUpdateRequestStatusEnumApi)[keyof typeof WizardRunStatusUpdateRequestStatusEnumApi]
+
+export const WizardRunStatusUpdateRequestStatusEnumApi = {
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+} as const
+
+export interface PatchedWizardRunStatusUpdateRequestApi {
+ /** New terminal status for the Wizard run.
+ *
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ status?: WizardRunStatusUpdateRequestStatusEnumApi
+ /**
+ * Machine-readable reason the Wizard run failed.
+ * @maxLength 50
+ * @nullable
+ */
+ error_code?: string | null
+}
+
+/**
+ * Format of the changes produced by the run.
+ *
+ * * `git_diff` - git_diff
+ */
+export type WizardRunGitDiffArtifactApiArtifactType =
+ (typeof WizardRunGitDiffArtifactApiArtifactType)[keyof typeof WizardRunGitDiffArtifactApiArtifactType]
+
+export const WizardRunGitDiffArtifactApiArtifactType = {
+ GitDiff: 'git_diff',
+} as const
+
+export interface WizardRunGitDiffArtifactApi {
+ /** Unique ID of the run artifact. */
+ readonly id: string
+ /** Project that owns the run artifact. */
+ readonly team_id: number
+ /** Wizard run that produced the artifact. */
+ readonly run_id: string
+ /** Format of the changes produced by the run.
+ *
+ * * `git_diff` - git_diff */
+ readonly artifact_type: WizardRunGitDiffArtifactApiArtifactType
+ /** Stored artifact size in bytes. */
+ readonly size_bytes: number
+ /** SHA-256 hash of the stored artifact content. */
+ readonly content_hash: string
+ /**
+ * Number of added lines in the diff.
+ * @nullable
+ */
+ readonly additions: number | null
+ /**
+ * Number of removed lines in the diff.
+ * @nullable
+ */
+ readonly removals: number | null
+ /** Time when the artifact was stored. */
+ readonly created_at: string
+}
+
+/**
+ * Format of the changes produced by the run.
+ *
+ * * `pull_request` - pull_request
+ */
+export type WizardRunPullRequestArtifactApiArtifactType =
+ (typeof WizardRunPullRequestArtifactApiArtifactType)[keyof typeof WizardRunPullRequestArtifactApiArtifactType]
+
+export const WizardRunPullRequestArtifactApiArtifactType = {
+ PullRequest: 'pull_request',
+} as const
+
+export interface WizardRunPullRequestArtifactApi {
+ /** Unique ID of the run artifact. */
+ readonly id: string
+ /** Project that owns the run artifact. */
+ readonly team_id: number
+ /** Wizard run that produced the artifact. */
+ readonly run_id: string
+ /** Format of the changes produced by the run.
+ *
+ * * `pull_request` - pull_request */
+ readonly artifact_type: WizardRunPullRequestArtifactApiArtifactType
+ /** GitHub URL of the pull request. */
+ readonly url: string
+ /** Repository-local pull request number. */
+ readonly number: number
+ /** GitHub repository in owner/name format. */
+ readonly repository: string
+ /** Branch containing the setup agent's changes. */
+ readonly head_branch: string
+ /** Branch that the pull request targets. */
+ readonly base_branch: string
+ /** Time when the artifact was stored. */
+ readonly created_at: string
+}
+
+export type WizardRunArtifactApi = WizardRunGitDiffArtifactApi | WizardRunPullRequestArtifactApi
+
+export interface PaginatedWizardRunArtifactListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WizardRunArtifactApi[]
+}
+
/**
* The in-flight `wizard_ask` question. Typed rather than a free-form dict so the shape the
* widget renders is enforced at the edge instead of trusted from the producer.
@@ -107,11 +453,11 @@ export interface WizardSessionDTOApi {
/** @nullable */
error: WizardSessionDTOApiError
/**
- * Markdown handoff doc the wizard produced for this run (its setup report), or null while the run hasn't written one. Sticky once set.
+ * Markdown handoff doc the wizard produced for this run (its setup report), or null while the run hasn't written one.
* @nullable
*/
handoff_text: string | null
- /** The user who initiated this wizard run (null for runs created before attribution existed). Lets the UI name whose run it is. */
+ /** The user who initiated this wizard run (null for runs created before attribution existed). */
created_by: WizardSessionUserDTOApi | null
created_at: string
updated_at: string
@@ -188,7 +534,27 @@ export interface UpsertWizardSessionRequestApi {
error?: UpsertWizardSessionRequestApiError
}
-export type WizardSessionsListParams = {
+/**
+ * * `git_diff` - git_diff
+ */
+export type WizardRunGitDiffArtifactArtifactTypeEnumApi =
+ (typeof WizardRunGitDiffArtifactArtifactTypeEnumApi)[keyof typeof WizardRunGitDiffArtifactArtifactTypeEnumApi]
+
+export const WizardRunGitDiffArtifactArtifactTypeEnumApi = {
+ GitDiff: 'git_diff',
+} as const
+
+/**
+ * * `pull_request` - pull_request
+ */
+export type WizardRunPullRequestArtifactArtifactTypeEnumApi =
+ (typeof WizardRunPullRequestArtifactArtifactTypeEnumApi)[keyof typeof WizardRunPullRequestArtifactArtifactTypeEnumApi]
+
+export const WizardRunPullRequestArtifactArtifactTypeEnumApi = {
+ PullRequest: 'pull_request',
+} as const
+
+export type WizardRegistryListParams = {
/**
* Number of results to return per page.
*/
@@ -197,28 +563,73 @@ export type WizardSessionsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+}
+
+export type WizardRunsListParams = {
/**
- * Filter to a single skill within the workflow (e.g. 'nextjs').
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type WizardRunsArtifactsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type WizardSessionsListParams = {
+ /**
+ * Maximum number of sessions to return.
+ * @minimum 0
+ * @maximum 200
+ */
+ limit?: number
+ /**
+ * Number of sessions to skip.
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Return sessions for this skill only.
*/
skill_id?: string
/**
- * Filter to a single workflow (e.g. 'onboarding').
+ * Return sessions for this workflow only.
+ * @minLength 1
*/
workflow_id?: string
}
export type WizardSessionsLatestRetrieveParams = {
/**
- * Filter to a single skill within the workflow (e.g. 'nextjs').
+ * Optional skill within the workflow.
*/
skill_id?: string
/**
- * Filter to a single workflow (e.g. 'posthog-integration').
+ * Workflow to inspect.
+ * @minLength 1
*/
workflow_id: string
}
export type WizardSessionsStreamRetrieveParams = {
+ /**
+ * Optional skill within the workflow.
+ */
skill_id?: string
+ /**
+ * Workflow to inspect.
+ * @minLength 1
+ */
workflow_id: string
}
diff --git a/products/wizard/frontend/generated/api.ts b/products/wizard/frontend/generated/api.ts
index 71f828cc2661..026daf48eecc 100644
--- a/products/wizard/frontend/generated/api.ts
+++ b/products/wizard/frontend/generated/api.ts
@@ -9,14 +9,196 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ PaginatedWizardProgramListApi,
+ PaginatedWizardRunArtifactListApi,
+ PaginatedWizardRunListApi,
PaginatedWizardSessionDTOListApi,
+ PatchedWizardRunStatusUpdateRequestApi,
UpsertWizardSessionRequestApi,
+ WizardRegistryListParams,
+ WizardRunApi,
+ WizardRunCreateRequestApi,
+ WizardRunsArtifactsListParams,
+ WizardRunsListParams,
WizardSessionDTOApi,
WizardSessionsLatestRetrieveParams,
WizardSessionsListParams,
WizardSessionsStreamRetrieveParams,
} from './api.schemas'
+export const getWizardRegistryListUrl = (projectId: string, params?: WizardRegistryListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/wizard/registry/?${stringifiedParams}`
+ : `/api/projects/${projectId}/wizard/registry/`
+}
+
+/**
+ * List Wizard programs available for this project.
+ */
+export const wizardRegistryList = async (
+ projectId: string,
+ params?: WizardRegistryListParams,
+ options?: RequestInit
+): Promise<PaginatedWizardProgramListApi> => {
+ return apiMutator<PaginatedWizardProgramListApi>(getWizardRegistryListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWizardRunsListUrl = (projectId: string, params?: WizardRunsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/wizard/runs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/wizard/runs/`
+}
+
+/**
+ * List Wizard runs for this project, ordered from newest to oldest.
+ */
+export const wizardRunsList = async (
+ projectId: string,
+ params?: WizardRunsListParams,
+ options?: RequestInit
+): Promise<PaginatedWizardRunListApi> => {
+ return apiMutator<PaginatedWizardRunListApi>(getWizardRunsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWizardRunsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/wizard/runs/`
+}
+
+/**
+ * Create a local or cloud Wizard run for a project workspace.
+ */
+export const wizardRunsCreate = async (
+ projectId: string,
+ wizardRunCreateRequestApi: WizardRunCreateRequestApi,
+ options?: RequestInit
+): Promise<WizardRunApi> => {
+ return apiMutator<WizardRunApi>(getWizardRunsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(wizardRunCreateRequestApi),
+ })
+}
+
+export const getWizardRunsRetrieveUrl = (projectId: string, runId: string) => {
+ return `/api/projects/${projectId}/wizard/runs/${runId}/`
+}
+
+/**
+ * Retrieve a Wizard run in this project.
+ */
+export const wizardRunsRetrieve = async (
+ projectId: string,
+ runId: string,
+ options?: RequestInit
+): Promise<WizardRunApi> => {
+ return apiMutator<WizardRunApi>(getWizardRunsRetrieveUrl(projectId, runId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWizardRunsPartialUpdateUrl = (projectId: string, runId: string) => {
+ return `/api/projects/${projectId}/wizard/runs/${runId}/`
+}
+
+/**
+ * Change the terminal status of a local Wizard run.
+ */
+export const wizardRunsPartialUpdate = async (
+ projectId: string,
+ runId: string,
+ patchedWizardRunStatusUpdateRequestApi?: PatchedWizardRunStatusUpdateRequestApi,
+ options?: RequestInit
+): Promise<WizardRunApi> => {
+ return apiMutator<WizardRunApi>(getWizardRunsPartialUpdateUrl(projectId, runId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedWizardRunStatusUpdateRequestApi),
+ })
+}
+
+export const getWizardRunsArtifactsListUrl = (
+ projectId: string,
+ runId: string,
+ params?: WizardRunsArtifactsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/wizard/runs/${runId}/artifacts/?${stringifiedParams}`
+ : `/api/projects/${projectId}/wizard/runs/${runId}/artifacts/`
+}
+
+/**
+ * List metadata for artifacts produced by a Wizard run.
+ */
+export const wizardRunsArtifactsList = async (
+ projectId: string,
+ runId: string,
+ params?: WizardRunsArtifactsListParams,
+ options?: RequestInit
+): Promise<PaginatedWizardRunArtifactListApi> => {
+ return apiMutator<PaginatedWizardRunArtifactListApi>(getWizardRunsArtifactsListUrl(projectId, runId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWizardRunsArtifactsContentRetrieveUrl = (projectId: string, runId: string, id: string) => {
+ return `/api/projects/${projectId}/wizard/runs/${runId}/artifacts/${id}/content/`
+}
+
+/**
+ * Get the unified git diff stored for a Wizard run artifact.
+ */
+export const wizardRunsArtifactsContentRetrieve = async (
+ projectId: string,
+ runId: string,
+ id: string,
+ options?: RequestInit
+): Promise<string> => {
+ return apiMutator<string>(getWizardRunsArtifactsContentRetrieveUrl(projectId, runId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getWizardSessionsListUrl = (projectId: string, params?: WizardSessionsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/wizard/frontend/generated/api.zod.ts b/products/wizard/frontend/generated/api.zod.ts
index 61607177ffa5..1b0ae62d3768 100644
--- a/products/wizard/frontend/generated/api.zod.ts
+++ b/products/wizard/frontend/generated/api.zod.ts
@@ -9,6 +9,71 @@
*/
import * as zod from 'zod'
+/**
+ * Create a local or cloud Wizard run for a project workspace.
+ */
+export const wizardRunsCreateBodyProgramIdRegExp = new RegExp('^[a-z0-9]+(?:-[a-z0-9]+)\*$')
+export const wizardRunsCreateBodyWorkspaceOneOneProjectNameMax = 255
+
+export const wizardRunsCreateBodyWorkspaceOneTwoRepositoryMax = 255
+
+export const wizardRunsCreateBodyIdempotencyKeyMax = 255
+
+export const WizardRunsCreateBody = /* @__PURE__ */ zod.object({
+ program_id: zod.string().regex(wizardRunsCreateBodyProgramIdRegExp).describe('Registry program to run.'),
+ environment: zod
+ .enum(['local', 'cloud'])
+ .describe('\* `local` - local\n\* `cloud` - cloud')
+ .describe('Where the setup agent runs.\n\n\* `local` - local\n\* `cloud` - cloud'),
+ workspace: zod
+ .union([
+ zod.object({
+ type: zod.enum(['local_folder']).describe("Selects a folder on the user's machine as the workspace."),
+ project_name: zod
+ .string()
+ .max(wizardRunsCreateBodyWorkspaceOneOneProjectNameMax)
+ .describe('Name of the project in the local folder.'),
+ }),
+ zod.object({
+ type: zod.enum(['git_repository']).describe('Selects a GitHub repository as the workspace.'),
+ repository: zod
+ .string()
+ .max(wizardRunsCreateBodyWorkspaceOneTwoRepositoryMax)
+ .describe('GitHub repository in owner\/name format.'),
+ }),
+ ])
+ .describe('Project that the setup agent works on.'),
+ idempotency_key: zod
+ .string()
+ .max(wizardRunsCreateBodyIdempotencyKeyMax)
+ .optional()
+ .describe('Unique key that makes cloud run creation safe to retry.'),
+ wizard_version: zod
+ .string()
+ .optional()
+ .describe('Wizard package version to run. Defaults to the backend pin and accepts latest explicitly.'),
+})
+
+/**
+ * Change the terminal status of a local Wizard run.
+ */
+export const wizardRunsPartialUpdateBodyErrorCodeMax = 50
+
+export const WizardRunsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ status: zod
+ .enum(['completed', 'failed', 'cancelled'])
+ .describe('\* `completed` - completed\n\* `failed` - failed\n\* `cancelled` - cancelled')
+ .optional()
+ .describe(
+ 'New terminal status for the Wizard run.\n\n\* `completed` - completed\n\* `failed` - failed\n\* `cancelled` - cancelled'
+ ),
+ error_code: zod
+ .string()
+ .max(wizardRunsPartialUpdateBodyErrorCodeMax)
+ .nullish()
+ .describe('Machine-readable reason the Wizard run failed.'),
+})
+
/**
* 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.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 951ecab1c50d..ac6ddd6e6209 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10624,10 +10624,10 @@ export namespace Schemas {
* * `file` - file
* * `github_pr` - github_pr
*/
- export type ArtifactTypeEnum = typeof ArtifactTypeEnum[keyof typeof ArtifactTypeEnum];
+ export type ArtifactType2f0Enum = typeof ArtifactType2f0Enum[keyof typeof ArtifactType2f0Enum];
- export const ArtifactTypeEnum = {
+ export const ArtifactType2f0Enum = {
SlackMessage: 'slack_message',
SlackCanvas: 'slack_canvas',
Document: 'document',
@@ -42098,6 +42098,26 @@ export namespace Schemas {
error?: string;
}
+ /**
+ * Selects a GitHub repository as the workspace.
+ */
+ export type GitRepositoryWorkspaceType = typeof GitRepositoryWorkspaceType[keyof typeof GitRepositoryWorkspaceType];
+
+
+ export const GitRepositoryWorkspaceType = {
+ GitRepository: 'git_repository',
+ } as const;
+
+ export interface GitRepositoryWorkspace {
+ /** Selects a GitHub repository as the workspace. */
+ type: GitRepositoryWorkspaceType;
+ /**
+ * GitHub repository in owner/name format.
+ * @maxLength 255
+ */
+ repository: string;
+ }
+
export interface GiteaIssueSignalExtra {
state: string | null;
labels: unknown[];
@@ -49102,6 +49122,26 @@ export namespace Schemas {
url: string;
}
+ /**
+ * Selects a folder on the user's machine as the workspace.
+ */
+ export type LocalFolderWorkspaceType = typeof LocalFolderWorkspaceType[keyof typeof LocalFolderWorkspaceType];
+
+
+ export const LocalFolderWorkspaceType = {
+ LocalFolder: 'local_folder',
+ } as const;
+
+ export interface LocalFolderWorkspace {
+ /** Selects a folder on the user's machine as the workspace. */
+ type: LocalFolderWorkspaceType;
+ /**
+ * Name of the project in the local folder.
+ * @maxLength 255
+ */
+ project_name: string;
+ }
+
export interface LogsAlertFilters {
filterGroup?: PropertyGroupFilter | null;
serviceNames?: string[] | null;
@@ -61184,6 +61224,251 @@ export namespace Schemas {
results: WebExperimentsAPI[];
}
+ /**
+ * * `local` - local
+ * * `cloud` - cloud
+ */
+ export type RunEnvironmentEnum = typeof RunEnvironmentEnum[keyof typeof RunEnvironmentEnum];
+
+
+ export const RunEnvironmentEnum = {
+ Local: 'local',
+ Cloud: 'cloud',
+ } as const;
+
+ export interface WizardProgram {
+ /** Stable identifier used to select the program. */
+ readonly id: string;
+ /** Display name of the program. */
+ readonly name: string;
+ /** What the program does. */
+ readonly description: string;
+ /** Exact Wizard package version used by the program. */
+ readonly wizard_version: string;
+ /** Wizard CLI arguments used to start the program. */
+ readonly command: readonly string[];
+ /** Labels that categorize the program. */
+ readonly tags: readonly string[];
+ /** Programs that should run before this program. */
+ readonly required_programs: readonly string[];
+ /** Environments where the program can run. */
+ readonly supported_environments: readonly RunEnvironmentEnum[];
+ }
+
+ export interface PaginatedWizardProgramList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: WizardProgram[];
+ }
+
+ /**
+ * Format of the changes produced by the run.
+ *
+ * * `git_diff` - git_diff
+ */
+ export type WizardRunGitDiffArtifactArtifactType = typeof WizardRunGitDiffArtifactArtifactType[keyof typeof WizardRunGitDiffArtifactArtifactType];
+
+
+ export const WizardRunGitDiffArtifactArtifactType = {
+ GitDiff: 'git_diff',
+ } as const;
+
+ export interface WizardRunGitDiffArtifact {
+ /** Unique ID of the run artifact. */
+ readonly id: string;
+ /** Project that owns the run artifact. */
+ readonly team_id: number;
+ /** Wizard run that produced the artifact. */
+ readonly run_id: string;
+ /** Format of the changes produced by the run.
+ *
+ * * `git_diff` - git_diff */
+ readonly artifact_type: WizardRunGitDiffArtifactArtifactType;
+ /** Stored artifact size in bytes. */
+ readonly size_bytes: number;
+ /** SHA-256 hash of the stored artifact content. */
+ readonly content_hash: string;
+ /**
+ * Number of added lines in the diff.
+ * @nullable
+ */
+ readonly additions: number | null;
+ /**
+ * Number of removed lines in the diff.
+ * @nullable
+ */
+ readonly removals: number | null;
+ /** Time when the artifact was stored. */
+ readonly created_at: string;
+ }
+
+ /**
+ * Format of the changes produced by the run.
+ *
+ * * `pull_request` - pull_request
+ */
+ export type WizardRunPullRequestArtifactArtifactType = typeof WizardRunPullRequestArtifactArtifactType[keyof typeof WizardRunPullRequestArtifactArtifactType];
+
+
+ export const WizardRunPullRequestArtifactArtifactType = {
+ PullRequest: 'pull_request',
+ } as const;
+
+ export interface WizardRunPullRequestArtifact {
+ /** Unique ID of the run artifact. */
+ readonly id: string;
+ /** Project that owns the run artifact. */
+ readonly team_id: number;
+ /** Wizard run that produced the artifact. */
+ readonly run_id: string;
+ /** Format of the changes produced by the run.
+ *
+ * * `pull_request` - pull_request */
+ readonly artifact_type: WizardRunPullRequestArtifactArtifactType;
+ /** GitHub URL of the pull request. */
+ readonly url: string;
+ /** Repository-local pull request number. */
+ readonly number: number;
+ /** GitHub repository in owner/name format. */
+ readonly repository: string;
+ /** Branch containing the setup agent's changes. */
+ readonly head_branch: string;
+ /** Branch that the pull request targets. */
+ readonly base_branch: string;
+ /** Time when the artifact was stored. */
+ readonly created_at: string;
+ }
+
+ export type WizardRunArtifact = WizardRunGitDiffArtifact | WizardRunPullRequestArtifact;
+
+ export interface PaginatedWizardRunArtifactList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: WizardRunArtifact[];
+ }
+
+ export type WizardWorkspace = LocalFolderWorkspace | GitRepositoryWorkspace;
+
+ /**
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled
+ */
+ export type WizardRunStatusEnum = typeof WizardRunStatusEnum[keyof typeof WizardRunStatusEnum];
+
+
+ export const WizardRunStatusEnum = {
+ Created: 'created',
+ Running: 'running',
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+ } as const;
+
+ /**
+ * * `dispatching` - dispatching
+ * * `provisioning` - provisioning
+ * * `preparing_workspace` - preparing_workspace
+ * * `executing_wizard` - executing_wizard
+ * * `creating_artifacts` - creating_artifacts
+ */
+ export type WizardRunStageEnum = typeof WizardRunStageEnum[keyof typeof WizardRunStageEnum];
+
+
+ export const WizardRunStageEnum = {
+ Dispatching: 'dispatching',
+ Provisioning: 'provisioning',
+ PreparingWorkspace: 'preparing_workspace',
+ ExecutingWizard: 'executing_wizard',
+ CreatingArtifacts: 'creating_artifacts',
+ } as const;
+
+ export interface WizardRun {
+ /** Unique ID of the Wizard run. */
+ readonly id: string;
+ /** Project that owns the Wizard run. */
+ readonly team_id: number;
+ /**
+ * User who created the Wizard run, or null if that user no longer exists.
+ * @nullable
+ */
+ readonly created_by_id: number | null;
+ /** Where the setup agent runs.
+ *
+ * * `local` - local
+ * * `cloud` - cloud */
+ readonly environment: RunEnvironmentEnum;
+ /** Project that the setup agent works on. */
+ readonly workspace: WizardWorkspace;
+ /** Registry program selected for this run. */
+ readonly program: WizardProgram;
+ /** Current lifecycle status of the Wizard run.
+ *
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ readonly status: WizardRunStatusEnum;
+ /**
+ * Machine-readable failure reason, or null if the run has not failed.
+ * @nullable
+ */
+ readonly error_code: string | null;
+ /**
+ * Safe failure explanation, or null if the run has not failed.
+ * @nullable
+ */
+ readonly error_message: string | null;
+ /** Current cloud worker stage, or null outside active cloud execution.
+ *
+ * * `dispatching` - dispatching
+ * * `provisioning` - provisioning
+ * * `preparing_workspace` - preparing_workspace
+ * * `executing_wizard` - executing_wizard
+ * * `creating_artifacts` - creating_artifacts */
+ readonly stage: WizardRunStageEnum | null;
+ /** When the Wizard run was created. */
+ readonly created_at: string;
+ /**
+ * When the run last changed.
+ * @nullable
+ */
+ readonly updated_at: string | null;
+ /**
+ * When execution started, or null while queued.
+ * @nullable
+ */
+ readonly started_at: string | null;
+ /**
+ * When execution reached a terminal status, or null while active.
+ * @nullable
+ */
+ readonly finished_at: string | null;
+ /**
+ * Cloud execution deadline, or null for local runs.
+ * @nullable
+ */
+ readonly deadline_at: string | null;
+ }
+
+ export interface PaginatedWizardRunList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: WizardRun[];
+ }
+
/**
* The in-flight `wizard_ask` question. Typed rather than a free-form dict so the shape the
* widget renders is enforced at the edge instead of trusted from the producer.
@@ -61286,11 +61571,11 @@ export namespace Schemas {
/** @nullable */
error: WizardSessionDTOError;
/**
- * Markdown handoff doc the wizard produced for this run (its setup report), or null while the run hasn't written one. Sticky once set.
+ * Markdown handoff doc the wizard produced for this run (its setup report), or null while the run hasn't written one.
* @nullable
*/
handoff_text: string | null;
- /** The user who initiated this wizard run (null for runs created before attribution existed). Lets the UI name whose run it is. */
+ /** The user who initiated this wizard run (null for runs created before attribution existed). */
created_by: WizardSessionUserDTO | null;
created_at: string;
updated_at: string;
@@ -69717,6 +70002,35 @@ export namespace Schemas {
variants?: unknown;
}
+ /**
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled
+ */
+ export type WizardRunStatusUpdateRequestStatusEnum = typeof WizardRunStatusUpdateRequestStatusEnum[keyof typeof WizardRunStatusUpdateRequestStatusEnum];
+
+
+ export const WizardRunStatusUpdateRequestStatusEnum = {
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+ } as const;
+
+ export interface PatchedWizardRunStatusUpdateRequest {
+ /** New terminal status for the Wizard run.
+ *
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ status?: WizardRunStatusUpdateRequestStatusEnum;
+ /**
+ * Machine-readable reason the Wizard run failed.
+ * @maxLength 50
+ * @nullable
+ */
+ error_code?: string | null;
+ }
+
export interface PathCleaningPreviewExample {
/** A real sampled path before the suggested rules are applied. */
before: string;
@@ -85902,18 +86216,6 @@ export namespace Schemas {
artifacts: TaskRunArtifactResponse[];
}
- /**
- * * `local` - local
- * * `cloud` - cloud
- */
- export type TaskRunBootstrapCreateRequestEnvironmentEnum = typeof TaskRunBootstrapCreateRequestEnvironmentEnum[keyof typeof TaskRunBootstrapCreateRequestEnvironmentEnum];
-
-
- export const TaskRunBootstrapCreateRequestEnvironmentEnum = {
- Local: 'local',
- Cloud: 'cloud',
- } as const;
-
/**
* Request body for creating a task run without starting execution yet.
*/
@@ -85932,7 +86234,7 @@ export namespace Schemas {
*
* * `local` - local
* * `cloud` - cloud */
- environment?: TaskRunBootstrapCreateRequestEnvironmentEnum;
+ environment?: RunEnvironmentEnum;
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -86223,7 +86525,7 @@ export namespace Schemas {
* * `dashboard` - dashboard
* * `file` - file
* * `github_pr` - github_pr */
- artifact_type: ArtifactTypeEnum;
+ artifact_type: ArtifactType2f0Enum;
/** Adapter that currently stores or edits the artifact.
*
* * `slack_message` - slack_message
@@ -86289,7 +86591,7 @@ export namespace Schemas {
* * `dashboard` - dashboard
* * `file` - file
* * `github_pr` - github_pr */
- artifact_type?: ArtifactTypeEnum;
+ artifact_type?: ArtifactType2f0Enum;
/** Optional preferred external storage or delivery adapter. Slack adapters deliver into the mapped Slack thread; omitted Slack-run documents use Slack canvas, omitted Slack-run files and spreadsheets use Slack file upload, and document_connector uses a connected external document provider.
*
* * `slack_message` - slack_message
@@ -86371,7 +86673,7 @@ export namespace Schemas {
* * `dashboard` - dashboard
* * `file` - file
* * `github_pr` - github_pr */
- artifact_type: ArtifactTypeEnum;
+ artifact_type: ArtifactType2f0Enum;
/** Adapter that currently stores or edits the artifact.
*
* * `slack_message` - slack_message
@@ -89030,6 +89332,62 @@ export namespace Schemas {
started_at?: string | null;
}
+ export interface WizardRunCreateRequest {
+ /**
+ * Registry program to run.
+ * @pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$
+ */
+ program_id: string;
+ /** Where the setup agent runs.
+ *
+ * * `local` - local
+ * * `cloud` - cloud */
+ environment: RunEnvironmentEnum;
+ /** Project that the setup agent works on. */
+ workspace: WizardWorkspace;
+ /**
+ * Unique key that makes cloud run creation safe to retry.
+ * @maxLength 255
+ */
+ idempotency_key?: string;
+ /** Wizard package version to run. Defaults to the backend pin and accepts latest explicitly. */
+ wizard_version?: string;
+ }
+
+ export interface WizardRunError {
+ /** Error category. */
+ readonly type: string;
+ /** Machine-readable error code. */
+ readonly code: string;
+ /** What happened and how to continue. */
+ readonly detail: string;
+ /**
+ * Request field associated with the error, when available.
+ * @nullable
+ */
+ readonly attr: string | null;
+ }
+
+ /**
+ * * `git_diff` - git_diff
+ */
+ export type WizardRunGitDiffArtifactArtifactTypeEnum = typeof WizardRunGitDiffArtifactArtifactTypeEnum[keyof typeof WizardRunGitDiffArtifactArtifactTypeEnum];
+
+
+ export const WizardRunGitDiffArtifactArtifactTypeEnum = {
+ GitDiff: 'git_diff',
+ } as const;
+
+ /**
+ * * `pull_request` - pull_request
+ */
+ export type WizardRunPullRequestArtifactArtifactTypeEnum = typeof WizardRunPullRequestArtifactArtifactTypeEnum[keyof typeof WizardRunPullRequestArtifactArtifactTypeEnum];
+
+
+ export const WizardRunPullRequestArtifactArtifactTypeEnum = {
+ PullRequest: 'pull_request',
+ } as const;
+
export interface WorkflowHealthBucket {
/** Bucket start, aligned to the item's granularity (top of hour, midnight, or Monday). */
bucket_start: string;
@@ -102794,7 +103152,18 @@ export namespace Schemas {
export type WebVitalsRetrieve200 = { [key: string]: unknown };
- export type WizardSessionsListParams = {
+ export type WizardRegistryListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type WizardRunsListParams = {
/**
* Number of results to return per page.
*/
@@ -102803,29 +103172,63 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ };
+
+ export type WizardRunsArtifactsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type WizardSessionsListParams = {
+ /**
+ * Maximum number of sessions to return.
+ * @minimum 0
+ * @maximum 200
+ */
+ limit?: number;
+ /**
+ * Number of sessions to skip.
+ * @minimum 0
+ */
+ offset?: number;
/**
- * Filter to a single skill within the workflow (e.g. 'nextjs').
+ * Return sessions for this skill only.
*/
skill_id?: string;
/**
- * Filter to a single workflow (e.g. 'onboarding').
+ * Return sessions for this workflow only.
+ * @minLength 1
*/
workflow_id?: string;
};
export type WizardSessionsLatestRetrieveParams = {
/**
- * Filter to a single skill within the workflow (e.g. 'nextjs').
+ * Optional skill within the workflow.
*/
skill_id?: string;
/**
- * Filter to a single workflow (e.g. 'posthog-integration').
+ * Workflow to inspect.
+ * @minLength 1
*/
workflow_id: string;
};
export type WizardSessionsStreamRetrieveParams = {
+ /**
+ * Optional skill within the workflow.
+ */
skill_id?: string;
+ /**
+ * Workflow to inspect.
+ * @minLength 1
+ */
workflow_id: string;
};