:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): enroll github-optional research pilots (#123617)
Georgiy Tarasov781f9443de9e
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.mdindex e492ada219ae..93704324ae42 100644--- a/docs/internal/signals-pr-lifecycle.md+++ b/docs/internal/signals-pr-lifecycle.md@@ -209,17 +209,25 @@ For information from a private repository or another explicitly private source,Each candidate carries a private, public, or unknown label from the cached GitHub repository list, so the agent does not query GitHub for visibility.These broader context checks remain prompt guidance; the source-repository restriction does not validate selections made outside the shared selector.-### GitHub-optional research+### GitHub-optional pilotThe boolean `self-driving-github-optional` flag targets the canonical project group (project UUID, with its numeric `id` as a group property). It defaults to off, including in development.+Pilot activation stores `activation_mode: github_optional` in the existing onboarding draft and completes through the existing activation API. It leaves `autostart_enabled` false regardless of pricing flags. Completed pilot activation also admits the project to scout discovery and dispatch while the flag is enabled, respecting fleet exclusions, withheld skills, permissions, and budgets. Fleet admission uses loaded local flag definitions and retries admission on later ticks when definitions are unavailable. Enabling the flag alone never creates scouts or enables sources. Already-active projects keep their settings.++An explicit `guaranteed_team_ids: []` in the `signals-scout` payload drains pilot teams too, blocking both scheduled and manual scout runs.++Activation in a child environment requires task editor access on the parent project and disables automatic implementation there. Scout-authored reports record code availability from the run's saved repository, GitHub posture, and pilot eligibility at dispatch. Repository checks distinguish missing access from temporary GitHub failures: automatic work can retry temporary failures, and manual requests return a retryable 503.+Flagged research continues without code when no repository is selected or GitHub is unavailable. Its `repo_selection` artefact records `research_context.mode` (`code` or `data_only`) and `repository_status`. Recognized repository authentication and clone failures can retry once without a checkout or GitHub credentials. Other failures keep their normal handling. Findings remain code-focused; missing code access alone is not a product decision requiring human input.Research without a repository preserves structured agent startup failures and clears their health issues after a successful startup, using the same provider and runtime scope as research with code.A saved repository is reused before checking GitHub availability. A data-only fallback leaves that selection and its recorded context unchanged, so a transient failure cannot replace a reviewer's pinned target.-Disable the flag to restore legacy behavior on subsequent research passes. Running passes finish with their recorded decision. Previous blocked reports are not automatically rerun.+The report remains readable and supports discussion, assignment, resolution, and eligible monitoring. Pull request creation requires usable repository access. The access check probes GitHub directly, preserving temporary failures for retry instead of treating a stale repository list as a permission decision. Any installation that confirms access enables the action without waiting for other installations. Connecting or repairing GitHub does not enable automatic implementation; the user must opt in separately. Previous blocked reports are not automatically rerun.++Disable the flag to remove pilot activation and restore legacy behavior on subsequent research passes. Running passes finish with their recorded decision. Reports and saved source/scout settings remain intact; fleet dispatch still applies its ordinary enrollment and exclusion gates.Without a repository, legacy ownership lookup is skipped. Existing human assignments remain intact.diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex a2719dd612f5..eea14de8a700 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -62,7 +62,7 @@ from posthog.api.integration_push_tokens import (from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from posthog.api.utils import action+from posthog.api.utils import ErrorResponseSerializer, actionfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.dns_hosts import lookup_dns_hostfrom posthog.domain_connect import discover_domain_connect, extract_root_domain_and_host, get_available_providers@@ -375,6 +375,20 @@ class GitHubRepoSerializer(serializers.Serializer):)+class GitHubRepositoryAccessQuerySerializer(serializers.Serializer):+ repository = serializers.CharField(+ required=False,+ help_text="Repository in owner/repo format. Omit to check access to any repository.",+ )++ def validate_repository(self, value: str) -> str:+ return validate_github_repository_name(value)+++class GitHubRepositoryAccessResponseSerializer(serializers.Serializer):+ available = serializers.BooleanField(help_text="Whether a live GitHub request confirmed repository access.")++class GitHubReposQuerySerializer(serializers.Serializer):search = serializers.CharField(required=False,@@ -1508,6 +1522,7 @@ class IntegrationViewSet("channels","users","github_repos",+ "github_repository_access","github_branches","github_teams","github_available_installations",@@ -2390,6 +2405,33 @@ class IntegrationViewSet())+ @validated_request(+ query_serializer=GitHubRepositoryAccessQuerySerializer,+ responses={200: GitHubRepositoryAccessResponseSerializer, 503: ErrorResponseSerializer},+ )+ @action(methods=["GET"], detail=True, url_path="github_repository_access")+ def github_repository_access(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ instance = self.get_object()+ if instance.kind != "github":+ raise ValidationError("github_repository_access endpoint is only supported for GitHub integrations")+ github = GitHubIntegration(instance, source="integrations_api", priority=Priority.CRITICAL)+ repository = request.validated_query_data.get("repository")+ try:+ if repository:+ available = github.installation_can_access_repository(repository, raise_on_transient=True)+ else:+ repositories, _ = github.list_repositories(per_page=1)+ available = bool(repositories)+ except GitHubIntegrationError as error:+ if error.status_code in (401, 403, 404) or github.installation_unavailable():+ available = False+ else:+ return Response(+ {"error": "Couldn't check GitHub access. Try again in a moment."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ return Response({"available": available})+@extend_schema(parameters=[GitHubAssigneesQuerySerializer], responses={200: IntegrationAssigneesResponseSerializer})@action(methods=["GET"], detail=True, url_path="github_assignees")def github_assignees(self, request: Request, *args: Any, **kwargs: Any) -> Response:diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 357c7463157f..fb9b916f7fc2 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -1740,6 +1740,7 @@ class TestIntegrationAPIKeyAccess:"url_suffix,method,expected_provider",[("github_repos/", "get", "GitHub"),+ ("github_repository_access/", "get", "GitHub"),("github_repos/refresh/", "post", "GitHub"),("github_branches/?repo=org/repo", "get", "GitHub"),("jira_projects/", "get", "Jira"),@@ -1769,6 +1770,52 @@ class TestIntegrationAPIKeyAccess:assert response.status_code == status.HTTP_400_BAD_REQUESTassert expected_provider in response.json()["detail"]+ @pytest.mark.parametrize("repository", ["", "org/repo"])+ @pytest.mark.parametrize(+ "github_status,refresh_status,expected_status",+ [(200, None, 200), (404, None, 200), (503, None, 503), (None, None, 503), (401, 404, 200), (401, 503, 503)],+ )+ @patch("posthog.models.integration.github.GitHubIntegration.client_request")+ @patch("posthog.models.github_integration_base.github_request")+ def test_github_repository_access_ignores_stale_cache(+ self,+ mock_request: MagicMock,+ mock_token_request: MagicMock,+ repository: str,+ github_status: int | None,+ refresh_status: int | None,+ expected_status: int,+ client: HttpClient,+ ) -> None:+ self.github_integration.repository_cache = []+ self.github_integration.repository_cache_updated_at = timezone.now() - timedelta(days=2)+ self.github_integration.save()+ if github_status is None:+ mock_request.side_effect = requests.ConnectionError("Network unavailable")+ else:+ mock_request.return_value.status_code = github_status+ mock_request.return_value.headers = {}+ mock_request.return_value.json.return_value = {+ "repositories": [{"id": 1, "name": "repo", "full_name": "org/repo"}]+ }+ mock_token_request.return_value.status_code = refresh_status+ mock_token_request.return_value.text = "Token refresh failed"+ mock_token_request.return_value.json.return_value = {"message": "Token refresh failed"}+ key_value = "test_repository_access"+ PersonalAPIKey.objects.create(+ user=self.user, secure_value=hash_key_value(key_value), scopes=["integration:read"]+ )++ response = client.get(+ f"/api/projects/{self.team.pk}/integrations/{self.github_integration.id}/github_repository_access/",+ {"repository": repository} if repository else {},+ HTTP_AUTHORIZATION=f"Bearer {key_value}",+ )++ assert response.status_code == expected_status+ if expected_status == 200:+ assert response.json() == {"available": github_status == 200}+@patch("posthog.models.integration.github.GitHubIntegration.list_cached_repositories")def test_github_repos_with_scope_succeeds(self, mock_list_repos, client: HttpClient):mock_list_repos.return_value = (diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 0e436f2dea33..e07e9a291b51 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -622,6 +622,16 @@ export interface GitHubReposRefreshResponseApi {installation_status: InstallationStatusEnumApi}+export interface GitHubRepositoryAccessResponseApi {+ /** Whether a live GitHub request confirmed repository access. */+ available: boolean+}++export interface ErrorResponseApi {+ /** Error message */+ error: string+}+export interface GitHubTeamApi {/** GitHub team numeric identifier. */id: number@@ -1227,6 +1237,14 @@ export type IntegrationsGithubReposRetrieveParams = {search?: string}+export type IntegrationsGithubRepositoryAccessRetrieveParams = {+ /**+ * Repository in owner/repo format. Omit to check access to any repository.+ * @minLength 1+ */+ repository?: string+}+export type IntegrationsGithubTeamsRetrieveParams = {/*** Maximum number of teams to return per request (max 500).diff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.tsindex b15714e51df5..7cea480691f2 100644--- a/products/integrations/frontend/generated/api.ts+++ b/products/integrations/frontend/generated/api.ts@@ -20,6 +20,7 @@ import type {GitHubPrepareCallbackRequestApi,GitHubReposRefreshResponseApi,GitHubReposResponseApi,+ GitHubRepositoryAccessResponseApi,GitHubTeamsResponseApi,IntegrationAccessRequestApi,IntegrationAccessRequestResponseApi,@@ -31,6 +32,7 @@ import type {IntegrationsGithubAssigneesRetrieveParams,IntegrationsGithubBranchesRetrieveParams,IntegrationsGithubReposRetrieveParams,+ IntegrationsGithubRepositoryAccessRetrieveParams,IntegrationsGithubTeamsRetrieveParams,IntegrationsGitlabMembersRetrieveParams,IntegrationsJiraAssignableUsersRetrieveParams,@@ -573,6 +575,41 @@ export const integrationsGithubReposRefreshCreate = async (})}+export const getIntegrationsGithubRepositoryAccessRetrieveUrl = (+ projectId: string,+ id: number,+ params?: IntegrationsGithubRepositoryAccessRetrieveParams+) => {+ 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}/integrations/${id}/github_repository_access/?${stringifiedParams}`+ : `/api/projects/${projectId}/integrations/${id}/github_repository_access/`+}++export const integrationsGithubRepositoryAccessRetrieve = async (+ projectId: string,+ id: number,+ params?: IntegrationsGithubRepositoryAccessRetrieveParams,+ options?: RequestInit+): Promise<GitHubRepositoryAccessResponseApi> => {+ return apiMutator<GitHubRepositoryAccessResponseApi>(+ getIntegrationsGithubRepositoryAccessRetrieveUrl(projectId, id, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getIntegrationsGithubTeamsRetrieveUrl = (projectId: string,id: number,diff --git a/products/signals/backend/facade/onboarding.py b/products/signals/backend/facade/onboarding.pyindex 0293d687099c..ef426856621f 100644--- a/products/signals/backend/facade/onboarding.py+++ b/products/signals/backend/facade/onboarding.py@@ -14,6 +14,7 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.transactional_email import is_transactional_email_configured+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.replay_vision.backend.facade.api import signal_emitting_scanner_idsfrom products.signals.backend.first_report_completion import first_report_completion_notifications_enabledfrom products.signals.backend.first_report_experiment import (@@ -23,6 +24,7 @@ from products.signals.backend.first_report_experiment import (from products.signals.backend.first_report_notification import register_first_report_notificationfrom products.signals.backend.first_report_scout import first_report_statefrom products.signals.backend.first_report_scout_types import FirstReportStatus+from products.signals.backend.github_optional import GITHUB_OPTIONAL_ACTIVATION, ResearchAccessPolicyfrom products.signals.backend.models import (AutonomyPriority,SignalFirstReportNotification,@@ -47,6 +49,10 @@ class InboxOnboardingValidationError(ValueError):pass+class InboxOnboardingPermissionError(PermissionError):+ pass++def onboarding_source_products() -> Sequence[tuple[str, str | Promise]]:return signal_source_product_choices()@@ -96,6 +102,7 @@ class InboxOnboarding:):jobs["recommendations"] = "failed"return {+ "github_optional_available": ResearchAccessPolicy.enabled(self.team_id),"draft": state.get("draft"),"completed_at": state.get("completed_at"),"variant": state.get("variant"),@@ -146,7 +153,19 @@ class InboxOnboarding:transaction.on_commit(lambda: self._report_exposure(self.user, config), robust=True)return self._state(config)+ def _validate_pilot(self, draft: dict[str, Any]) -> bool:+ if draft.get("activation_mode") != GITHUB_OPTIONAL_ACTIVATION:+ return False+ if not ResearchAccessPolicy.enabled(self.team_id):+ raise InboxOnboardingValidationError("The GitHub-optional pilot is not enabled for this project.")+ if draft["automatic_implementation"]:+ raise InboxOnboardingValidationError(+ "Activate without automatic implementation. You can enable it later in settings."+ )+ return True+def save_draft(self, draft: dict[str, Any]) -> dict[str, Any]:+ self._validate_pilot(draft)config = get_or_create_team_extension(self.team, SignalTeamConfig)with transaction.atomic():config = SignalTeamConfig.objects.select_for_update().get(team_id=self.team_id, pk=config.pk)@@ -166,9 +185,17 @@ class InboxOnboarding:self._enqueue_activation_jobs(config)return self._state(config)- if (config.onboarding or {}).get("variant") in ("test-github", "test-ui"):+ pilot = self._validate_pilot(draft)+ if pilot and self.team.parent_team_id:+ if not UserAccessControl(user=self.user, team=self.team.parent_team).check_access_level_for_resource(+ "task", "editor"+ ):+ raise InboxOnboardingPermissionError(+ "Activating this pilot requires task editor access on the parent project."+ )+ if pilot or (config.onboarding or {}).get("variant") in ("test-github", "test-ui"):self.authorize_scouts(True)- if (config.onboarding or {}).get("variant") == "test-github":+ if pilot or (config.onboarding or {}).get("variant") == "test-github":if not any(item["kind"] == "canonical" and item["skill_name"] == "signals-scout-general"for item in draft["suggestions"]@@ -186,7 +213,7 @@ class InboxOnboarding:"Scout findings are disabled. Enable the scout source before activating.")- if not InboxOnboardingReconciler(self.team_id).has_repository():+ if not pilot and not InboxOnboardingReconciler(self.team_id).has_repository():raise InboxOnboardingValidationError("Connect GitHub with access to at least one repository.")selected_source = False@@ -238,6 +265,11 @@ class InboxOnboarding:config = SignalTeamConfig.objects.select_for_update().get(team_id=self.team_id, pk=config.pk)state = config.onboarding or {}if not state.get("completed_at"):+ if pilot and (parent_team := self.team.parent_team) is not None:+ parent_config = get_or_create_team_extension(parent_team, SignalTeamConfig)+ SignalTeamConfig.objects.filter(pk=parent_config.pk, team_id=scout_team_id).update(+ autostart_enabled=False, updated_at=timezone.now()+ )config.autostart_enabled = draft["automatic_implementation"]config.default_autostart_priority = draft["implementation_priority"]config.onboarding = {@@ -246,14 +278,16 @@ class InboxOnboarding:"completed_at": timezone.now().isoformat(),"activated_by": user.pk,}- if state.get("variant") in ("test-github", "test-ui"):+ if pilot or state.get("variant") in ("test-github", "test-ui"):config.onboarding["jobs"] = {- "scout": "pending" if experiment or state.get("variant") == "test-github" else "skipped",+ "scout": "pending"+ if pilot or experiment or state.get("variant") == "test-github"+ else "skipped","recommendations": "skipped",}if experiment:config.onboarding["first_report_variant"] = experiment.variant- if state.get("variant") == "test-github":+ if pilot or state.get("variant") == "test-github":config.onboarding["jobs"]["recommendations"] = "pending"config.save(update_fields=["onboarding", "autostart_enabled", "default_autostart_priority", "updated_at"]@@ -267,7 +301,10 @@ class InboxOnboarding:def _enqueue_activation_jobs(self, config: SignalTeamConfig) -> None:state = config.onboarding or {}- if state.get("variant") not in ("test-github", "test-ui"):+ if (+ state.get("variant") not in ("test-github", "test-ui")+ and (state.get("draft") or {}).get("activation_mode") != GITHUB_OPTIONAL_ACTIVATION+ ):returnself.authorize_scouts(True)from products.signals.backend.tasks import (diff --git a/products/signals/backend/github_optional.py b/products/signals/backend/github_optional.pyindex ba62bcd1b1d5..e13d46672b01 100644--- a/products/signals/backend/github_optional.py+++ b/products/signals/backend/github_optional.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom django.db.models import Qimport structlog+import posthoganalyticsfrom requests import RequestExceptionfrom rest_framework.exceptions import APIException@@ -59,7 +60,7 @@ class ResearchAccessPolicy:return ResearchAccessPolicy.repository_integration_id(team_id, repository, priority=priority) is not None@staticmethod- def enabled_for_project(project: Team) -> bool:+ def enabled_for_project(project: Team, *, only_evaluate_locally: bool = False) -> bool:try:return (feature_enabled_or_false(@@ -68,6 +69,7 @@ class ResearchAccessPolicy:groups={"project": str(project.uuid)},group_properties={"project": {"id": project.id, "uuid": str(project.uuid)}},send_feature_flag_events=False,+ only_evaluate_locally=only_evaluate_locally,)is True)@@ -90,6 +92,10 @@ class ResearchAccessPolicy:@staticmethoddef enrolled_team_ids(*, exclude_team_ids: set[int] | None = None) -> set[int]:+ # Even local-only evaluation loads definitions synchronously when the SDK is cold.+ client = posthoganalytics.default_client+ if client is None or client.feature_flags is None:+ return set()projects = {parent_id or team_idfor team_id, parent_id in SignalTeamConfig.objects.filter(@@ -103,5 +109,5 @@ class ResearchAccessPolicy:return {project.idfor project in Team.objects.filter(id__in=projects).only("id", "uuid")- if ResearchAccessPolicy.enabled_for_project(project)+ if ResearchAccessPolicy.enabled_for_project(project, only_evaluate_locally=True)}diff --git a/products/signals/backend/onboarding_activation.py b/products/signals/backend/onboarding_activation.pyindex 7952459e84c1..8374b8c0e07c 100644--- a/products/signals/backend/onboarding_activation.py+++ b/products/signals/backend/onboarding_activation.py@@ -23,6 +23,7 @@ from products.signals.backend.first_report_scout import (set_first_report_state,)from products.signals.backend.first_report_scout_types import FirstReportStatus+from products.signals.backend.github_optional import GITHUB_OPTIONAL_ACTIVATIONfrom products.signals.backend.models import SignalScoutConfig, SignalTeamConfigfrom products.signals.backend.onboarding_analytics import InboxOnboardingAnalyticsfrom products.signals.backend.onboarding_completion import InboxOnboardingReconciler@@ -121,7 +122,11 @@ class InboxOnboardingActivation:return Truedef _start_default_scout(self, team: Team, state: dict[str, Any]) -> bool:- return state.get("variant") == "test-github" and self._start_general_scout(team)+ quick = (+ state.get("variant") == "test-github"+ or (state.get("draft") or {}).get("activation_mode") == GITHUB_OPTIONAL_ACTIVATION+ )+ return quick and self._start_general_scout(team)def _start_general_scout(self, team: Team) -> bool:scout = (@@ -154,7 +159,11 @@ class InboxOnboardingActivation:team_id=self.team_id)state = config.onboarding or {}- if state.get("variant") not in ("test-github", "test-ui") or not state.get("completed_at"):+ quick = (+ state.get("variant") in ("test-github", "test-ui")+ or (state.get("draft") or {}).get("activation_mode") == GITHUB_OPTIONAL_ACTIVATION+ )+ if not quick or not state.get("completed_at"):returnif state.get("jobs", {}).get(job) in ("started", "skipped"):returndiff --git a/products/signals/backend/onboarding_analytics.py b/products/signals/backend/onboarding_analytics.pyindex f841022c1e8d..135df50f2df5 100644--- a/products/signals/backend/onboarding_analytics.py+++ b/products/signals/backend/onboarding_analytics.py@@ -33,13 +33,14 @@ class InboxOnboardingAnalytics:draft = state.get("draft") or {}variant = state.get("variant")return {+ **({"activation_mode": draft["activation_mode"]} if draft.get("activation_mode") else {}),"project_id": config.team_id,"variant": variant,"$feature/inbox-ui-onboarding": variant,"flow_version": "ui-first-v1","inbox_client": "cloud","setup_mode": "quick"- if variant == "test-github"+ if variant == "test-github" or draft.get("activation_mode") == "github_optional"else "guided"if draft or variant == "test-ui"else "legacy",diff --git a/products/signals/backend/presentation/onboarding.py b/products/signals/backend/presentation/onboarding.pyindex c4dd188ce01e..9bdf91611457 100644--- a/products/signals/backend/presentation/onboarding.py+++ b/products/signals/backend/presentation/onboarding.py@@ -22,6 +22,7 @@ from posthog.permissions import APIScopePermission, get_authenticator_scopesfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.signals.backend.facade.onboarding import (InboxOnboarding,+ InboxOnboardingPermissionError,InboxOnboardingValidationError,can_create_onboarding_scout,onboarding_first_report_statuses,@@ -62,7 +63,16 @@ class InboxOnboardingSourceSerializer(serializers.Serializer):enabled = serializers.BooleanField(help_text="Whether this source should be enabled at activation.")+class InboxActivationMode(models.TextChoices):+ GITHUB_OPTIONAL = "github_optional", "GitHub optional"++class InboxOnboardingDraftSerializer(serializers.Serializer):+ activation_mode = serializers.ChoiceField(+ choices=InboxActivationMode.choices,+ required=False,+ help_text="Activate the GitHub-optional pilot. Requires project eligibility and leaves automatic implementation off.",+ )step = serializers.ChoiceField(choices=InboxOnboardingStep.choices, help_text="Step to resume after returning.")sources: serializers.ListSerializer[dict[str, object]] = serializers.ListSerializer(child=InboxOnboardingSourceSerializer(), max_length=50, help_text="Staged signal source choices."@@ -135,6 +145,9 @@ class FirstReportStateSerializer(serializers.Serializer):@extend_schema_serializer(many=False)class InboxOnboardingStateSerializer(serializers.Serializer):+ github_optional_available = serializers.BooleanField(+ required=False, help_text="Whether this project can activate Self-driving without connecting GitHub."+ )first_report_completion_notification = serializers.BooleanField(required=False,help_text="Whether the current user can receive an in-app notification when this investigation finishes.",@@ -226,7 +239,10 @@ class InboxOnboardingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def create(self, request: Request, *args: object, **kwargs: object) -> Response:serializer = InboxOnboardingDraftSerializer(data=request.data)serializer.is_valid(raise_exception=True)- return Response(self._service().save_draft(dict(serializer.data)))+ try:+ return Response(self._service().save_draft(dict(serializer.data)))+ except InboxOnboardingValidationError as error:+ raise serializers.ValidationError(str(error)) from error@extend_schema(request=InboxOnboardingDraftSerializer, responses=InboxOnboardingStateSerializer)@action(detail=False, methods=["POST"])@@ -237,5 +253,7 @@ class InboxOnboardingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):self._check_scout_access(request)try:return Response(self._service().complete(dict(serializer.data)))+ except InboxOnboardingPermissionError as error:+ raise PermissionDenied(str(error)) from errorexcept InboxOnboardingValidationError as error:raise serializers.ValidationError(str(error)) from errordiff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex bcbcd71ab973..6563c2c202db 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -38,6 +38,7 @@ from products.signals.backend.first_report_completion import complete_first_repofrom products.signals.backend.first_report_experiment import FirstReportExperiment, resolve_first_report_experimentfrom products.signals.backend.first_report_scout import set_first_report_statefrom products.signals.backend.first_report_scout_types import FirstReportScoutResult+from products.signals.backend.github_optional import ResearchAccessPolicyfrom products.signals.backend.models import SignalScoutConfig, SignalScoutRunfrom products.signals.backend.scout_harness.acting_user import resolve_scout_run_acting_userfrom products.signals.backend.scout_harness.derived_metadata import stamp_derived_metadata@@ -1013,6 +1014,7 @@ async def _spawn_and_run(# The config's `network_access` picks the sandbox env — and with it the egress policy the# provisioning layer enforces. Trusted (default) shares the research env; full gets its own# env name so its unrestricted policy can't be reasserted onto the shared one.+ github_optional = await database_sync_to_async(ResearchAccessPolicy.enabled, thread_sensitive=False)(team.id)if config.network_access == SignalScoutConfig.NetworkAccess.FULL:sandbox_env_name = SIGNALS_SCOUT_FULL_NETWORK_ENV_NAMEnetwork_access_level = tasks_facade.SandboxNetworkAccessLevel.FULL@@ -1158,6 +1160,7 @@ async def _spawn_and_run(runtime=runtime,experiment=experiment,github_guidance=github_guidance,+ github_optional=github_optional,business_knowledge_maintained=business_knowledge_maintained,background_backoff=background_backoff,repositories=repositories,@@ -1466,6 +1469,7 @@ def _create_run_row(runtime: str = "acp",experiment: FirstReportExperiment | None = None,github_guidance: bool = False,+ github_optional: bool = False,business_knowledge_maintained: bool = False,background_backoff: BackgroundBackoff | None = None,repositories: list[str] | None = None,@@ -1515,6 +1519,7 @@ def _create_run_row(# minted. Both can change between runs, so this is a fourth composition fork rather than a# property of the build.metadata["github_guidance"] = github_guidance+ metadata["github_optional"] = github_optional# Whether the business-knowledge section rendered — a fifth composition fork, resolved per run# from the team's flag + a maintained knowledge base (`_business_knowledge_maintained_for_team`).# Both inputs can change between runs, so like `github_guidance` this is stamped rather thandiff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.pyindex c0ad568b022e..3572c7845718 100644--- a/products/signals/backend/scout_harness/team_limits.py+++ b/products/signals/backend/scout_harness/team_limits.py@@ -24,9 +24,11 @@ import structlogimport posthoganalyticsfrom posthog.cloud_utils import is_cloud+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team+from products.signals.backend.github_optional import ResearchAccessPolicyfrom products.signals.backend.models import SignalScoutRunfrom products.signals.backend.scout_harness.limits import (COORDINATOR_INTERVAL_MINUTES,@@ -169,7 +171,7 @@ def _read_flag_payload() -> dict | None:ENROLL_ALL_TOKEN = "*"-@dataclass(frozen=True)+@frozenclass Enrollment:"""Parsed scout enrollment from the `signals-scout` flag payload.@@ -182,6 +184,7 @@ class Enrollment:wildcard: boolexplicit: set[int]skip: set[int]+ drained: bool = Falsedef _parse_enrollment(payload: dict | None) -> Enrollment:@@ -223,7 +226,7 @@ def _parse_enrollment(payload: dict | None) -> Enrollment:else:skip = set()- return Enrollment(wildcard=wildcard, explicit=explicit, skip=skip)+ return Enrollment(wildcard=wildcard, explicit=explicit, skip=skip, drained=payload.get("guaranteed_team_ids") == [])# Flag payload block that enrolls a pilot cohort in one scout that PostHog sets up without a person@@ -807,11 +810,11 @@ def _resolve_enrolled(canonical_team_id: int, enrollment: Enrollment) -> bool:A skipped team is never enrolled. Otherwise enrolled iff the wildcard is set (everyone is in —the UI gates whether they actually HAVE configs) or the team is in the explicit allowlist.Canonicalizes child-env ids the same way the coordinator does (`_is_team_enrolled`)."""- if _is_team_enrolled(canonical_team_id, enrollment.skip):+ if enrollment.drained or _is_team_enrolled(canonical_team_id, enrollment.skip):return Falseif enrollment.wildcard:return True- return _is_team_enrolled(canonical_team_id, enrollment.explicit)+ return _is_team_enrolled(canonical_team_id, enrollment.explicit) or ResearchAccessPolicy.enrolled(canonical_team_id)def team_is_enrolled(canonical_team_id: int) -> bool:diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.pyindex 0c8b01923e97..7270b54ada0c 100644--- a/products/signals/backend/scout_harness/tools/report.py+++ b/products/signals/backend/scout_harness/tools/report.py@@ -154,6 +154,7 @@ from products.signals.backend.scout_report.judge import (from products.signals.backend.slack_formatting import strip_chart_referencesfrom products.signals.backend.supersession import NO_IMPLEMENTATION_CONTEXTfrom products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.repo_selection_types import ReportResearchContextif TYPE_CHECKING:from products.signals.backend.scout_harness.trial_state import ScoutTrialStore, TrialReport@@ -1473,6 +1474,28 @@ def _settled_repository(report_id: str) -> str | None:return selection.repository if selection is not None else None+def _with_scout_research_context(+ team: Team, run: SignalScoutRun | None, selection: RepoSelectionResult | None+) -> RepoSelectionResult | None:+ metadata = (run.metadata or {}) if run is not None else {}+ if run is None or not metadata.get("github_optional"):+ return selection+ task_run = tasks_facade.get_task_run(run.task_run_id, team_id=team.id)+ state = task_run.state if task_run else {}+ if not metadata.get("repositories") and "github_read_access_available" not in state:+ return selection+ code_available = bool(metadata.get("repositories") or state.get("github_read_access_available"))+ if selection is None:+ selection = RepoSelectionResult(+ repository=None, reason="The scout did not select a repository.", autostart_eligible=False+ )+ selection.research_context = ReportResearchContext(+ mode="code" if code_available else "data_only",+ repository_status="available" if code_available else "github_unavailable",+ )+ return selection++async def _resolve_report_repository(*,team_id: int,@@ -2218,6 +2241,10 @@ async def emit_report(if surfacedelse None)+ if surfaced:+ repo_selection = await database_sync_to_async(_with_scout_research_context, thread_sensitive=False)(+ team, run, repo_selection+ )if surfaced and reviewers is not None:# Re-stamp owner provenance from the live owner set after the judge wait (see# `_stamp_owner_provenance`) — autostart trusts the stored stamp.@@ -2415,6 +2442,8 @@ def emit_report_sync(if surfacedelse None)+ if surfaced:+ repo_selection = _with_scout_research_context(team, run, repo_selection)if surfaced and reviewers is not None:# Re-stamp owner provenance from the live owner set after the judge wait (see# `_stamp_owner_provenance`) — autostart trusts the stored stamp.diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.pyindex 3c611a522ec0..d297a8cc83ba 100644--- a/products/signals/backend/scout_report/persistence.py+++ b/products/signals/backend/scout_report/persistence.py@@ -1317,7 +1317,9 @@ def set_scout_report_repository(# The whole selection is compared rather than the repository alone: a selection inferred from# the report's own text names the same repository with `autostart_eligible=False`, and a scout# naming it is the decision that lifts it, so that correction must still land.- if persisted_repo_selection(report_id) == selection:+ previous = persisted_repo_selection(report_id)+ selection.research_context = previous.research_context if previous is not None else None+ if previous == selection:logger.info("signals_scout.edit_report: repository unchanged",extra={"team_id": team_id, "report_id": report_id, "repository": repository},@@ -1432,6 +1434,7 @@ def set_scout_report_inferred_repository(with transaction.atomic():if not SignalReport.objects.select_for_update().filter(team_id=team_id, id=report_id).exists():raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")+ previous = persisted_repo_selection(report_id)SignalReportArtefact.append_status(team_id=team_id,report_id=report_id,@@ -1439,6 +1442,7 @@ def set_scout_report_inferred_repository(repository=repository,reason=INFERRED_REPOSITORY_REASON,autostart_eligible=False,+ research_context=previous.research_context if previous is not None else None,),attribution=attribution,reevaluate_autostart=False,diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex c9be5fc51e28..dfdd87f82c96 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -1497,6 +1497,29 @@ class ReportStartupFailureSerializer(serializers.Serializer):message = serializers.CharField(help_text="Safe explanation and suggested next action.")+class ReportResearchMode(TextChoices):+ CODE = "code", "Code context"+ DATA_ONLY = "data_only", "Project data"+++class ReportRepositoryStatus(TextChoices):+ AVAILABLE = "available", "Available"+ NO_INTEGRATION = "no_integration", "Not connected"+ NO_REPOSITORIES = "no_repositories", "No repositories"+ SELECTION_UNRESOLVED = "selection_unresolved", "No repository selected"+ GITHUB_UNAVAILABLE = "github_unavailable", "GitHub unavailable"+++class ReportResearchContextSerializer(serializers.Serializer):+ mode = serializers.ChoiceField(+ choices=ReportResearchMode.choices, help_text="Whether research had access to a repository."+ )+ repository_status = serializers.ChoiceField(+ choices=ReportRepositoryStatus.choices,+ help_text="Code availability when the report was researched; not a live integration health check.",+ )++class SignalReportSerializer(serializers.ModelSerializer):startup_failure = ReportStartupFailureSerializer(read_only=True,@@ -1504,6 +1527,9 @@ class SignalReportSerializer(serializers.ModelSerializer):required=False,help_text="Startup failure from the latest failed research attempt, when available.",)+ research_context = serializers.SerializerMethodField(+ help_text="Evidence available to the latest research pass. Null for legacy reports."+ )reviewer_assignment = serializers.SerializerMethodField(help_text="Reviewer control and state token for preparing an automatic proposal.")@@ -1735,6 +1761,7 @@ class SignalReportSerializer(serializers.ModelSerializer):"suppression_explanation","repo_slug","is_self_improvement_report",+ "research_context","is_suggested_reviewer","source_products","scout_name",@@ -1982,6 +2009,15 @@ class SignalReportSerializer(serializers.ModelSerializer):value = data.get("repository")return value if isinstance(value, str) and value else None+ @extend_schema_field(ReportResearchContextSerializer(allow_null=True))+ def get_research_context(self, obj: SignalReport) -> dict[str, str] | None:+ data = self._get_repo_selection_artefact_data(obj)+ context = data.get("research_context") if data else None+ if not isinstance(context, dict):+ return None+ serializer = ReportResearchContextSerializer(data=context)+ return dict(serializer.validated_data) if serializer.is_valid() else None+@extend_schema_field(ReportRankingSerializer)def get_ranking(self, obj: SignalReport) -> dict:request = self.context.get("request")diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex e88ccc6174ab..f8205ad352e4 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -27,6 +27,7 @@ from posthog.models.scoping.manager import TeamScopeErrorfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeater+from products.signals.backend.github_optional import ResearchAccessPolicyfrom products.signals.backend.models import (SignalReportAction,SignalReportArtefact,@@ -1076,7 +1077,7 @@ def _reconcile_wildcard_operational_configs(def _participating_teams(enrollment: Enrollment, reconcile_team_ids: set[int] | None = None) -> list[tuple[Team, bool]]:"""Resolve enrollment to canonical `Team`s to run scouts on, each tagged `needs_seed`.- Two ways a team participates:+ Three ways a team participates:- explicit `guaranteed_team_ids` (skip removed) → force-provisioned: `needs_seed=True`, so thetick seeds canonical skills + registers configs from nothing (the pinned internal projects).Adding an id in the flag UI enrolls it on the next tick with no manual seed; removing it (or@@ -1087,11 +1088,15 @@ def _participating_teams(enrollment: Enrollment, reconcile_team_ids: set[int] |explicit tag wins (it gets the seed pass).`reconcile_team_ids` joins the wildcard set too: a team whose only scouts are operationalones the harness left off has no enabled config, and it must still reach the reconcile.+ - completed GitHub-optional pilot activation while its project flag is enabled. Activation+ provisions the general scout, so this path needs no seed pass or separate fleet allowlist.Child envs canonicalize to their parent project; `skip_team_ids` is removed from both sets.Skip is subtracted AFTER canonicalizing both sides, so listing a child env in `guaranteed_team_ids`and its parent project in `skip_team_ids` (or the reverse) still hard-excludes the project — theraw ids differ but their canonical parent matches."""+ if enrollment.drained:+ return []skip_canonical = _canonicalize_team_ids(enrollment.skip)explicit = _canonicalize_team_ids(enrollment.explicit) - skip_canonical@@ -1114,6 +1119,7 @@ def _participating_teams(enrollment: Enrollment, reconcile_team_ids: set[int] |.distinct())wildcard_ids |= reconcile_team_ids or set()+ wildcard_ids |= ResearchAccessPolicy.enrolled_team_ids(exclude_team_ids=wildcard_ids | explicit | skip_canonical)wildcard_ids -= skip_canonicalwildcard_ids -= explicit # explicit wins the tag — it gets the seed pass belowdiff --git a/products/signals/backend/test/test_github_optional.py b/products/signals/backend/test/test_github_optional.pyindex 02af1f8811d6..7833825d66bf 100644--- a/products/signals/backend/test/test_github_optional.py+++ b/products/signals/backend/test/test_github_optional.py@@ -1,3 +1,5 @@+from types import SimpleNamespace+from posthog.test.base import BaseTestfrom unittest.mock import patch@@ -7,6 +9,9 @@ from posthog.models import Teamfrom posthog.models.integration import GitHubIntegration, Integrationfrom products.signals.backend.github_optional import GITHUB_OPTIONAL_FLAG, ResearchAccessPolicy+from products.signals.backend.models import SignalTeamConfig+from products.signals.backend.scout_harness.team_limits import _parse_enrollment, _resolve_enrolled+from products.signals.backend.temporal.agentic.scout_coordinator import _participating_teamsclass TestResearchAccessPolicy(BaseTest):@@ -27,3 +32,36 @@ class TestResearchAccessPolicy(BaseTest):with patch.object(GitHubIntegration, "installation_can_access_repository") as probe:assert ResearchAccessPolicy.repository_integration_id(self.team.id, repository) is Noneprobe.assert_not_called()++ @parameterized.expand(+ [+ (False, False, False, True),+ (True, False, True, True),+ (True, True, False, True),+ (True, False, False, False),+ (True, False, False, True, True),+ ]+ )+ def test_activation_enrolls_in_both_scheduled_and_manual_dispatch(+ self, enabled: bool, excluded: bool, expected: bool, completed: bool, drained: bool = False+ ) -> None:+ SignalTeamConfig.objects.update_or_create(+ team=self.team,+ defaults={+ "onboarding": {+ "draft": {"activation_mode": "github_optional"},+ "completed_at": "2026-10-26T00:00:00Z" if completed else None,+ }+ },+ )+ enrollment = _parse_enrollment({"skip_team_ids": [self.team.id] if excluded else []})+ if drained:+ enrollment = _parse_enrollment({"guaranteed_team_ids": []})+ with (+ patch("products.signals.backend.github_optional.feature_enabled_or_false", return_value=enabled),+ patch("posthoganalytics.default_client", SimpleNamespace(feature_flags=[])),+ ):+ assert _resolve_enrolled(self.team.id, enrollment) is expected+ assert (self.team.id in {team.id for team, _ in _participating_teams(enrollment)}) is expected+ with patch("posthoganalytics.default_client", None):+ assert ResearchAccessPolicy.enrolled_team_ids() == set()diff --git a/products/signals/backend/test/test_inbox_onboarding.py b/products/signals/backend/test/test_inbox_onboarding.pyindex d10ea654bec9..877e4ebce3e1 100644--- a/products/signals/backend/test/test_inbox_onboarding.py+++ b/products/signals/backend/test/test_inbox_onboarding.py@@ -294,6 +294,65 @@ class TestInboxOnboarding(APIBaseTest):== 1)+ @parameterized.expand(+ [+ (False, False, 400, False),+ (True, True, 400, False),+ (True, False, 200, False),+ (True, False, 200, True),+ (True, False, 403, True, False),+ ]+ )+ def test_pilot_activation_requires_eligibility_and_keeps_implementation_off(+ self, eligible: bool, automatic: bool, status: int, child_environment: bool, parent_task_editor: bool = True+ ) -> None:+ self.draft.update(+ activation_mode="github_optional", automatic_implementation=automatic, suggestions=[self.suggestion]+ )+ SignalScoutConfig.objects.create(team=self.team, skill_name=self.scout_skill_name, enabled=True, emit=True)+ activation_team = self.team+ if child_environment:+ activation_team = Team.objects.create(organization=self.organization, parent_team=self.team)+ SignalSourceConfig.objects.create(+ team=activation_team, source_product="error_tracking", source_type="issue_created", enabled=True+ )+ config, _ = SignalTeamConfig.objects.get_or_create(team=activation_team)+ config.onboarding = {"variant": "control"}+ config.save()+ with (+ patch("products.signals.backend.github_optional.ResearchAccessPolicy.enabled", return_value=eligible),+ patch("products.signals.backend.facade.onboarding.UserAccessControl") as parent_access,+ patch.object(+ InboxOnboardingReconciler,+ "has_repository",+ side_effect=AssertionError("Pilot must not depend on GitHub"),+ ),+ patch("products.signals.backend.tasks.launch_inbox_onboarding_job.delay") as launch,+ self.captureOnCommitCallbacks(execute=True),+ ):+ parent_access.return_value.check_access_level_for_resource.return_value = parent_task_editor+ response = self.client.post(+ f"/api/projects/{activation_team.id}/signals/onboarding/complete/", self.draft, format="json"+ )+ assert response.status_code == status, response.json()+ if child_environment and eligible and not automatic:+ parent_access.assert_called_once_with(user=self.user, team=self.team)+ parent_access.return_value.check_access_level_for_resource.assert_called_once_with("task", "editor")+ config.refresh_from_db()+ assert config.onboarding["variant"] == "control"+ if status == 200:+ assert config.autostart_enabled is False+ assert SignalTeamConfig.objects.get(team=self.team).autostart_enabled is False+ assert config.onboarding["completed_at"]+ assert config.onboarding["jobs"] == {"scout": "pending", "recommendations": "pending"}+ assert {call.args for call in launch.call_args_list} == {+ (activation_team.id, "scout"),+ (activation_team.id, "recommendations"),+ }+ else:+ assert not config.onboarding.get("completed_at")+ launch.assert_not_called()+def test_completed_quick_activation_checks_scout_write_access_before_retrying_jobs(self) -> None:self.draft["suggestions"] = [self.suggestion]config = SignalTeamConfig.objects.get(team=self.team)@@ -732,17 +791,20 @@ class TestInboxOnboardingActivation(BaseTest):("scout", 5, "test-sol", "flag_missing"),("recommendations", 0, "test-sol"),("recommendations", 5, "test-sol"),+ ("scout", 0, None, "workflow", True),+ ("recommendations", 0, None, "workflow", True),])def test_dispatch_retries_use_one_workflow_and_preserve_completed_jobs(- self, job: str, retry_count: int, arm: str | None, failure_source: str = "workflow"+ self, job: str, retry_count: int, arm: str | None, failure_source: str = "workflow", pilot: bool = False) -> None:self.organization.is_ai_data_processing_approved = Trueself.organization.save()config = SignalTeamConfig.objects.create(team=self.team,onboarding={- "variant": "test-github",+ "variant": "control" if pilot else "test-github",+ "draft": {"activation_mode": "github_optional"} if pilot else {},"first_report_variant": arm,"completed_at": timezone.now().isoformat(),"activated_by": self.user.pk,diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex cdb7272c2048..d3b79e421cf2 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -2787,6 +2787,7 @@ async def test_run_pins_sandbox_to_resolved_scout_model(return session, resultwith (+ patch("products.signals.backend.github_optional.ResearchAccessPolicy.enabled", return_value=True),patch("products.signals.backend.scout_harness.runner.MultiTurnSession.start", new=_capture_start),patch("products.signals.backend.scout_harness.runner.resolve_scout_model",@@ -2827,6 +2828,7 @@ async def test_run_pins_sandbox_to_resolved_scout_model(if value is not None}stamped = bridge.metadata or {}+ assert stamped["github_optional"] is Truerouted = {key: value for key, value in stamped.items() if key in _ROUTED_MODEL_KEYS}assert routed == expected_metadata# Wiring guards for the two regions written outside `_create_run_row`'s routing triple:diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.pyindex 3f3425823df0..7138d739e0fc 100644--- a/products/signals/backend/test/test_scout_report_api.py+++ b/products/signals/backend/test/test_scout_report_api.py@@ -221,10 +221,24 @@ class TestScoutReportAPI(APIBaseTest):assert artefact is not Nonereturn [entry["github_login"] for entry in json.loads(artefact.content)]- def test_emit_report_authors_ready_report(self) -> None:+ @parameterized.expand([(False, None), (True, False), (True, True)])+ def test_emit_report_authors_ready_report(self, pilot: bool, code_access: bool | None) -> None:run = _make_run(self.team)+ if code_access is not None:+ run.metadata = {**(run.metadata or {}), "github_guidance": True, "github_optional": pilot}+ run.save(update_fields=["metadata"])+ TaskRun.objects.filter(pk=run.task_run_id, team_id=self.team.id).update(+ state={"github_read_access_available": code_access}+ )metric = self._affected_users_metric()- with _safe_judge(), patch(EMBED_PATH) as embed_mock:+ with (+ _safe_judge(),+ patch(EMBED_PATH) as embed_mock,+ patch(+ "products.signals.backend.github_optional.ResearchAccessPolicy.enabled",+ side_effect=AssertionError("Use dispatch snapshot"),+ ),+ ):response = self.client.post(self._emit_url(str(run.id)), data=self._payload(metrics=[metric]), format="json")@@ -237,6 +251,10 @@ class TestScoutReportAPI(APIBaseTest):assert len(report.metrics) == 1assert report.metrics[0]["metric_id"] == "affected-users"assert report.metrics[0]["query"] == metric["query"]+ selection = self._latest_artefact(str(report.id), SignalReportArtefact.ArtefactType.REPO_SELECTION)+ if pilot:+ assert selection is not None+ assert json.loads(selection.content)["research_context"]["mode"] == ("code" if code_access else "data_only")embed_mock.assert_called_once()@parameterized.expand([(False, False), (True, False), (True, True)])diff --git a/products/signals/backend/test/test_scout_report_persistence.py b/products/signals/backend/test/test_scout_report_persistence.pyindex 3f8932017a45..8b689203a29f 100644--- a/products/signals/backend/test/test_scout_report_persistence.py+++ b/products/signals/backend/test/test_scout_report_persistence.py@@ -38,6 +38,7 @@ from products.signals.backend.models import (SignalSpend,)from products.signals.backend.report_charts import MAX_REPORT_CHARTS, ReportChart+from products.signals.backend.report_generation.select_repo import persisted_repo_selectionfrom products.signals.backend.report_metrics import ReportMetricfrom products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPT_LENGTH, MAX_SUGGESTED_PROMPTSfrom products.signals.backend.reviewer_rules import ReviewerRules@@ -63,6 +64,7 @@ from products.signals.backend.scout_report.judge import resolve_authored_report_from products.signals.backend.scout_report.persistence import _report_metrics_unchangedfrom products.signals.backend.slack_inbox_notifications import resolve_suggested_reviewer_user_idsfrom products.signals.backend.spend import register_report_task_spend, signal_spend_totals+from products.tasks.backend.facade.repo_selection_types import ReportResearchContext, RepoSelectionResultfrom products.tasks.backend.models import Task, TaskRunPERSISTENCE_MODULE = "products.signals.backend.scout_report.persistence"@@ -978,20 +980,40 @@ class TestScoutReportRepository(BaseTest):assert self._set(report_id, repository) is Falseassert self._set(report_id, "acme/other") is True- def test_naming_an_already_inferred_repository_is_a_change(self) -> None:+ @parameterized.expand([False, True])+ def test_naming_an_already_inferred_repository_is_a_change(self, with_context: bool) -> None:# An inferred selection names the repository the report links, and is stamped ineligible for# autostart because the report never asked for a pull request. A scout naming the same one is# the decision that lifts it, so comparing the repository alone would drop the correction and# leave the report unable to open a draft pull request.report_id = self._create()+ context = ReportResearchContext(mode="data_only", repository_status="no_integration") if with_context else None+ if context is not None:+ SignalReportArtefact.append_status(+ team_id=self.team.id,+ report_id=report_id,+ content=RepoSelectionResult(+ repository="example/previous",+ reason="Inferred from the report",+ autostart_eligible=False,+ research_context=context,+ ),+ attribution=ArtefactAttribution.system(),+ reevaluate_autostart=False,+ )set_scout_report_inferred_repository(team_id=self.team.id,report_id=report_id,repository="acme/widgets",attribution=ArtefactAttribution.system(),)+ inferred = persisted_repo_selection(report_id)+ assert inferred is not None and inferred.research_context == contextassert self._set(report_id, "acme/widgets") is True+ corrected = persisted_repo_selection(report_id)+ assert corrected is not None and corrected.research_context == context+ assert self._set(report_id, "acme/widgets") is Falseselection = (SignalReportArtefact.objects.filter(report_id=report_id, type=SignalReportArtefact.ArtefactType.REPO_SELECTIONdiff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 160a792a6390..a10e12716d43 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -3133,13 +3133,18 @@ class TestSignalReportListAPI(APIBaseTest):assert row["dismissal_reason"] == "analysis_wrong"def _repo_selection_artefact(- self, report: SignalReport, *, repository: str | None, created_at: datetime | None = None+ self,+ report: SignalReport,+ *,+ repository: str | None,+ created_at: datetime | None = None,+ research_context: dict[str, str] | None = None,) -> SignalReportArtefact:art = SignalReportArtefact(team=self.team,report=report,type=SignalReportArtefact.ArtefactType.REPO_SELECTION,- content=json.dumps({"repository": repository, "reason": "pick"}),+ content=json.dumps({"repository": repository, "reason": "pick", "research_context": research_context}),)art.save()if created_at is not None:@@ -3167,14 +3172,16 @@ class TestSignalReportListAPI(APIBaseTest):assert reports[0].prefetched_repo_selection_artefacts == [latest]- def test_list_repo_slug_null_without_selection(self):+ @parameterized.expand([(None,), ({"mode": "data_only", "repository_status": "no_integration"},)])+ def test_list_repo_slug_null_without_selection(self, research_context: dict[str, str] | None) -> None:report = self._create_report()- self._repo_selection_artefact(report, repository=None)+ self._repo_selection_artefact(report, repository=None, research_context=research_context)response = self.client.get(self._list_url())assert response.status_code == status.HTTP_200_OKrow = next(r for r in response.json()["results"] if r["id"] == str(report.id))assert row["repo_slug"] is None+ assert row["research_context"] == research_context@parameterized.expand([diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 94306d4c082d..7669d75f40f1 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -855,6 +855,15 @@ export interface InboxOnboardingJobsApi {recommendations: InboxOnboardingJobStatusEnumApi}+/**+ * * `github_optional` - GitHub optional+ */+export type InboxActivationModeEnumApi = (typeof InboxActivationModeEnumApi)[keyof typeof InboxActivationModeEnumApi]++export const InboxActivationModeEnumApi = {+ GithubOptional: 'github_optional',+} as const+/*** * `signals` - Signals* * `scouts` - Scouts@@ -1363,6 +1372,10 @@ export interface ScoutSuggestionItemApi {}export interface InboxOnboardingDraftApi {+ /** Activate the GitHub-optional pilot. Requires project eligibility and leaves automatic implementation off.+ *+ * * `github_optional` - GitHub optional */+ activation_mode?: InboxActivationModeEnumApi/** Step to resume after returning.** * `signals` - Signals@@ -1411,6 +1424,8 @@ export const InboxOnboardingVariantEnumApi = {} as constexport interface InboxOnboardingStateApi {+ /** Whether this project can activate Self-driving without connecting GitHub. */+ github_optional_available?: boolean/** Whether the current user can receive an in-app notification when this investigation finishes. */first_report_completion_notification?: boolean/**@@ -1857,6 +1872,51 @@ export const SignalReportSuppressionSourceEnumApi = {System: 'system',} as const+/**+ * * `code` - Code context+ * * `data_only` - Project data+ */+export type ReportResearchModeEnumApi = (typeof ReportResearchModeEnumApi)[keyof typeof ReportResearchModeEnumApi]++export const ReportResearchModeEnumApi = {+ Code: 'code',+ DataOnly: 'data_only',+} as const++/**+ * * `available` - Available+ * * `no_integration` - Not connected+ * * `no_repositories` - No repositories+ * * `selection_unresolved` - No repository selected+ * * `github_unavailable` - GitHub unavailable+ */+export type ReportRepositoryStatusEnumApi =+ (typeof ReportRepositoryStatusEnumApi)[keyof typeof ReportRepositoryStatusEnumApi]++export const ReportRepositoryStatusEnumApi = {+ Available: 'available',+ NoIntegration: 'no_integration',+ NoRepositories: 'no_repositories',+ SelectionUnresolved: 'selection_unresolved',+ GithubUnavailable: 'github_unavailable',+} as const++export interface ReportResearchContextApi {+ /** Whether research had access to a repository.+ *+ * * `code` - Code context+ * * `data_only` - Project data */+ mode: ReportResearchModeEnumApi+ /** Code availability when the report was researched; not a live integration health check.+ *+ * * `available` - Available+ * * `no_integration` - Not connected+ * * `no_repositories` - No repositories+ * * `selection_unresolved` - No repository selected+ * * `github_unavailable` - GitHub unavailable */+ repository_status: ReportRepositoryStatusEnumApi+}+/*** * `unknown` - Unknown* * `draft` - Draft@@ -2294,6 +2354,8 @@ export interface SignalReportListApi {readonly repo_slug: string | null/** Whether this is a scout self-improvement report. Most update a team-owned skill in the skills store, but reports with a selected repository can still produce a pull request. */readonly is_self_improvement_report: boolean+ /** Evidence available to the latest research pass. Null for legacy reports. */+ readonly research_context: ReportResearchContextApi | nullreadonly is_suggested_reviewer: boolean/** Distinct source products contributing signals to this report (from ClickHouse). */readonly source_products: readonly string[]@@ -2548,6 +2610,8 @@ export interface SignalReportApi {readonly repo_slug: string | null/** Whether this is a scout self-improvement report. Most update a team-owned skill in the skills store, but reports with a selected repository can still produce a pull request. */readonly is_self_improvement_report: boolean+ /** Evidence available to the latest research pass. Null for legacy reports. */+ readonly research_context: ReportResearchContextApi | nullreadonly is_suggested_reviewer: boolean/** Distinct source products contributing signals to this report (from ClickHouse). */readonly source_products: readonly string[]diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 5662c8990922..e15866405345 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -128,6 +128,13 @@ export const signalsOnboardingCreateBodyActivationScoutsItemMax = 200export const signalsOnboardingCreateBodyActivationScoutsMax = 50export const SignalsOnboardingCreateBody = /* @__PURE__ */ zod.object({+ activation_mode: zod+ .enum(['github_optional'])+ .describe('\* `github_optional` - GitHub optional')+ .optional()+ .describe(+ 'Activate the GitHub-optional pilot. Requires project eligibility and leaves automatic implementation off.\n\n\* `github_optional` - GitHub optional'+ ),step: zod.enum(['signals', 'scouts', 'github']).describe('\* `signals` - Signals\n\* `scouts` - Scouts\n\* `github` - GitHub')@@ -367,6 +374,13 @@ export const signalsOnboardingCompleteCreateBodyActivationScoutsItemMax = 200export const signalsOnboardingCompleteCreateBodyActivationScoutsMax = 50export const SignalsOnboardingCompleteCreateBody = /* @__PURE__ */ zod.object({+ activation_mode: zod+ .enum(['github_optional'])+ .describe('\* `github_optional` - GitHub optional')+ .optional()+ .describe(+ 'Activate the GitHub-optional pilot. Requires project eligibility and leaves automatic implementation off.\n\n\* `github_optional` - GitHub optional'+ ),step: zod.enum(['signals', 'scouts', 'github']).describe('\* `signals` - Signals\n\* `scouts` - Scouts\n\* `github` - GitHub')diff --git a/products/signals/frontend/inbox/logics/inboxSetupLogic.ts b/products/signals/frontend/inbox/logics/inboxSetupLogic.tsindex 796de98d808f..030f0ec18c55 100644--- a/products/signals/frontend/inbox/logics/inboxSetupLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxSetupLogic.ts@@ -99,6 +99,7 @@ export interface inboxSetupLogicValues {hasGithubIntegration: booleaninProgress: booleanisFinalStep: boolean+ isGithubOptionalSetup: booleanisQuickSetup: booleanisTreatment: booleanquickSetupDraft: InboxOnboardingDraftApi | null@@ -234,7 +235,11 @@ export interface inboxSetupLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxSetupLogicMeta {__keaTypeGenInternalSelectorTypes: {- isQuickSetup: (experimentVariant: 'control' | 'test-github' | 'test-ui' | null) => boolean+ isGithubOptionalSetup: (savedState: InboxOnboardingStateApi | null) => boolean+ isQuickSetup: (+ experimentVariant: 'control' | 'test-github' | 'test-ui' | null,+ isGithubOptionalSetup: boolean+ ) => booleanshouldResumeQuickSetup: (isQuickSetup: boolean,quickSetupReady: boolean,@@ -248,7 +253,8 @@ export interface inboxSetupLogicMeta {sources: InboxSetupSource[],visionScanners: ReplayScannerApi[] | null,scoutConfigs: SignalScoutConfigApi[] | null,- featureFlags: FeatureFlagsSet+ featureFlags: FeatureFlagsSet,+ isGithubOptionalSetup: boolean) => InboxOnboardingDraftApi | nullquickSetupReady: (ready: boolean,@@ -265,7 +271,8 @@ export interface inboxSetupLogicMeta {isTreatment: boolean,started: boolean,savedState: InboxOnboardingStateApi | null,- resumingSetup: boolean+ resumingSetup: boolean,+ isGithubOptionalSetup: boolean) => booleansources: (sourceConfigs: SignalSourceConfig[] | null,@@ -447,9 +454,14 @@ export const inboxSetupLogic = kea<inboxSetupLogicType>([started: [false, { startSetup: () => true, openSetup: () => true }],}),selectors({+ isGithubOptionalSetup: [+ (s) => [s.savedState],+ (state: InboxOnboardingStateApi | null): boolean => state?.github_optional_available === true,+ ],isQuickSetup: [- (s) => [s.experimentVariant],- (variant: 'control' | 'test-github' | 'test-ui' | null): boolean => variant === 'test-github',+ (s) => [s.experimentVariant, s.isGithubOptionalSetup],+ (variant: 'control' | 'test-github' | 'test-ui' | null, pilot: boolean): boolean =>+ pilot || variant === 'test-github',],shouldResumeQuickSetup: [(s) => [@@ -473,18 +485,20 @@ export const inboxSetupLogic = kea<inboxSetupLogicType>([quick && ready && connected && params.onboarding_step === 'quick' && !saving && !error && !completed,],quickSetupDraft: [- (s) => [s.sources, s.visionScanners, s.scoutConfigs, s.featureFlags],+ (s) => [s.sources, s.visionScanners, s.scoutConfigs, s.featureFlags, s.isGithubOptionalSetup],(sources: InboxSetupSource[],scanners: ReplayScannerApi[] | null,configs: SignalScoutConfigApi[] | null,- flags: FeatureFlagsSet+ flags: FeatureFlagsSet,+ pilot: boolean): InboxOnboardingDraftApi | null => {const quickDraft = quickInboxSetupDraft(sources, scanners ?? [], configs ?? [])return quickDraft? {...quickDraft,- automatic_implementation: !flags[FEATURE_FLAGS.SELF_DRIVING_UBP],+ automatic_implementation: !pilot && !flags[FEATURE_FLAGS.SELF_DRIVING_UBP],+ ...(pilot ? { activation_mode: 'github_optional' as const } : {}),}: null},@@ -515,9 +529,14 @@ export const inboxSetupLogic = kea<inboxSetupLogicType>([['signals', 'scouts', 'github', 'quick'].includes(String(params.onboarding_step)),],usesFocusedSetup: [- (s) => [s.isTreatment, s.started, s.savedState, s.resumingSetup],- (treatment: boolean, started: boolean, state: InboxOnboardingStateApi | null, resuming: boolean): boolean =>- treatment || started || !!state?.draft || resuming,+ (s) => [s.isTreatment, s.started, s.savedState, s.resumingSetup, s.isGithubOptionalSetup],+ (+ treatment: boolean,+ started: boolean,+ state: InboxOnboardingStateApi | null,+ resuming: boolean,+ pilot: boolean+ ): boolean => pilot || treatment || started || !!state?.draft || resuming,],sources: [(s) => [@@ -564,9 +583,11 @@ export const inboxSetupLogic = kea<inboxSetupLogicType>([sources,(scanners ?? []).map((scanner) => scanner.id))- return flags[FEATURE_FLAGS.SELF_DRIVING_UBP]- ? reconciled- : { ...reconciled, automatic_implementation: true }+ return reconciled.activation_mode === 'github_optional'+ ? { ...reconciled, automatic_implementation: false }+ : flags[FEATURE_FLAGS.SELF_DRIVING_UBP]+ ? reconciled+ : { ...reconciled, automatic_implementation: true }},],scoutsLoading: [@@ -660,7 +681,7 @@ export const inboxSetupLogic = kea<inboxSetupLogicType>([): string | undefined =>!ready? 'Loading setup'- : !connected+ : !connected && draft.activation_mode !== 'github_optional'? 'Connect GitHub to continue': !sourceCount && !draft.suggestions.length? 'Select a signal source or scout'@@ -1065,7 +1086,7 @@ export const inboxSetupLogic = kea<inboxSetupLogicType>([let draft = values.draftconst projectId = String(values.currentTeamId)try {- if (values.isQuickSetup) {+ if (values.isQuickSetup && !values.isGithubOptionalSetup) {const state = await signalsOnboardingExposeCreate(projectId, { variant: 'test-github' })actions.setSavedState(state)if (state.variant !== 'test-github') {diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex 21604aeda238..cedc0b6a26b1 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -96,6 +96,7 @@ export const ACTIONABLE_ACTIONABILITY_VALUES: SignalReportActionability[] = [export interface SignalReport extends Pick<SignalReportApi, 'monitoring_started_at'> {startup_failure?: SignalReportApi['startup_failure']+ repo_slug?: SignalReportApi['repo_slug']pull_requests?: readonly SignalReportPullRequestApi[]assignee?: SignalReportAssigneeApi | nullid: string@@ -135,8 +136,6 @@ export interface SignalReport extends Pick<SignalReportApi, 'monitoring_started_scout_name?: string | null/** Whether the report proposes an improvement to a scout. */is_self_improvement_report?: boolean- /** Selected code repository, when the report has one. */- repo_slug?: string | null/** PR URL from the latest implementation task run, if available. */implementation_pr_url?: string | null/** Whether that implementation PR is merged, per the GitHub webhook. Status doesn't imply it: adiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 025b10d8e00f..b38bc19f3b26 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -57618,6 +57618,11 @@ export namespace Schemas {total: number;}+ export interface GitHubRepositoryAccessResponse {+ /** Whether a live GitHub request confirmed repository access. */+ available: boolean;+ }+export interface GitHubSource {/** Source id: pass back as `source_id` (with `repo`) to read this repository. */id: string;@@ -64053,6 +64058,16 @@ export namespace Schemas {last_error: string | null;}+ /**+ * * `github_optional` - GitHub optional+ */+ export type InboxActivationModeEnum = typeof InboxActivationModeEnum[keyof typeof InboxActivationModeEnum];+++ export const InboxActivationModeEnum = {+ GithubOptional: 'github_optional',+ } as const;+/*** * `signals` - Signals* * `scouts` - Scouts@@ -64551,6 +64566,10 @@ export namespace Schemas {}export interface InboxOnboardingDraft {+ /** Activate the GitHub-optional pilot. Requires project eligibility and leaves automatic implementation off.+ *+ * * `github_optional` - GitHub optional */+ activation_mode?: InboxActivationModeEnum;/** Step to resume after returning.** * `signals` - Signals@@ -64641,6 +64660,8 @@ export namespace Schemas {}export interface InboxOnboardingState {+ /** Whether this project can activate Self-driving without connecting GitHub. */+ github_optional_available?: boolean;/** Whether the current user can receive an in-app notification when this investigation finishes. */first_report_completion_notification?: boolean;/**@@ -80137,6 +80158,52 @@ export namespace Schemas {System: 'system',} as const;+ /**+ * * `code` - Code context+ * * `data_only` - Project data+ */+ export type ReportResearchModeEnum = typeof ReportResearchModeEnum[keyof typeof ReportResearchModeEnum];+++ export const ReportResearchModeEnum = {+ Code: 'code',+ DataOnly: 'data_only',+ } as const;++ /**+ * * `available` - Available+ * * `no_integration` - Not connected+ * * `no_repositories` - No repositories+ * * `selection_unresolved` - No repository selected+ * * `github_unavailable` - GitHub unavailable+ */+ export type ReportRepositoryStatusEnum = typeof ReportRepositoryStatusEnum[keyof typeof ReportRepositoryStatusEnum];+++ export const ReportRepositoryStatusEnum = {+ Available: 'available',+ NoIntegration: 'no_integration',+ NoRepositories: 'no_repositories',+ SelectionUnresolved: 'selection_unresolved',+ GithubUnavailable: 'github_unavailable',+ } as const;++ export interface ReportResearchContext {+ /** Whether research had access to a repository.+ *+ * * `code` - Code context+ * * `data_only` - Project data */+ mode: ReportResearchModeEnum;+ /** Code availability when the report was researched; not a live integration health check.+ *+ * * `available` - Available+ * * `no_integration` - Not connected+ * * `no_repositories` - No repositories+ * * `selection_unresolved` - No repository selected+ * * `github_unavailable` - GitHub unavailable */+ repository_status: ReportRepositoryStatusEnum;+ }+/*** * `unknown` - Unknown* * `draft` - Draft@@ -80559,6 +80626,8 @@ export namespace Schemas {readonly repo_slug: string | null;/** Whether this is a scout self-improvement report. Most update a team-owned skill in the skills store, but reports with a selected repository can still produce a pull request. */readonly is_self_improvement_report: boolean;+ /** Evidence available to the latest research pass. Null for legacy reports. */+ readonly research_context: ReportResearchContext | null;readonly is_suggested_reviewer: boolean;/** Distinct source products contributing signals to this report (from ClickHouse). */readonly source_products: readonly string[];@@ -103399,6 +103468,8 @@ export namespace Schemas {readonly repo_slug: string | null;/** Whether this is a scout self-improvement report. Most update a team-owned skill in the skills store, but reports with a selected repository can still produce a pull request. */readonly is_self_improvement_report: boolean;+ /** Evidence available to the latest research pass. Null for legacy reports. */+ readonly research_context: ReportResearchContext | null;readonly is_suggested_reviewer: boolean;/** Distinct source products contributing signals to this report (from ClickHouse). */readonly source_products: readonly string[];@@ -137386,6 +137457,14 @@ export namespace Schemas {search?: string;};+ export type IntegrationsGithubRepositoryAccessRetrieveParams = {+ /**+ * Repository in owner/repo format. Omit to check access to any repository.+ * @minLength 1+ */+ repository?: string;+ };+export type IntegrationsGithubTeamsRetrieveParams = {/*** Maximum number of teams to return per request (max 500).