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): store codebase scans the wizard reports (#115757)

Rafael Audibert85d4833f958b
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 98070d1d2426..2d5e03b14713 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -460,8 +460,10 @@ rules:
|WebAnalyticsFilterPreset
|WebAnalyticsInteraction
|WebAnalyticsVisit
+ |WizardDetectedTool
|WizardRun
|WizardRunArtifact
+ |WizardScan
|WizardSession
|WizardWorker
|WorkflowProposal
@@ -913,8 +915,10 @@ rules:
|WebAnalyticsFilterPreset
|WebAnalyticsInteraction
|WebAnalyticsVisit
+ |WizardDetectedTool
|WizardRun
|WizardRunArtifact
+ |WizardScan
|WizardSession
|WizardWorker
|WorkflowProposal
diff --git a/products/wizard/backend/facade/api.py b/products/wizard/backend/facade/api.py
index 0bc3be95d42a..a68edad3aff3 100644
--- a/products/wizard/backend/facade/api.py
+++ b/products/wizard/backend/facade/api.py
@@ -20,6 +20,7 @@ from products.wizard.backend.facade.contracts import (
CreatePullRequestArtifactInput,
CreateWizardRunInput,
ListWizardRunsInput,
+ RecordWizardScanInput,
UpdateWizardRunTaskInput,
UpsertWizardSessionInput,
WizardProgram,
@@ -30,6 +31,7 @@ from products.wizard.backend.facade.contracts import (
WizardRunPage,
WizardRunPullRequestArtifactDTO,
WizardRunTaskDTO,
+ WizardScanResult,
WizardSessionDTO,
)
from products.wizard.backend.facade.enums import WizardRunStage, WizardRunStatus
@@ -37,6 +39,7 @@ from products.wizard.backend.facade.validation import validate_wizard_version as
from products.wizard.backend.logic import (
registry as registry_service,
runs as run_service,
+ scans,
sessions,
)
from products.wizard.backend.logic.artifacts import service as artifacts
@@ -49,6 +52,10 @@ def upsert(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO, bool]:
return sessions.upsert_session(params)
+def record_scan(params: RecordWizardScanInput) -> WizardScanResult:
+ return scans.record_scan(params)
+
+
def get(team_id: int, session_id: str) -> WizardSessionDTO | None:
return sessions.get_session(team_id, session_id)
diff --git a/products/wizard/backend/facade/contracts.py b/products/wizard/backend/facade/contracts.py
index 00c6e6ed0977..1c1e3b4f0f60 100644
--- a/products/wizard/backend/facade/contracts.py
+++ b/products/wizard/backend/facade/contracts.py
@@ -270,3 +270,38 @@ class WizardRunPullRequestArtifactDTO:
type WizardRunArtifactDTO = WizardRunGitDiffArtifactDTO | WizardRunPullRequestArtifactDTO
+
+
+@frozen
+class WizardScanSignal:
+ # Free-form so the wizard can add a signal type without a backend change.
+ source: str
+ name: str
+ file: str | None
+
+
+@frozen
+class WizardScanTool:
+ kind: str
+ signals: tuple[WizardScanSignal, ...]
+
+
+@frozen
+class RecordWizardScanInput:
+ team_id: int
+ created_by_id: int | None
+ session_id: str
+ program: str
+ wizard_version: str
+ workspace_fingerprint: str
+ scanned_at: datetime
+ tools: tuple[WizardScanTool, ...]
+ # False when the wizard could not walk the whole workspace, so a missing tool may not be gone.
+ complete: bool = True
+
+
+@frozen
+class WizardScanResult:
+ id: UUID
+ # False when the session already reported this scan, so nothing was written.
+ created: bool
diff --git a/products/wizard/backend/logic/scans.py b/products/wizard/backend/logic/scans.py
new file mode 100644
index 000000000000..f1d420891c3d
--- /dev/null
+++ b/products/wizard/backend/logic/scans.py
@@ -0,0 +1,127 @@
+from datetime import datetime
+
+from django.db import connection, transaction
+
+from posthog.models.scoping.manager import resolve_effective_team_id
+
+from products.wizard.backend.facade.contracts import RecordWizardScanInput, WizardScanResult, WizardScanTool
+from products.wizard.backend.models import WizardDetectedTool, WizardScan
+from products.wizard.backend.tool_catalog.catalog import classify_tool
+
+
+def _signals_json(tool: WizardScanTool) -> list[dict[str, str | None]]:
+ return [{"source": signal.source, "name": signal.name, "file": signal.file} for signal in tool.signals]
+
+
+def _classify(row: WizardDetectedTool) -> None:
+ classification = classify_tool(row.kind)
+ row.warehouse_source_type = classification.warehouse_source_type if classification else None
+ row.competes_with = list(classification.competes_with) if classification else []
+
+
+def record_scan(params: RecordWizardScanInput) -> WizardScanResult:
+ # A scan can repeat the same kind when the wizard matches it in two manifests. The first wins.
+ tools: dict[str, WizardScanTool] = {}
+ for tool in params.tools:
+ tools.setdefault(tool.kind, tool)
+
+ # A child environment's scans are stored under its parent team. The lookup, the created row and the lock
+ # must use the same id, or a replayed session misses its stored scan and fails on the unique constraint.
+ team_id = resolve_effective_team_id(params.team_id)
+
+ with transaction.atomic():
+ _lock_workspace(team_id, params.workspace_fingerprint)
+ scan, created = WizardScan.objects.for_team(team_id, canonical=True).get_or_create(
+ team_id=team_id,
+ session_id=params.session_id,
+ defaults={
+ "created_by_id": params.created_by_id,
+ "workspace_fingerprint": params.workspace_fingerprint,
+ "program": params.program,
+ "wizard_version": params.wizard_version,
+ "scanned_at": params.scanned_at,
+ "detected_count": len(tools),
+ },
+ )
+ if not created:
+ return WizardScanResult(id=scan.id, created=False)
+
+ # Tool state follows the newest scan of the workspace. A scan that arrives after a newer one is stored,
+ # but it changes nothing, even when the newer scan found no tools at all. Both reads use the writer, because
+ # a lagging read replica can miss the scan or tool rows that the previous holder of the lock committed.
+ newer_scan_exists = (
+ WizardScan.objects.for_team(team_id, canonical=True)
+ .using("default")
+ .filter(workspace_fingerprint=params.workspace_fingerprint, scanned_at__gt=scan.scanned_at)
+ .exists()
+ )
+ if not newer_scan_exists:
+ existing = {
+ row.kind: row
+ for row in WizardDetectedTool.objects.for_team(team_id, canonical=True)
+ .using("default")
+ .filter(workspace_fingerprint=params.workspace_fingerprint)
+ }
+ _apply_scan(scan, tools, existing, complete=params.complete)
+
+ return WizardScanResult(id=scan.id, created=True)
+
+
+def _lock_workspace(team_id: int, workspace_fingerprint: str) -> None:
+ # Scans of one workspace from different sessions write the same tool rows. Without the lock, two first scans
+ # both insert a row and one fails on the unique constraint, and the newest-scan check can miss a scan that
+ # commits in between. The lock ends with the transaction.
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [team_id, f"wizard-scan:{workspace_fingerprint}"]
+ )
+
+
+def _apply_scan(
+ scan: WizardScan, tools: dict[str, WizardScanTool], existing: dict[str, WizardDetectedTool], *, complete: bool
+) -> None:
+ scanned_at: datetime = scan.scanned_at
+ to_create: list[WizardDetectedTool] = []
+ to_update: list[WizardDetectedTool] = []
+
+ for kind, tool in tools.items():
+ row = existing.get(kind)
+ if row is None:
+ row = WizardDetectedTool(
+ team_id=scan.team_id,
+ workspace_fingerprint=scan.workspace_fingerprint,
+ kind=kind,
+ first_seen_scan=scan,
+ first_seen_at=scanned_at,
+ )
+ to_create.append(row)
+ else:
+ to_update.append(row)
+ row.signals = _signals_json(tool)
+ row.last_seen_scan = scan
+ row.last_seen_at = scanned_at
+ row.removed_in_scan = None
+ row.removed_at = None
+ _classify(row)
+
+ for kind, row in existing.items():
+ if complete and kind not in tools and row.removed_at is None:
+ row.removed_in_scan = scan
+ row.removed_at = scanned_at
+ to_update.append(row)
+
+ # Scoped explicitly, because the ambient team context is not always the scanned team.
+ tools_of_team = WizardDetectedTool.objects.for_team(scan.team_id)
+ tools_of_team.bulk_create(to_create)
+ tools_of_team.bulk_update(
+ to_update,
+ [
+ "signals",
+ "warehouse_source_type",
+ "competes_with",
+ "last_seen_scan",
+ "last_seen_at",
+ "removed_in_scan",
+ "removed_at",
+ ],
+ )
diff --git a/products/wizard/backend/migrations/0010_wizardscan_wizarddetectedtool.py b/products/wizard/backend/migrations/0010_wizardscan_wizarddetectedtool.py
new file mode 100644
index 000000000000..a1facec7dc26
--- /dev/null
+++ b/products/wizard/backend/migrations/0010_wizardscan_wizarddetectedtool.py
@@ -0,0 +1,157 @@
+# Generated by Django 5.2.18 on 2026-10-12 23:29
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1396_events_retention_config"),
+ ("wizard", "0009_wizardrun_tasks_snapshot_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="WizardScan",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("session_id", models.CharField(max_length=255)),
+ ("workspace_fingerprint", models.CharField(max_length=64)),
+ ("program", models.CharField(max_length=50)),
+ ("wizard_version", models.CharField(max_length=32)),
+ ("scanned_at", models.DateTimeField()),
+ ("detected_count", models.PositiveSmallIntegerField()),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ migrations.CreateModel(
+ name="WizardDetectedTool",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("workspace_fingerprint", models.CharField(max_length=64)),
+ ("kind", models.CharField(max_length=64)),
+ (
+ "warehouse_source_type",
+ models.CharField(blank=True, max_length=128, null=True),
+ ),
+ ("competes_with", models.JSONField(default=list)),
+ ("signals", models.JSONField(default=list)),
+ ("first_seen_at", models.DateTimeField()),
+ ("last_seen_at", models.DateTimeField()),
+ ("removed_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "first_seen_scan",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="wizard.wizardscan",
+ ),
+ ),
+ (
+ "last_seen_scan",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="wizard.wizardscan",
+ ),
+ ),
+ (
+ "removed_in_scan",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="wizard.wizardscan",
+ ),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ migrations.AddIndex(
+ model_name="wizardscan",
+ index=models.Index(
+ fields=["team", "workspace_fingerprint", "scanned_at"],
+ name="wizard_scan_workspace_idx",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="wizardscan",
+ constraint=models.UniqueConstraint(fields=("team", "session_id"), name="unique_wizard_scan_per_session"),
+ ),
+ migrations.AddIndex(
+ model_name="wizarddetectedtool",
+ index=models.Index(fields=["team", "kind"], name="wizard_tool_team_kind_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="wizarddetectedtool",
+ index=models.Index(
+ condition=models.Q(("removed_at__isnull", True)),
+ fields=["kind"],
+ name="wizard_tool_active_kind_idx",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="wizarddetectedtool",
+ constraint=models.UniqueConstraint(
+ fields=("team", "workspace_fingerprint", "kind"),
+ name="unique_wizard_tool_per_workspace",
+ ),
+ ),
+ ]
diff --git a/products/wizard/backend/migrations/max_migration.txt b/products/wizard/backend/migrations/max_migration.txt
index 1db8be1ce7f3..49d792af0b0b 100644
--- a/products/wizard/backend/migrations/max_migration.txt
+++ b/products/wizard/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0009_wizardrun_tasks_snapshot_and_more
+0010_wizardscan_wizarddetectedtool
diff --git a/products/wizard/backend/models.py b/products/wizard/backend/models.py
index 39abaacfc90e..65bb41d30c79 100644
--- a/products/wizard/backend/models.py
+++ b/products/wizard/backend/models.py
@@ -220,3 +220,68 @@ class WizardWorker(UUIDModel, TeamScopedRootMixin, UpdatedMetaFields):
name="wizard_worker_cleanup_idx",
)
]
+
+
+# One codebase scan reported by one wizard run, sent only when the user agreed to share it.
+class WizardScan(UUIDModel, TeamScopedRootMixin):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="+",
+ db_constraint=False,
+ )
+
+ session_id = models.CharField(max_length=255)
+ # sha256 of the project id and the git remote (or install dir), so scans of one repository line up
+ # without storing the repository name.
+ workspace_fingerprint = models.CharField(max_length=64)
+ program = models.CharField(max_length=50)
+ wizard_version = models.CharField(max_length=32)
+ scanned_at = models.DateTimeField()
+ detected_count = models.PositiveSmallIntegerField()
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta(TeamScopedRootMixin.Meta):
+ constraints = [models.UniqueConstraint(fields=["team", "session_id"], name="unique_wizard_scan_per_session")]
+ indexes = [
+ # Recording a scan checks for a newer scan of the same workspace.
+ models.Index(fields=["team", "workspace_fingerprint", "scanned_at"], name="wizard_scan_workspace_idx")
+ ]
+
+
+# The current state of one tool in one workspace. Each scan of that workspace updates it.
+class WizardDetectedTool(UUIDModel, TeamScopedRootMixin):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ workspace_fingerprint = models.CharField(max_length=64)
+ kind = models.CharField(max_length=64)
+
+ # Copied from the tool catalog when the row is written, so the row stays readable after the
+ # catalog changes. Empty for a kind the catalog does not know.
+ warehouse_source_type = models.CharField(max_length=128, null=True, blank=True)
+ competes_with = models.JSONField(default=list)
+
+ signals = models.JSONField(default=list)
+
+ first_seen_scan = models.ForeignKey(WizardScan, on_delete=models.SET_NULL, null=True, related_name="+")
+ first_seen_at = models.DateTimeField()
+ last_seen_scan = models.ForeignKey(WizardScan, on_delete=models.SET_NULL, null=True, related_name="+")
+ last_seen_at = models.DateTimeField()
+ # Set when a later scan of the same workspace no longer finds the tool, cleared if it returns.
+ removed_in_scan = models.ForeignKey(WizardScan, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
+ removed_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta(TeamScopedRootMixin.Meta):
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "workspace_fingerprint", "kind"], name="unique_wizard_tool_per_workspace"
+ )
+ ]
+ indexes = [
+ models.Index(fields=["team", "kind"], name="wizard_tool_team_kind_idx"),
+ models.Index(
+ fields=["kind"], condition=models.Q(removed_at__isnull=True), name="wizard_tool_active_kind_idx"
+ ),
+ ]
diff --git a/products/wizard/backend/presentation/scans/__init__.py b/products/wizard/backend/presentation/scans/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/wizard/backend/presentation/scans/serializers.py b/products/wizard/backend/presentation/scans/serializers.py
new file mode 100644
index 000000000000..3a68c3a6d93f
--- /dev/null
+++ b/products/wizard/backend/presentation/scans/serializers.py
@@ -0,0 +1,77 @@
+from datetime import datetime, timedelta
+
+from django.utils import timezone
+
+from rest_framework import serializers
+
+MAX_TOOLS_PER_SCAN = 300
+MAX_SIGNALS_PER_TOOL = 50
+# The wizard stamps `scanned_at` with the client clock. A day of slack covers clock skew, and anything
+# later would let one scan claim to be newer than every scan that follows it.
+MAX_SCANNED_AT_SKEW = timedelta(days=1)
+
+
+class WizardScanSignalSerializer(serializers.Serializer):
+ source = serializers.CharField( # type: ignore[assignment] # field named `source` shadows DRF Field.source
+ max_length=32,
+ help_text="Where the wizard found the tool, such as `npm`, `pypi`, `env_key` or `script_host`.",
+ )
+ name = serializers.CharField(
+ max_length=255,
+ help_text="The package name, `.env` key name or script host that matched. Never a `.env` value.",
+ )
+ file = serializers.CharField(
+ max_length=512,
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Path of the file the signal came from, relative to the scanned directory.",
+ )
+
+
+class WizardScanToolSerializer(serializers.Serializer):
+ kind = serializers.CharField(
+ max_length=64,
+ help_text="The tool's kind in the wizard tool catalog, such as `Stripe` or `Amplitude`.",
+ )
+ signals = serializers.ListField(
+ child=WizardScanSignalSerializer(),
+ max_length=MAX_SIGNALS_PER_TOOL,
+ help_text="The signals that matched this tool.",
+ )
+
+
+class RecordWizardScanRequestSerializer(serializers.Serializer):
+ session_id = serializers.CharField(max_length=255, help_text="The wizard run that made the scan.")
+ program = serializers.CharField(
+ max_length=50,
+ help_text="The wizard program that scanned, such as `posthog-integration` or `warehouse-source`.",
+ )
+ wizard_version = serializers.CharField(max_length=32, help_text="Version of the wizard that made the scan.")
+ workspace_fingerprint = serializers.RegexField(
+ r"^[0-9a-f]{64}$",
+ max_length=64,
+ help_text="sha256 hex digest that identifies the scanned repository without naming it.",
+ )
+ scanned_at = serializers.DateTimeField(help_text="When the wizard scanned the codebase.")
+ tools = serializers.ListField(
+ child=WizardScanToolSerializer(),
+ max_length=MAX_TOOLS_PER_SCAN,
+ help_text="Every tool the scan found. An empty list is a scan that found nothing.",
+ )
+ complete = serializers.BooleanField(
+ default=True,
+ help_text="False when the scan could not read the whole workspace. Tools it did not find are then kept.",
+ )
+
+ def validate_scanned_at(self, value: datetime) -> datetime:
+ if value > timezone.now() + MAX_SCANNED_AT_SKEW:
+ raise serializers.ValidationError("scanned_at is in the future.")
+ return value
+
+
+class WizardScanResultSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="ID of the stored scan.")
+ created = serializers.BooleanField(
+ help_text="False when this session had already reported its scan, so nothing changed."
+ )
diff --git a/products/wizard/backend/presentation/scans/views.py b/products/wizard/backend/presentation/scans/views.py
new file mode 100644
index 000000000000..5c8880fc2b0c
--- /dev/null
+++ b/products/wizard/backend/presentation/scans/views.py
@@ -0,0 +1,61 @@
+from typing import Any
+
+from drf_spectacular.utils import OpenApiResponse
+from rest_framework import status, viewsets
+from rest_framework.response import Response
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import RecordWizardScanInput, WizardScanSignal, WizardScanTool
+from products.wizard.backend.presentation.scans.serializers import (
+ RecordWizardScanRequestSerializer,
+ WizardScanResultSerializer,
+)
+
+
+class WizardScanViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "wizard_session"
+ scope_object_write_actions = ["create"]
+ http_method_names = ["post", "options"]
+
+ @validated_request(
+ request_serializer=RecordWizardScanRequestSerializer,
+ responses={
+ 201: OpenApiResponse(response=WizardScanResultSerializer, description="The scan was stored."),
+ 200: OpenApiResponse(
+ response=WizardScanResultSerializer, description="This session already reported its scan."
+ ),
+ },
+ summary="Record the tools a wizard scan found in a codebase",
+ )
+ def create(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ data = request.validated_data
+ user = getattr(request, "user", None)
+ result = wizard_facade.record_scan(
+ RecordWizardScanInput(
+ team_id=self.team_id,
+ created_by_id=user.id if user is not None and not user.is_anonymous else None,
+ session_id=data["session_id"],
+ program=data["program"],
+ wizard_version=data["wizard_version"],
+ workspace_fingerprint=data["workspace_fingerprint"],
+ scanned_at=data["scanned_at"],
+ complete=data["complete"],
+ tools=tuple(
+ WizardScanTool(
+ kind=tool["kind"],
+ signals=tuple(
+ WizardScanSignal(source=signal["source"], name=signal["name"], file=signal["file"])
+ for signal in tool["signals"]
+ ),
+ )
+ for tool in data["tools"]
+ ),
+ )
+ )
+ return Response(
+ WizardScanResultSerializer(result).data,
+ status=status.HTTP_201_CREATED if result.created else status.HTTP_200_OK,
+ )
diff --git a/products/wizard/backend/routes.py b/products/wizard/backend/routes.py
index e62caf065574..ae6575f502f1 100644
--- a/products/wizard/backend/routes.py
+++ b/products/wizard/backend/routes.py
@@ -3,11 +3,13 @@ from posthog.api.routing import RouterRegistry
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 WizardRunTasksViewSet, WizardRunViewSet
+from products.wizard.backend.presentation.scans.views import WizardScanViewSet
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"])
+ routers.projects.register(r"wizard/scans", WizardScanViewSet, "project_wizard_scans", ["project_id"])
# Wizard Runs
wizard_runs_router = routers.projects.register(
diff --git a/products/wizard/backend/tests/scans/__init__.py b/products/wizard/backend/tests/scans/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/wizard/backend/tests/scans/test_logic.py b/products/wizard/backend/tests/scans/test_logic.py
new file mode 100644
index 000000000000..13730f936385
--- /dev/null
+++ b/products/wizard/backend/tests/scans/test_logic.py
@@ -0,0 +1,127 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+
+from posthog.models import Team
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import (
+ RecordWizardScanInput,
+ WizardScanResult,
+ WizardScanSignal,
+ WizardScanTool,
+)
+from products.wizard.backend.models import WizardDetectedTool
+
+WORKSPACE = "a" * 64
+OTHER_WORKSPACE = "b" * 64
+START = datetime(2026, 5, 19, 10, 0, tzinfo=UTC)
+
+
+def _scan(
+ team: Team, session_id: str, hours: int, kinds: list[str], workspace: str = WORKSPACE, complete: bool = True
+) -> WizardScanResult:
+ return wizard_facade.record_scan(
+ RecordWizardScanInput(
+ team_id=team.id,
+ created_by_id=None,
+ session_id=session_id,
+ program="posthog-integration",
+ wizard_version="2.0.0",
+ workspace_fingerprint=workspace,
+ scanned_at=START + timedelta(hours=hours),
+ tools=tuple(
+ WizardScanTool(kind=kind, signals=(WizardScanSignal(source="npm", name=kind.lower(), file=None),))
+ for kind in kinds
+ ),
+ complete=complete,
+ )
+ )
+
+
+def _tools(team: Team, workspace: str = WORKSPACE) -> dict[str, WizardDetectedTool]:
+ return {
+ row.kind: row for row in WizardDetectedTool.objects.for_team(team.id).filter(workspace_fingerprint=workspace)
+ }
+
+
+def test_tracks_tools_across_scans(team: Team) -> None:
+ first = _scan(team, "s1", 0, ["Stripe", "Amplitude", "NotInTheCatalog"])
+ second = _scan(team, "s2", 1, ["Stripe"])
+
+ tools = _tools(team)
+ assert tools["Amplitude"].removed_in_scan_id == second.id
+ assert tools["Stripe"].removed_at is None
+ assert tools["Stripe"].last_seen_scan_id == second.id
+ assert tools["Amplitude"].competes_with == ["product_analytics"]
+ assert tools["Stripe"].warehouse_source_type == "Stripe"
+ assert (tools["NotInTheCatalog"].warehouse_source_type, tools["NotInTheCatalog"].competes_with) == (None, [])
+
+ third = _scan(team, "s3", 2, ["Stripe", "Amplitude"])
+
+ amplitude = _tools(team)["Amplitude"]
+ assert (amplitude.removed_in_scan_id, amplitude.removed_at) == (None, None)
+ assert amplitude.first_seen_scan_id == first.id
+ assert amplitude.last_seen_scan_id == third.id
+
+
+ "scans, last_seen_session, removed_session",
+ [
+ pytest.param([("newer", 2, ["Stripe"]), ("older", 1, [])], "newer", None, id="late_empty_scan"),
+ pytest.param(
+ [("seen", 0, ["Stripe"]), ("removed", 2, []), ("late", 1, ["Stripe"])],
+ "seen",
+ "removed",
+ id="late_sighting_after_removal",
+ ),
+ pytest.param(
+ [("seen", 0, ["Stripe"]), ("removed", 2, []), ("still_absent", 4, []), ("late", 3, ["Stripe"])],
+ "seen",
+ "removed",
+ id="late_sighting_after_repeated_absence",
+ ),
+ ],
+)
+def test_older_scan_arriving_late_does_not_rewind_state(
+ team: Team, scans: list[tuple[str, int, list[str]]], last_seen_session: str, removed_session: str | None
+) -> None:
+ ids = {session_id: _scan(team, session_id, hours, kinds).id for session_id, hours, kinds in scans}
+
+ stripe = _tools(team)["Stripe"]
+ assert stripe.last_seen_scan_id == ids[last_seen_session]
+ assert stripe.removed_in_scan_id == (ids[removed_session] if removed_session else None)
+
+
[email protected]("through_child_environment", [False, True])
+def test_replayed_session_changes_nothing(team: Team, through_child_environment: bool) -> None:
+ reporting_team = (
+ Team.objects.create(organization=team.organization, parent_team=team, name="env")
+ if through_child_environment
+ else team
+ )
+ first = _scan(reporting_team, "s1", 0, ["Stripe"])
+ replay = _scan(reporting_team, "s1", 1, ["Amplitude"])
+
+ assert replay == WizardScanResult(id=first.id, created=False)
+ assert set(_tools(team)) == {"Stripe"}
+
+
+def test_scan_of_one_workspace_leaves_other_workspaces_alone(team: Team) -> None:
+ _scan(team, "s1", 0, ["Stripe"])
+ _scan(team, "s2", 1, [], workspace=OTHER_WORKSPACE)
+
+ assert _tools(team)["Stripe"].removed_at is None
+
+
+def test_partial_scan_adds_what_it_saw_and_removes_nothing(team: Team) -> None:
+ _scan(team, "s1", 0, ["Stripe", "Amplitude"])
+ _scan(team, "s2", 1, ["Stripe", "Sentry"], complete=False)
+
+ tools = _tools(team)
+ assert {kind for kind, row in tools.items() if row.removed_at is None} == {"Stripe", "Amplitude", "Sentry"}
diff --git a/products/wizard/backend/tests/scans/test_scan_presentation.py b/products/wizard/backend/tests/scans/test_scan_presentation.py
new file mode 100644
index 000000000000..ddef3503bb70
--- /dev/null
+++ b/products/wizard/backend/tests/scans/test_scan_presentation.py
@@ -0,0 +1,31 @@
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+
+
+class TestWizardScanViewSet(APIBaseTest):
+ def _payload(self) -> dict:
+ return {
+ "session_id": "onboarding-nextjs-2026-05-19T10:00:00Z",
+ "program": "posthog-integration",
+ "wizard_version": "2.0.0",
+ "workspace_fingerprint": "a" * 64,
+ "scanned_at": "2026-05-19T10:00:00Z",
+ "tools": [{"kind": "Amplitude", "signals": [{"source": "npm", "name": "@amplitude/analytics-browser"}]}],
+ }
+
+ def _post(self) -> int:
+ return self.client.post(
+ f"/api/projects/{self.team.id}/wizard/scans/", self._payload(), format="json"
+ ).status_code
+
+ def test_records_a_scan_once_per_session(self) -> None:
+ assert self._post() == status.HTTP_201_CREATED
+ assert self._post() == status.HTTP_200_OK
+
+ def test_requires_wizard_session_write_scope(self) -> None:
+ token = self.create_personal_api_key_with_scopes(["wizard_session:read"])
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ assert self._post() == status.HTTP_403_FORBIDDEN
diff --git a/products/wizard/frontend/generated/api.schemas.ts b/products/wizard/frontend/generated/api.schemas.ts
index d9e836327d25..fee955194e17 100644
--- a/products/wizard/frontend/generated/api.schemas.ts
+++ b/products/wizard/frontend/generated/api.schemas.ts
@@ -440,6 +440,78 @@ export interface UpdateWizardRunTaskListApi {
tasks: UpdateWizardRunTaskApi[]
}
+export interface WizardScanSignalApi {
+ /**
+ * Where the wizard found the tool, such as `npm`, `pypi`, `env_key` or `script_host`.
+ * @maxLength 32
+ */
+ source: string
+ /**
+ * The package name, `.env` key name or script host that matched. Never a `.env` value.
+ * @maxLength 255
+ */
+ name: string
+ /**
+ * Path of the file the signal came from, relative to the scanned directory.
+ * @maxLength 512
+ * @nullable
+ */
+ file?: string | null
+}
+
+export interface WizardScanToolApi {
+ /**
+ * The tool's kind in the wizard tool catalog, such as `Stripe` or `Amplitude`.
+ * @maxLength 64
+ */
+ kind: string
+ /**
+ * The signals that matched this tool.
+ * @maxItems 50
+ */
+ signals: WizardScanSignalApi[]
+}
+
+export interface RecordWizardScanRequestApi {
+ /**
+ * The wizard run that made the scan.
+ * @maxLength 255
+ */
+ session_id: string
+ /**
+ * The wizard program that scanned, such as `posthog-integration` or `warehouse-source`.
+ * @maxLength 50
+ */
+ program: string
+ /**
+ * Version of the wizard that made the scan.
+ * @maxLength 32
+ */
+ wizard_version: string
+ /**
+ * sha256 hex digest that identifies the scanned repository without naming it.
+ * @maxLength 64
+ * @pattern ^[0-9a-f]{64}$
+ */
+ workspace_fingerprint: string
+ /** When the wizard scanned the codebase. */
+ scanned_at: string
+ /**
+ * Every tool the scan found. An empty list is a scan that found nothing.
+ * @maxItems 300
+ */
+ tools: WizardScanToolApi[]
+ /** False when the scan could not read the whole workspace. Tools it did not find are then kept. */
+ complete?: boolean
+}
+
+export interface WizardScanResultApi {
+ /** ID of the stored scan. */
+ id: string
+ /** False when this session had already reported its scan, so nothing changed. */
+ created: boolean
+}
+
/**
* 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.
diff --git a/products/wizard/frontend/generated/api.ts b/products/wizard/frontend/generated/api.ts
index 96e9cc8b1038..441d9197bde9 100644
--- a/products/wizard/frontend/generated/api.ts
+++ b/products/wizard/frontend/generated/api.ts
@@ -14,6 +14,7 @@ import type {
PaginatedWizardRunListApi,
PaginatedWizardSessionDTOListApi,
PatchedWizardRunStatusUpdateRequestApi,
+ RecordWizardScanRequestApi,
UpdateWizardRunTaskListApi,
UpsertWizardSessionRequestApi,
WizardRegistryListParams,
@@ -22,6 +23,7 @@ import type {
WizardRunTaskListApi,
WizardRunsArtifactsListParams,
WizardRunsListParams,
+ WizardScanResultApi,
WizardSessionDTOApi,
WizardSessionsLatestRetrieveParams,
WizardSessionsListParams,
@@ -262,6 +264,26 @@ export const wizardRunsTasksUpdate = async (
})
}
+export const getWizardScansCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/wizard/scans/`
+}
+
+/**
+ * @summary Record the tools a wizard scan found in a codebase
+ */
+export const wizardScansCreate = async (
+ projectId: string,
+ recordWizardScanRequestApi: RecordWizardScanRequestApi,
+ options?: RequestInit
+): Promise<WizardScanResultApi> => {
+ return apiMutator<WizardScanResultApi>(getWizardScansCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(recordWizardScanRequestApi),
+ })
+}
+
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 1f3ecce7d992..8270d52c049f 100644
--- a/products/wizard/frontend/generated/api.zod.ts
+++ b/products/wizard/frontend/generated/api.zod.ts
@@ -102,6 +102,89 @@ export const WizardRunsTasksUpdateBody = /* @__PURE__ */ zod.object({
.describe("Complete task snapshot. An empty list clears the run's tasks."),
})
+/**
+ * @summary Record the tools a wizard scan found in a codebase
+ */
+export const wizardScansCreateBodySessionIdMax = 255
+
+export const wizardScansCreateBodyProgramMax = 50
+
+export const wizardScansCreateBodyWizardVersionMax = 32
+
+export const wizardScansCreateBodyWorkspaceFingerprintMax = 64
+
+export const wizardScansCreateBodyWorkspaceFingerprintRegExp = new RegExp('^[0-9a-f]{64}$')
+export const wizardScansCreateBodyToolsItemKindMax = 64
+
+export const wizardScansCreateBodyToolsItemSignalsItemSourceMax = 32
+
+export const wizardScansCreateBodyToolsItemSignalsItemNameMax = 255
+
+export const wizardScansCreateBodyToolsItemSignalsItemFileMax = 512
+
+export const wizardScansCreateBodyToolsItemSignalsMax = 50
+
+export const wizardScansCreateBodyToolsMax = 300
+
+export const wizardScansCreateBodyCompleteDefault = true
+
+export const WizardScansCreateBody = /* @__PURE__ */ zod.object({
+ session_id: zod.string().max(wizardScansCreateBodySessionIdMax).describe('The wizard run that made the scan.'),
+ program: zod
+ .string()
+ .max(wizardScansCreateBodyProgramMax)
+ .describe('The wizard program that scanned, such as `posthog-integration` or `warehouse-source`.'),
+ wizard_version: zod
+ .string()
+ .max(wizardScansCreateBodyWizardVersionMax)
+ .describe('Version of the wizard that made the scan.'),
+ workspace_fingerprint: zod
+ .string()
+ .max(wizardScansCreateBodyWorkspaceFingerprintMax)
+ .regex(wizardScansCreateBodyWorkspaceFingerprintRegExp)
+ .describe('sha256 hex digest that identifies the scanned repository without naming it.'),
+ scanned_at: zod.iso.datetime({ offset: true }).describe('When the wizard scanned the codebase.'),
+ tools: zod
+ .array(
+ zod.object({
+ kind: zod
+ .string()
+ .max(wizardScansCreateBodyToolsItemKindMax)
+ .describe("The tool's kind in the wizard tool catalog, such as `Stripe` or `Amplitude`."),
+ signals: zod
+ .array(
+ zod.object({
+ source: zod
+ .string()
+ .max(wizardScansCreateBodyToolsItemSignalsItemSourceMax)
+ .describe(
+ 'Where the wizard found the tool, such as `npm`, `pypi`, `env_key` or `script_host`.'
+ ),
+ name: zod
+ .string()
+ .max(wizardScansCreateBodyToolsItemSignalsItemNameMax)
+ .describe(
+ 'The package name, `.env` key name or script host that matched. Never a `.env` value.'
+ ),
+ file: zod
+ .string()
+ .max(wizardScansCreateBodyToolsItemSignalsItemFileMax)
+ .nullish()
+ .describe('Path of the file the signal came from, relative to the scanned directory.'),
+ })
+ )
+ .max(wizardScansCreateBodyToolsItemSignalsMax)
+ .describe('The signals that matched this tool.'),
+ })
+ )
+ .max(wizardScansCreateBodyToolsMax)
+ .describe('Every tool the scan found. An empty list is a scan that found nothing.'),
+ complete: zod
+ .boolean()
+ .default(wizardScansCreateBodyCompleteDefault)
+ .describe('False when the scan could not read the whole workspace. Tools it did not find are then kept.'),
+})
+
/**
* 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 34ddca1400e3..e079dc37d1be 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -94500,6 +94500,71 @@ export namespace Schemas {
recorded: boolean;
}
+ export interface WizardScanSignal {
+ /**
+ * Where the wizard found the tool, such as `npm`, `pypi`, `env_key` or `script_host`.
+ * @maxLength 32
+ */
+ source: string;
+ /**
+ * The package name, `.env` key name or script host that matched. Never a `.env` value.
+ * @maxLength 255
+ */
+ name: string;
+ /**
+ * Path of the file the signal came from, relative to the scanned directory.
+ * @maxLength 512
+ * @nullable
+ */
+ file?: string | null;
+ }
+
+ export interface WizardScanTool {
+ /**
+ * The tool's kind in the wizard tool catalog, such as `Stripe` or `Amplitude`.
+ * @maxLength 64
+ */
+ kind: string;
+ /**
+ * The signals that matched this tool.
+ * @maxItems 50
+ */
+ signals: WizardScanSignal[];
+ }
+
+ export interface RecordWizardScanRequest {
+ /**
+ * The wizard run that made the scan.
+ * @maxLength 255
+ */
+ session_id: string;
+ /**
+ * The wizard program that scanned, such as `posthog-integration` or `warehouse-source`.
+ * @maxLength 50
+ */
+ program: string;
+ /**
+ * Version of the wizard that made the scan.
+ * @maxLength 32
+ */
+ wizard_version: string;
+ /**
+ * sha256 hex digest that identifies the scanned repository without naming it.
+ * @maxLength 64
+ * @pattern ^[0-9a-f]{64}$
+ */
+ workspace_fingerprint: string;
+ /** When the wizard scanned the codebase. */
+ scanned_at: string;
+ /**
+ * Every tool the scan found. An empty list is a scan that found nothing.
+ * @maxItems 300
+ */
+ tools: WizardScanTool[];
+ /** False when the scan could not read the whole workspace. Tools it did not find are then kept. */
+ complete?: boolean;
+ }
+
/**
* * `Redshift` - Redshift
*/
@@ -114080,6 +114145,13 @@ export namespace Schemas {
readonly tasks: readonly WizardRunTask[];
}
+ export interface WizardScanResult {
+ /** ID of the stored scan. */
+ id: string;
+ /** False when this session had already reported its scan, so nothing changed. */
+ created: boolean;
+ }
+
/**
* Whether PostHog paused this one workflow's email sending, and why.
*/