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(experiments): team default repository for flag cleanup PRs (#78200)

Juraj Majerik152fdd4e831a
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
index 72e174379b45..8f90ba8edfc9 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
@@ -15,7 +15,8 @@ import {
Link,
} from '@posthog/lemon-ui'
-import { FEATURE_FLAGS } from 'lib/constants'
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
@@ -222,6 +223,7 @@ export function FinishExperimentModal(): JSX.Element {
const [releaseToEveryone, setReleaseToEveryone] = useState<boolean>(false)
const [openCleanupPr, setOpenCleanupPr] = useState<boolean>(false)
const [cleanupRepository, setCleanupRepository] = useState<string | null>(null)
+ const [setAsTeamDefault, setSetAsTeamDefault] = useState<boolean>(false)
// Reset on open, not only on close: a failed end/ship closes the modal through the logic
// without this component's close handler, which would leave a stale pick for the next open.
@@ -229,6 +231,7 @@ export function FinishExperimentModal(): JSX.Element {
if (isFinishExperimentModalOpen) {
setOpenCleanupPr(false)
setCleanupRepository(null)
+ setSetAsTeamDefault(false)
}
}, [isFinishExperimentModalOpen])
@@ -240,6 +243,12 @@ export function FinishExperimentModal(): JSX.Element {
// With several connected repositories and none saved on the experiment, the backend would
// skip the cleanup rather than guess — so a pick is required here.
const cleanupNeedsRepositoryPick = cleanupTarget?.source === 'ambiguous'
+ // The team default is environment-wide configuration, so offering to set it follows the
+ // same admin bar as the experiments_config settings endpoint.
+ const teamDefaultRestrictionReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: OrganizationMembershipLevel.Admin,
+ })
const aggregationTargetName =
experiment.filters.aggregation_group_type_index != null
@@ -249,6 +258,7 @@ export function FinishExperimentModal(): JSX.Element {
const handleClose = (): void => {
setOpenCleanupPr(false)
setCleanupRepository(null)
+ setSetAsTeamDefault(false)
restoreUnmodifiedExperiment()
closeFinishExperimentModal()
}
@@ -256,14 +266,16 @@ export function FinishExperimentModal(): JSX.Element {
const handleEndExperiment = (): void => {
const withCleanupPr = cleanupPrAvailable && openCleanupPr
const repository = withCleanupPr && cleanupNeedsRepositoryPick ? cleanupRepository : null
+ const repositoryAsTeamDefault = !!repository && setAsTeamDefault && !teamDefaultRestrictionReason
if (isSingleVariantShipped || !selectedVariantKey) {
- endExperimentWithoutShipping(withCleanupPr, repository)
+ endExperimentWithoutShipping(withCleanupPr, repository, repositoryAsTeamDefault)
} else {
finishExperiment({
selectedVariantKey,
releaseToEveryone,
openCleanupPr: withCleanupPr,
repository,
+ setRepositoryAsTeamDefault: repositoryAsTeamDefault,
})
}
}
@@ -449,17 +461,27 @@ export function FinishExperimentModal(): JSX.Element {
</div>
)}
{openCleanupPr && cleanupNeedsRepositoryPick && (
- <LemonInputSelect
- mode="single"
- value={cleanupRepository ? [cleanupRepository] : []}
- onChange={(repositories) => setCleanupRepository(repositories[0] ?? null)}
- options={(cleanupTarget?.candidates ?? []).map((repository) => ({
- key: repository,
- label: repository,
- }))}
- placeholder="Select a repository"
- data-attr="experiment-cleanup-repository"
- />
+ <>
+ <LemonInputSelect
+ mode="single"
+ value={cleanupRepository ? [cleanupRepository] : []}
+ onChange={(repositories) => setCleanupRepository(repositories[0] ?? null)}
+ options={(cleanupTarget?.candidates ?? []).map((repository) => ({
+ key: repository,
+ label: repository,
+ }))}
+ placeholder="Select a repository"
+ data-attr="experiment-cleanup-repository"
+ />
+ {!teamDefaultRestrictionReason && (
+ <LemonCheckbox
+ checked={setAsTeamDefault}
+ onChange={setSetAsTeamDefault}
+ data-attr="experiment-cleanup-repository-team-default"
+ label="Use this repository for all experiments in this project"
+ />
+ )}
+ </>
)}
</div>
)}
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 612d9b880fb1..2b4d90753dfb 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -871,33 +871,40 @@ export interface experimentLogicActions {
}
endExperiment: (
openCleanupPr?: boolean,
- repository?: string | null
+ repository?: string | null,
+ setRepositoryAsTeamDefault?: boolean
) => {
openCleanupPr: boolean
repository: string | null
+ setRepositoryAsTeamDefault: boolean
}
endExperimentWithoutShipping: (
openCleanupPr?: boolean,
- repository?: string | null
+ repository?: string | null,
+ setRepositoryAsTeamDefault?: boolean
) => {
openCleanupPr: boolean
repository: string | null
+ setRepositoryAsTeamDefault: boolean
}
finishExperiment: ({
selectedVariantKey,
releaseToEveryone,
openCleanupPr,
repository,
+ setRepositoryAsTeamDefault,
}: {
openCleanupPr?: boolean
releaseToEveryone: boolean
repository?: string | null
selectedVariantKey: string
+ setRepositoryAsTeamDefault?: boolean
}) => {
openCleanupPr: boolean
releaseToEveryone: boolean
repository: string | null
selectedVariantKey: string
+ setRepositoryAsTeamDefault: boolean
}
freezeExposure: () => {
value: true
@@ -1530,29 +1537,42 @@ export const experimentLogic = kea<experimentLogicType>([
changeExperimentStartDate: (startDate: string) => ({ startDate }),
changeExperimentEndDate: (endDate: string) => ({ endDate }),
launchExperiment: true,
- endExperiment: (openCleanupPr: boolean = false, repository: string | null = null) => ({
+ endExperiment: (
+ openCleanupPr: boolean = false,
+ repository: string | null = null,
+ setRepositoryAsTeamDefault: boolean = false
+ ) => ({
openCleanupPr,
repository,
+ setRepositoryAsTeamDefault,
}),
- endExperimentWithoutShipping: (openCleanupPr: boolean = false, repository: string | null = null) => ({
+ endExperimentWithoutShipping: (
+ openCleanupPr: boolean = false,
+ repository: string | null = null,
+ setRepositoryAsTeamDefault: boolean = false
+ ) => ({
openCleanupPr,
repository,
+ setRepositoryAsTeamDefault,
}),
finishExperiment: ({
selectedVariantKey,
releaseToEveryone,
openCleanupPr,
repository,
+ setRepositoryAsTeamDefault,
}: {
selectedVariantKey: string
releaseToEveryone: boolean
openCleanupPr?: boolean
repository?: string | null
+ setRepositoryAsTeamDefault?: boolean
}) => ({
selectedVariantKey,
releaseToEveryone,
openCleanupPr: openCleanupPr ?? false,
repository: repository ?? null,
+ setRepositoryAsTeamDefault: setRepositoryAsTeamDefault ?? false,
}),
pauseExperiment: true,
resumeExperiment: true,
@@ -2426,7 +2446,7 @@ export const experimentLogic = kea<experimentLogicType>([
values.experiment && eventUsageLogic.actions.reportExperimentEndDateChange(values.experiment, endDate)
actions.refreshExperimentResults(true, 'config_change')
},
- endExperiment: async ({ openCleanupPr, repository }) => {
+ endExperiment: async ({ openCleanupPr, repository, setRepositoryAsTeamDefault }) => {
actions.setEndExperimentLoading(true)
try {
const response: Experiment = await api.create(
@@ -2436,6 +2456,7 @@ export const experimentLogic = kea<experimentLogicType>([
conclusion_comment: values.experiment.conclusion_comment,
open_cleanup_pr: openCleanupPr,
...(repository ? { repository } : {}),
+ ...(setRepositoryAsTeamDefault ? { set_repository_as_team_default: true } : {}),
}
)
actions.setExperiment(response)
@@ -2446,8 +2467,8 @@ export const experimentLogic = kea<experimentLogicType>([
actions.setEndExperimentLoading(false)
}
},
- endExperimentWithoutShipping: async ({ openCleanupPr, repository }) => {
- actions.endExperiment(openCleanupPr, repository)
+ endExperimentWithoutShipping: async ({ openCleanupPr, repository, setRepositoryAsTeamDefault }) => {
+ actions.endExperiment(openCleanupPr, repository, setRepositoryAsTeamDefault)
actions.closeFinishExperimentModal()
lemonToast.success('Experiment ended successfully')
@@ -2762,7 +2783,13 @@ export const experimentLogic = kea<experimentLogicType>([
})
}
},
- finishExperiment: async ({ selectedVariantKey, releaseToEveryone, openCleanupPr, repository }) => {
+ finishExperiment: async ({
+ selectedVariantKey,
+ releaseToEveryone,
+ openCleanupPr,
+ repository,
+ setRepositoryAsTeamDefault,
+ }) => {
actions.setEndExperimentLoading(true)
try {
const response: Experiment = await api.create(
@@ -2774,6 +2801,7 @@ export const experimentLogic = kea<experimentLogicType>([
conclusion_comment: values.experiment.conclusion_comment,
open_cleanup_pr: openCleanupPr,
...(repository ? { repository } : {}),
+ ...(setRepositoryAsTeamDefault ? { set_repository_as_team_default: true } : {}),
}
)
actions.setExperiment(response)
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 3d4a55509541..62d8f5576f12 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -116,7 +116,7 @@ logger = structlog.get_logger(__name__)
# experiment ends. Evaluated as a project-group flag — see _cleanup_pr_flag_enabled.
EXPERIMENT_CLEANUP_PR_FLAG = "experiment-flag-cleanup-pr"
-CleanupRepositorySource = Literal["explicit", "single_repo", "ambiguous", "no_integration"]
+CleanupRepositorySource = Literal["explicit", "team_default", "single_repo", "ambiguous", "no_integration"]
class CleanupRepositoryTarget(TypedDict):
@@ -2481,6 +2481,7 @@ class ExperimentService:
conclusion_comment: str | None = None,
open_cleanup_pr: bool = False,
repository: str | None = None,
+ set_repository_as_team_default: bool = False,
request: Any | None = None,
) -> Experiment:
"""End a running experiment: set end_date and mark as stopped.
@@ -2500,7 +2501,11 @@ class ExperimentService:
self._bump_version_and_save(experiment, update_fields=["end_date", "conclusion", "conclusion_comment"])
self._report_experiment_ended(
- experiment, request=request, open_cleanup_pr=open_cleanup_pr, repository=repository
+ experiment,
+ request=request,
+ open_cleanup_pr=open_cleanup_pr,
+ repository=repository,
+ set_repository_as_team_default=set_repository_as_team_default,
)
return experiment
@@ -2521,7 +2526,11 @@ class ExperimentService:
)
def _maybe_open_cleanup_pr(
- self, experiment: Experiment, open_cleanup_pr: bool, requested_repository: str | None = None
+ self,
+ experiment: Experiment,
+ open_cleanup_pr: bool,
+ requested_repository: str | None = None,
+ set_repository_as_team_default: bool = False,
) -> None:
"""When opted in (the checkbox) and the team's gate flag is on, open a draft PR that removes the
experiment's feature-flag code, via the Tasks engine.
@@ -2548,10 +2557,11 @@ class ExperimentService:
)
return
- if requested_repository and target["source"] == "explicit":
+ picked_repository = requested_repository if target["source"] == "explicit" else None
+ if picked_repository:
# Persist the request's choice only now that it passed the installation check —
# a typo'd or stale name must not stick and block the single-repo fallback later.
- experiment.repository = requested_repository
+ experiment.repository = picked_repository
experiment.save(update_fields=["repository"])
plan = cleanup_plan(conclusion, experiment.feature_flag.variants or [])
@@ -2581,6 +2591,12 @@ class ExperimentService:
# on_commit runs before the view serializes the response — reflect the id on the
# in-memory instance so the end/ship response already carries it.
experiment.flag_cleanup_task_id = created.task_id
+ if picked_repository and set_repository_as_team_default:
+ # The team default steers other experiments, so save it only once a
+ # cleanup has actually opened against the picked repo.
+ config = self._get_team_experiments_config()
+ config.flag_cleanup_repository = picked_repository
+ config.save(update_fields=["flag_cleanup_repository"])
except Exception:
logger.exception("experiment_cleanup_pr_task_failed", experiment_id=experiment_id)
@@ -2601,9 +2617,9 @@ class ExperimentService:
self, experiment: Experiment, requested_repository: str | None = None
) -> CleanupRepositoryTarget:
"""Repository the cleanup PR targets: the repository requested on end/ship, else the
- experiment's saved `repository`, else the team's only cached GitHub repo. Several repos
- (or no GitHub integration) means there is no safe target and the cleanup is skipped —
- a wrong-repo PR is worse than none.
+ experiment's saved `repository`, else the team default, else the team's only cached
+ GitHub repo. Several repos (or no GitHub integration) means there is no safe target
+ and the cleanup is skipped — a wrong-repo PR is worse than none.
Returns how the target was determined (`source`) and the team's connected repositories
(`candidates`) so the end-experiment modal can show the target or offer a picker.
@@ -2641,6 +2657,11 @@ class ExperimentService:
# The stored value is lowercased on write; return GitHub's own casing.
return {"repository": cached[explicit.lower()], "source": "explicit", "candidates": candidates}
return {"repository": None, "source": "ambiguous", "candidates": candidates}
+ team_default = self._get_team_experiments_config().flag_cleanup_repository
+ if team_default and team_default.lower() in cached:
+ # A stale default falls through instead of asking: it is a convenience, not
+ # per-experiment intent, so it must not brick the flow when it stops matching.
+ return {"repository": cached[team_default.lower()], "source": "team_default", "candidates": candidates}
if len(cached) == 1:
return {"repository": candidates[0], "source": "single_repo", "candidates": candidates}
return {"repository": None, "source": "ambiguous", "candidates": candidates}
@@ -2652,10 +2673,11 @@ class ExperimentService:
request: Any | None = None,
open_cleanup_pr: bool = False,
repository: str | None = None,
+ set_repository_as_team_default: bool = False,
) -> None:
# The opt-in cleanup PR doesn't depend on the request — run it before the request-gated
# analytics below so it behaves the same regardless of call context.
- self._maybe_open_cleanup_pr(experiment, open_cleanup_pr, repository)
+ self._maybe_open_cleanup_pr(experiment, open_cleanup_pr, repository, set_repository_as_team_default)
if request is None:
return
@@ -2850,6 +2872,7 @@ class ExperimentService:
conclusion_comment: str | None = None,
open_cleanup_pr: bool = False,
repository: str | None = None,
+ set_repository_as_team_default: bool = False,
request: Any,
) -> Experiment:
"""Ship a variant and (optionally) end the experiment.
@@ -2934,7 +2957,11 @@ class ExperimentService:
)
if was_running:
self._report_experiment_ended(
- experiment, request=request, open_cleanup_pr=open_cleanup_pr, repository=repository
+ experiment,
+ request=request,
+ open_cleanup_pr=open_cleanup_pr,
+ repository=repository,
+ set_repository_as_team_default=set_repository_as_team_default,
)
return experiment
diff --git a/products/experiments/backend/migrations/0032_teamexperimentsconfig_flag_cleanup_repository.py b/products/experiments/backend/migrations/0032_teamexperimentsconfig_flag_cleanup_repository.py
new file mode 100644
index 000000000000..c7c038bc7cb6
--- /dev/null
+++ b/products/experiments/backend/migrations/0032_teamexperimentsconfig_flag_cleanup_repository.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.14 on 2026-08-05 08:27
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("experiments", "0031_add_experiment_version"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="teamexperimentsconfig",
+ name="flag_cleanup_repository",
+ field=models.CharField(
+ blank=True,
+ help_text="Default GitHub repository (organization/repository) for experiment flag-cleanup PRs in this environment. Used when an experiment has no repository of its own. It must belong to the team's GitHub installation at cleanup time or it is ignored.",
+ max_length=255,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txt
index c3bcf5291b00..59eab7f4a56e 100644
--- a/products/experiments/backend/migrations/max_migration.txt
+++ b/products/experiments/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0031_add_experiment_version
+0032_teamexperimentsconfig_flag_cleanup_repository
diff --git a/products/experiments/backend/models/team_experiments_config.py b/products/experiments/backend/models/team_experiments_config.py
index b62fb07ad40e..06de3bb024a4 100644
--- a/products/experiments/backend/models/team_experiments_config.py
+++ b/products/experiments/backend/models/team_experiments_config.py
@@ -96,5 +96,16 @@ class TeamExperimentsConfig(models.Model):
),
)
+ flag_cleanup_repository = models.CharField(
+ max_length=255,
+ null=True,
+ blank=True,
+ help_text=(
+ "Default GitHub repository (organization/repository) for experiment flag-cleanup PRs in "
+ "this environment. Used when an experiment has no repository of its own. It must belong "
+ "to the team's GitHub installation at cleanup time or it is ignored."
+ ),
+ )
+
register_team_extension_signal(TeamExperimentsConfig, logger=logger)
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index b2a645046a5c..2c1f18cbdb12 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -1116,7 +1116,17 @@ class EndExperimentSerializer(serializers.Serializer):
"GitHub repository to open the cleanup pull request in, in `organization/repository` format. "
"Only used when open_cleanup_pr is true. It must be one of the team's connected repositories "
"(see the flag_cleanup_target action); it is then saved as the experiment's repository. When "
- "omitted, the experiment's saved repository or the team's only connected repository is used."
+ "omitted, the experiment's saved repository, the team's default cleanup repository, or the "
+ "team's only connected repository is used."
+ ),
+ )
+ set_repository_as_team_default = serializers.BooleanField(
+ default=False,
+ help_text=(
+ "When true, also save `repository` as this environment's default cleanup repository, used for "
+ "experiments that have no repository of their own. Only acts when open_cleanup_pr is true and "
+ "`repository` is provided and belongs to the team's GitHub installation. Requires project admin "
+ "access (403 otherwise)."
),
)
@@ -1156,11 +1166,12 @@ class ExperimentFlagCleanupTargetSerializer(serializers.Serializer):
help_text="Repository a flag-cleanup pull request would be opened in, or null when none can be determined.",
)
source = serializers.ChoiceField( # type: ignore[assignment] # field named `source` shadows DRF Field.source
- choices=["explicit", "single_repo", "ambiguous", "no_integration"],
+ choices=["explicit", "team_default", "single_repo", "ambiguous", "no_integration"],
help_text=(
- "How the repository was determined: `explicit` (saved on the experiment), `single_repo` (the "
- "team's only connected repository), `ambiguous` (several connected repositories and none saved — "
- "pass one via repository on end/ship_variant), or `no_integration` (no GitHub integration or no "
+ "How the repository was determined: `explicit` (saved on the experiment), `team_default` (the "
+ "environment's default cleanup repository), `single_repo` (the team's only connected repository), "
+ "`ambiguous` (several connected repositories and none saved — pass one via repository on "
+ "end/ship_variant), or `no_integration` (no GitHub integration or no "
"connected repositories, so no cleanup PR can be opened)."
),
)
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index b6f764e6704d..9e29c8a9b564 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -436,6 +436,10 @@ class EnterpriseExperimentsViewSet(
scopes = ["experiment:write"]
if request.data.get("open_cleanup_pr", False) in serializers.BooleanField.TRUE_VALUES:
scopes.append("task:write")
+ # Saving the team default cleanup repository writes environment-wide configuration,
+ # so the token also needs project:write, matching the experiments_config surface.
+ if request.data.get("set_repository_as_team_default", False) in serializers.BooleanField.TRUE_VALUES:
+ scopes.append("project:write")
return scopes
return None
@@ -446,6 +450,15 @@ class EnterpriseExperimentsViewSet(
if not has_tasks_access(cast(User, request.user)):
raise PermissionDenied("Opening a flag cleanup PR requires access to PostHog Desktop.")
+ def _check_team_default_repository_access(self, request: Request) -> None:
+ """The team default cleanup repository is environment-wide configuration; writing it via
+ experiments_config requires project admin (TeamMemberStrictManagementPermission), so the
+ write through end/ship_variant must hold the same bar."""
+ user_permissions = UserPermissions(user=cast(User, request.user))
+ effective_level = user_permissions.team(self.team).effective_membership_level
+ if effective_level is None or effective_level < OrganizationMembership.Level.ADMIN:
+ raise PermissionDenied("Setting the default cleanup repository requires project admin access.")
+
def _token_can_write_feature_flag(self, request: Request) -> bool:
"""Whether the request's token carries feature_flag:write.
@@ -571,6 +584,8 @@ class EnterpriseExperimentsViewSet(
request_serializer.is_valid(raise_exception=True)
if request_serializer.validated_data["open_cleanup_pr"]:
self._check_cleanup_pr_access(request)
+ if request_serializer.validated_data["set_repository_as_team_default"]:
+ self._check_team_default_repository_access(request)
service = ExperimentService(team=self.team, user=request.user)
ended_experiment = service.end_experiment(
experiment,
@@ -578,6 +593,7 @@ class EnterpriseExperimentsViewSet(
conclusion_comment=request_serializer.validated_data.get("conclusion_comment"),
open_cleanup_pr=request_serializer.validated_data["open_cleanup_pr"],
repository=request_serializer.validated_data.get("repository"),
+ set_repository_as_team_default=request_serializer.validated_data["set_repository_as_team_default"],
request=request,
)
return Response(ExperimentSerializer(ended_experiment, context=self.get_serializer_context()).data)
@@ -617,6 +633,8 @@ class EnterpriseExperimentsViewSet(
request_serializer.is_valid(raise_exception=True)
if request_serializer.validated_data["open_cleanup_pr"]:
self._check_cleanup_pr_access(request)
+ if request_serializer.validated_data["set_repository_as_team_default"]:
+ self._check_team_default_repository_access(request)
service = ExperimentService(team=self.team, user=request.user)
shipped_experiment = service.ship_variant(
experiment,
@@ -626,6 +644,7 @@ class EnterpriseExperimentsViewSet(
conclusion_comment=request_serializer.validated_data.get("conclusion_comment"),
open_cleanup_pr=request_serializer.validated_data["open_cleanup_pr"],
repository=request_serializer.validated_data.get("repository"),
+ set_repository_as_team_default=request_serializer.validated_data["set_repository_as_team_default"],
request=request,
)
return Response(ExperimentSerializer(shipped_experiment, context=self.get_serializer_context()).data)
@@ -686,10 +705,11 @@ class EnterpriseExperimentsViewSet(
"""
Repository a flag-cleanup pull request for this experiment would be opened in.
- Resolution order: the experiment's saved repository, else the team's only connected
- GitHub repository. When the team has several repositories and none is saved
- (source=ambiguous), pass one via `repository` on end/ship_variant. Requires access
- to PostHog Desktop, like open_cleanup_pr (403 otherwise).
+ Resolution order: the experiment's saved repository, else the environment's default
+ cleanup repository, else the team's only connected GitHub repository. When the team
+ has several repositories and none is saved (source=ambiguous), pass one via
+ `repository` on end/ship_variant. Requires access to PostHog Desktop, like
+ open_cleanup_pr (403 otherwise).
"""
experiment: Experiment = self.get_object()
# The repository list mirrors what the cleanup checkbox needs, so gate it the same way.
diff --git a/products/experiments/backend/test/test_experiment_cleanup_pr.py b/products/experiments/backend/test/test_experiment_cleanup_pr.py
index 59896d74338e..ae2e3e6cd54e 100644
--- a/products/experiments/backend/test/test_experiment_cleanup_pr.py
+++ b/products/experiments/backend/test/test_experiment_cleanup_pr.py
@@ -10,10 +10,12 @@ from parameterized import parameterized
from rest_framework.test import APIRequestFactory
from posthog.models.organization import OrganizationMembership
+from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.user_integration import UserIntegration
from products.experiments.backend.experiment_service import ExperimentService
from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.tasks.backend.facade import api as tasks_facade
@@ -24,10 +26,10 @@ class TestExperimentCleanupPr(APIBaseTest):
request.user = self.user
return request
- def _running_experiment(self, repository: str | None = None) -> Experiment:
+ def _running_experiment(self, repository: str | None = None, flag_key: str = "cleanup-test-flag") -> Experiment:
flag = FeatureFlag.objects.create(
team=self.team,
- key="cleanup-test-flag",
+ key=flag_key,
created_by=self.user,
filters={
"multivariate": {
@@ -102,19 +104,55 @@ class TestExperimentCleanupPr(APIBaseTest):
@parameterized.expand(
[
- # (name, experiment_repository, cached_repos, expected_repository or None for skip)
+ # (name, experiment_repository, team_default, cached_repos, expected_repository or None for skip)
(
"explicit_field_wins",
"acme/monorepo",
+ None,
[{"full_name": "acme/monorepo"}, {"full_name": "acme/web"}],
"acme/monorepo",
),
- ("explicit_case_insensitive", "acme/monorepo", [{"full_name": "Acme/Monorepo"}], "Acme/Monorepo"),
- ("explicit_not_in_installation_skips", "evil/other", [{"full_name": "acme/web"}], None),
- ("single_cached_repo", None, [{"full_name": "acme/web"}], "acme/web"),
- ("multiple_repos_skips", None, [{"full_name": "acme/web"}, {"full_name": "acme/api"}], None),
- ("no_github_integration", None, None, None),
- ("explicit_but_no_integration_skips", "acme/monorepo", None, None),
+ ("explicit_case_insensitive", "acme/monorepo", None, [{"full_name": "Acme/Monorepo"}], "Acme/Monorepo"),
+ ("explicit_not_in_installation_skips", "evil/other", None, [{"full_name": "acme/web"}], None),
+ ("single_cached_repo", None, None, [{"full_name": "acme/web"}], "acme/web"),
+ ("multiple_repos_skips", None, None, [{"full_name": "acme/web"}, {"full_name": "acme/api"}], None),
+ ("no_github_integration", None, None, None, None),
+ ("explicit_but_no_integration_skips", "acme/monorepo", None, None, None),
+ (
+ "team_default_resolves_multi_repo",
+ None,
+ "acme/api",
+ [{"full_name": "acme/web"}, {"full_name": "acme/api"}],
+ "acme/api",
+ ),
+ (
+ "explicit_beats_team_default",
+ "acme/web",
+ "acme/api",
+ [{"full_name": "acme/web"}, {"full_name": "acme/api"}],
+ "acme/web",
+ ),
+ (
+ "stale_explicit_does_not_fall_to_team_default",
+ "gone/repo",
+ "acme/api",
+ [{"full_name": "acme/web"}, {"full_name": "acme/api"}],
+ None,
+ ),
+ (
+ "stale_team_default_falls_through_to_single_repo",
+ None,
+ "gone/repo",
+ [{"full_name": "acme/web"}],
+ "acme/web",
+ ),
+ (
+ "stale_team_default_multi_repo_skips",
+ None,
+ "gone/repo",
+ [{"full_name": "acme/web"}, {"full_name": "acme/api"}],
+ None,
+ ),
]
)
@patch("products.experiments.backend.experiment_service.report_user_action")
@@ -125,6 +163,7 @@ class TestExperimentCleanupPr(APIBaseTest):
self,
_name,
experiment_repository,
+ team_default,
cached_repos,
expected_repository,
mock_resolve_github,
@@ -139,6 +178,10 @@ class TestExperimentCleanupPr(APIBaseTest):
list_all_cached_repositories=lambda max_repos: cached_repos
)
mock_create_task.return_value = SimpleNamespace(task_id=uuid4())
+ if team_default:
+ config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
+ config.flag_cleanup_repository = team_default
+ config.save()
experiment = self._running_experiment(repository=experiment_repository)
with self.captureOnCommitCallbacks(execute=True):
@@ -218,6 +261,88 @@ class TestExperimentCleanupPr(APIBaseTest):
mock_create_task.assert_not_called()
self.assertIsNone(experiment.repository)
+ @parameterized.expand(
+ [
+ # (name, picked_repository, expect_default_saved)
+ ("valid_pick_becomes_team_default", "acme/api", True),
+ ("invalid_pick_does_not_become_team_default", "evil/other", False),
+ ]
+ )
+ @patch("products.experiments.backend.experiment_service.report_user_action")
+ @patch("products.experiments.backend.experiment_service.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.experiments.backend.experiment_service.tasks_facade.create_and_run_task")
+ @patch("products.tasks.backend.facade.repo_selection.resolve_team_github_integration")
+ def test_set_repository_as_team_default(
+ self,
+ _name,
+ picked_repository,
+ expect_default_saved,
+ mock_resolve_github,
+ mock_create_task,
+ _mock_feature_enabled,
+ _mock_report,
+ ):
+ mock_resolve_github.return_value = SimpleNamespace(
+ list_all_cached_repositories=lambda max_repos: [{"full_name": "acme/web"}, {"full_name": "acme/api"}]
+ )
+ mock_create_task.return_value = SimpleNamespace(task_id=uuid4())
+ experiment = self._running_experiment()
+ service = ExperimentService(team=self.team, user=self.user)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ service.end_experiment(
+ experiment,
+ conclusion="won",
+ open_cleanup_pr=True,
+ repository=picked_repository,
+ set_repository_as_team_default=True,
+ request=self._make_request(),
+ )
+
+ config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
+ if expect_default_saved:
+ self.assertEqual(config.flag_cleanup_repository, picked_repository)
+ # A later experiment with no repository of its own now resolves to the default.
+ other = self._running_experiment(flag_key="cleanup-default-second-flag")
+ target = service.get_cleanup_repository_target(other)
+ self.assertEqual(target["repository"], picked_repository)
+ self.assertEqual(target["source"], "team_default")
+ else:
+ self.assertIsNone(config.flag_cleanup_repository)
+ mock_create_task.assert_not_called()
+
+ @patch("products.experiments.backend.experiment_service.report_user_action")
+ @patch("products.experiments.backend.experiment_service.posthoganalytics.feature_enabled", return_value=True)
+ @patch(
+ "products.experiments.backend.experiment_service.tasks_facade.create_and_run_task",
+ side_effect=Exception("sandbox unavailable"),
+ )
+ @patch("products.tasks.backend.facade.repo_selection.resolve_team_github_integration")
+ def test_team_default_not_saved_when_task_creation_fails(
+ self,
+ mock_resolve_github,
+ _mock_create_task,
+ _mock_feature_enabled,
+ _mock_report,
+ ):
+ mock_resolve_github.return_value = SimpleNamespace(
+ list_all_cached_repositories=lambda max_repos: [{"full_name": "acme/web"}, {"full_name": "acme/api"}]
+ )
+ experiment = self._running_experiment()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ ExperimentService(team=self.team, user=self.user).end_experiment(
+ experiment,
+ conclusion="won",
+ open_cleanup_pr=True,
+ repository="acme/api",
+ set_repository_as_team_default=True,
+ request=self._make_request(),
+ )
+
+ config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
+ self.assertIsNone(config.flag_cleanup_repository)
+
def test_cleanup_target_never_uses_personal_github_connections(self):
# The team has no GitHub integration, but an org owner has a personal connection with
# cached repos. The resolver's owner fallback must not surface those repo names to
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 0604cb30a6d4..4497b2bf23d7 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -17,7 +17,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
-from posthog.models import Organization, Team
+from posthog.models import Organization, OrganizationMembership, Team
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.extensions import get_or_create_team_extension
@@ -49,6 +49,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag, get_
from ee.api.test.base import APILicensedTest
from ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializer
+from ee.models.rbac.access_control import AccessControl
def _make(cls, **attrs):
@@ -5958,53 +5959,77 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
@parameterized.expand(
[
- # (name, stored_repository, cached_repos, expected_body)
+ # (name, stored_repository, team_default, cached_repos, expected_body)
(
"no_integration",
None,
None,
+ None,
{"repository": None, "source": "no_integration", "candidates": []},
),
(
"single_repo",
None,
+ None,
[{"full_name": "acme/web"}],
{"repository": "acme/web", "source": "single_repo", "candidates": ["acme/web"]},
),
(
"ambiguous",
None,
+ None,
[{"full_name": "acme/web"}, {"full_name": "acme/api"}],
{"repository": None, "source": "ambiguous", "candidates": ["acme/api", "acme/web"]},
),
(
"explicit",
"acme/api",
+ None,
[{"full_name": "acme/web"}, {"full_name": "acme/api"}],
{"repository": "acme/api", "source": "explicit", "candidates": ["acme/api", "acme/web"]},
),
(
"stale_explicit_needs_a_new_choice",
"gone/repo",
+ None,
[{"full_name": "acme/web"}],
{"repository": None, "source": "ambiguous", "candidates": ["acme/web"]},
),
(
"stale_explicit_with_empty_cache",
"gone/repo",
+ None,
[],
{"repository": None, "source": "no_integration", "candidates": []},
),
+ (
+ "team_default",
+ None,
+ "acme/api",
+ [{"full_name": "acme/web"}, {"full_name": "Acme/API"}],
+ {"repository": "Acme/API", "source": "team_default", "candidates": ["Acme/API", "acme/web"]},
+ ),
+ (
+ "stale_team_default_falls_through",
+ None,
+ "gone/repo",
+ [{"full_name": "acme/web"}, {"full_name": "acme/api"}],
+ {"repository": None, "source": "ambiguous", "candidates": ["acme/api", "acme/web"]},
+ ),
]
)
@patch("products.experiments.backend.presentation.views.has_tasks_access", return_value=True)
@patch("products.tasks.backend.facade.repo_selection.resolve_team_github_integration")
def test_flag_cleanup_target_endpoint(
- self, _name, stored_repository, cached_repos, expected_body, mock_resolve_github, _mock_access
+ self, _name, stored_repository, team_default, cached_repos, expected_body, mock_resolve_github, _mock_access
):
exp_id = self._create_running_experiment(name="Cleanup Target", flag_key="cleanup-target-flag")["id"]
if stored_repository:
Experiment.objects.filter(id=exp_id).update(repository=stored_repository)
+ if team_default:
+ config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
+ config.flag_cleanup_repository = team_default
+ config.save()
if cached_repos is None:
mock_resolve_github.return_value = None
else:
@@ -6076,6 +6101,48 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(mock_create_task.call_args.kwargs["repository"], "Acme/Web")
self.assertEqual(Experiment.objects.get(id=exp_id).repository, "acme/web")
+ @patch("products.experiments.backend.presentation.views.has_tasks_access", return_value=True)
+ @patch("products.experiments.backend.experiment_service.report_user_action")
+ @patch("products.experiments.backend.experiment_service.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.experiments.backend.experiment_service.tasks_facade.create_and_run_task")
+ @patch("products.tasks.backend.facade.repo_selection.resolve_team_github_integration")
+ def test_set_repository_as_team_default_requires_project_admin(
+ self, mock_resolve_github, mock_create_task, _mock_flag, _mock_report, _mock_access
+ ):
+ mock_resolve_github.return_value = SimpleNamespace(
+ list_all_cached_repositories=lambda max_repos: [{"full_name": "acme/web"}, {"full_name": "acme/api"}]
+ )
+ mock_create_task.return_value = SimpleNamespace(task_id=uuid4())
+ exp_member = self._create_running_experiment(name="Default Deny", flag_key="team-default-deny-flag")["id"]
+ exp_admin = self._create_running_experiment(name="Default Allow", flag_key="team-default-allow-flag")["id"]
+ body = {
+ "conclusion": "won",
+ "open_cleanup_pr": True,
+ "repository": "acme/web",
+ "set_repository_as_team_default": True,
+ }
+
+ # A team-wide default is environment configuration, admin-gated like experiments_config.
+ # Without an access-control row every member is effectively admin, so pin the project's
+ # default access to member to exercise the deny path.
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=self.team.id, access_level="member"
+ )
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ resp = self.client.post(f"/api/projects/{self.team.id}/experiments/{exp_member}/end/", body, format="json")
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN, resp.content)
+ self.assertIsNone(get_or_create_team_extension(self.team, TeamExperimentsConfig).flag_cleanup_repository)
+
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ with self.captureOnCommitCallbacks(execute=True):
+ resp = self.client.post(f"/api/projects/{self.team.id}/experiments/{exp_admin}/end/", body, format="json")
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ self.assertEqual(
+ get_or_create_team_extension(self.team, TeamExperimentsConfig).flag_cleanup_repository, "acme/web"
+ )
+
def test_ship_variant_endpoint_default_preserves_groups(self):
data = self._create_running_experiment(name="Ship Endpoint", flag_key="ship-endpoint-flag")
experiment_id = data["id"]
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 152cb0784f70..6110a4010b6d 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -1884,15 +1884,18 @@ export interface EndExperimentApi {
/** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Desktop (403 otherwise). Only acts for allowlisted teams; ignored otherwise. */
open_cleanup_pr?: boolean
/**
- * GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used.
+ * GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used.
* @maxLength 255
* @nullable
*/
repository?: string | null
+ /** When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise). */
+ set_repository_as_team_default?: boolean
}
/**
* * `explicit` - explicit
+ * * `team_default` - team_default
* * `single_repo` - single_repo
* * `ambiguous` - ambiguous
* * `no_integration` - no_integration
@@ -1902,6 +1905,7 @@ export type ExperimentFlagCleanupTargetSourceEnumApi =
export const ExperimentFlagCleanupTargetSourceEnumApi = {
Explicit: 'explicit',
+ TeamDefault: 'team_default',
SingleRepo: 'single_repo',
Ambiguous: 'ambiguous',
NoIntegration: 'no_integration',
@@ -1913,9 +1917,10 @@ export interface ExperimentFlagCleanupTargetApi {
* @nullable
*/
repository: string | null
- /** How the repository was determined: `explicit` (saved on the experiment), `single_repo` (the team's only connected repository), `ambiguous` (several connected repositories and none saved — pass one via repository on end/ship_variant), or `no_integration` (no GitHub integration or no connected repositories, so no cleanup PR can be opened).
+ /** How the repository was determined: `explicit` (saved on the experiment), `team_default` (the environment's default cleanup repository), `single_repo` (the team's only connected repository), `ambiguous` (several connected repositories and none saved — pass one via repository on end/ship_variant), or `no_integration` (no GitHub integration or no connected repositories, so no cleanup PR can be opened).
*
* * `explicit` - explicit
+ * * `team_default` - team_default
* * `single_repo` - single_repo
* * `ambiguous` - ambiguous
* * `no_integration` - no_integration */
@@ -2264,11 +2269,13 @@ export interface ShipVariantApi {
/** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Desktop (403 otherwise). Only acts for allowlisted teams; ignored otherwise. */
open_cleanup_pr?: boolean
/**
- * GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used.
+ * GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used.
* @maxLength 255
* @nullable
*/
repository?: string | null
+ /** When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise). */
+ set_repository_as_team_default?: boolean
/** The key of the variant to ship. */
variant_key: string
/** If true, prepend a release condition to the feature flag that rolls the variant out to 100% of users, overriding any existing release conditions on the flag. If false (default), only update the variant distribution — existing release conditions are preserved and the variant is served only to users who already match them. */
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 3fb711b22635..68af66e743f1 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -596,10 +596,11 @@ export const getExperimentsFlagCleanupTargetRetrieveUrl = (projectId: string, id
/**
* Repository a flag-cleanup pull request for this experiment would be opened in.
*
- * Resolution order: the experiment's saved repository, else the team's only connected
- * GitHub repository. When the team has several repositories and none is saved
- * (source=ambiguous), pass one via `repository` on end/ship_variant. Requires access
- * to PostHog Desktop, like open_cleanup_pr (403 otherwise).
+ * Resolution order: the experiment's saved repository, else the environment's default
+ * cleanup repository, else the team's only connected GitHub repository. When the team
+ * has several repositories and none is saved (source=ambiguous), pass one via
+ * `repository` on end/ship_variant. Requires access to PostHog Desktop, like
+ * open_cleanup_pr (403 otherwise).
*/
export const experimentsFlagCleanupTargetRetrieve = async (
projectId: string,
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index bf5826055720..b9a07d12c2c1 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -975,6 +975,8 @@ export const experimentsEndCreateBodyConclusionCommentMax = 4000
export const experimentsEndCreateBodyOpenCleanupPrDefault = false
export const experimentsEndCreateBodyRepositoryMax = 255
+export const experimentsEndCreateBodySetRepositoryAsTeamDefaultDefault = false
+
export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
conclusion: zod
.union([
@@ -1005,7 +1007,13 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
.max(experimentsEndCreateBodyRepositoryMax)
.nullish()
.describe(
- "GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used."
+ "GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
+ ),
+ set_repository_as_team_default: zod
+ .boolean()
+ .default(experimentsEndCreateBodySetRepositoryAsTeamDefaultDefault)
+ .describe(
+ "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise)."
),
})
@@ -1129,6 +1137,7 @@ export const experimentsShipVariantCreateBodyConclusionCommentMax = 4000
export const experimentsShipVariantCreateBodyOpenCleanupPrDefault = false
export const experimentsShipVariantCreateBodyRepositoryMax = 255
+export const experimentsShipVariantCreateBodySetRepositoryAsTeamDefaultDefault = false
export const experimentsShipVariantCreateBodyReleaseToEveryoneDefault = false
export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
@@ -1161,7 +1170,13 @@ export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
.max(experimentsShipVariantCreateBodyRepositoryMax)
.nullish()
.describe(
- "GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used."
+ "GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
+ ),
+ set_repository_as_team_default: zod
+ .boolean()
+ .default(experimentsShipVariantCreateBodySetRepositoryAsTeamDefaultDefault)
+ .describe(
+ "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise)."
),
variant_key: zod.string().describe('The key of the variant to ship.'),
release_to_everyone: zod
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 90cd83809c4a..7c36214be1e7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25020,11 +25020,13 @@ export namespace Schemas {
/** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Desktop (403 otherwise). Only acts for allowlisted teams; ignored otherwise. */
open_cleanup_pr?: boolean;
/**
- * GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used.
+ * GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used.
* @maxLength 255
* @nullable
*/
repository?: string | null;
+ /** When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise). */
+ set_repository_as_team_default?: boolean;
}
export interface EndpointBreakdownLimitExceededSignalExtra {
@@ -29045,6 +29047,7 @@ export namespace Schemas {
/**
* * `explicit` - explicit
+ * * `team_default` - team_default
* * `single_repo` - single_repo
* * `ambiguous` - ambiguous
* * `no_integration` - no_integration
@@ -29054,6 +29057,7 @@ export namespace Schemas {
export const ExperimentFlagCleanupTargetSourceEnum = {
Explicit: 'explicit',
+ TeamDefault: 'team_default',
SingleRepo: 'single_repo',
Ambiguous: 'ambiguous',
NoIntegration: 'no_integration',
@@ -29065,9 +29069,10 @@ export namespace Schemas {
* @nullable
*/
repository: string | null;
- /** How the repository was determined: `explicit` (saved on the experiment), `single_repo` (the team's only connected repository), `ambiguous` (several connected repositories and none saved — pass one via repository on end/ship_variant), or `no_integration` (no GitHub integration or no connected repositories, so no cleanup PR can be opened).
+ /** How the repository was determined: `explicit` (saved on the experiment), `team_default` (the environment's default cleanup repository), `single_repo` (the team's only connected repository), `ambiguous` (several connected repositories and none saved — pass one via repository on end/ship_variant), or `no_integration` (no GitHub integration or no connected repositories, so no cleanup PR can be opened).
*
* * `explicit` - explicit
+ * * `team_default` - team_default
* * `single_repo` - single_repo
* * `ambiguous` - ambiguous
* * `no_integration` - no_integration */
@@ -65998,11 +66003,13 @@ export namespace Schemas {
/** When true, open a draft pull request that removes the experiment's feature-flag code from the linked repository. Requires the requesting user to have access to PostHog Desktop (403 otherwise). Only acts for allowlisted teams; ignored otherwise. */
open_cleanup_pr?: boolean;
/**
- * GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used.
+ * GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used.
* @maxLength 255
* @nullable
*/
repository?: string | null;
+ /** When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise). */
+ set_repository_as_team_default?: boolean;
/** The key of the variant to ship. */
variant_key: string;
/** If true, prepend a release condition to the feature flag that rolls the variant out to 100% of users, overriding any existing release conditions on the flag. If false (default), only update the variant distribution — existing release conditions are preserved and the variant is served only to users who already match them. */
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index db8c633f290f..f5ed7bcb8912 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -12040,6 +12040,8 @@ export const experimentsEndCreateBodyConclusionCommentMax = 4000
export const experimentsEndCreateBodyOpenCleanupPrDefault = false
export const experimentsEndCreateBodyRepositoryMax = 255
+export const experimentsEndCreateBodySetRepositoryAsTeamDefaultDefault = false
+
export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
conclusion: zod
.union([
@@ -12070,7 +12072,13 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
.max(experimentsEndCreateBodyRepositoryMax)
.nullish()
.describe(
- "GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used."
+ "GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
+ ),
+ set_repository_as_team_default: zod
+ .boolean()
+ .default(experimentsEndCreateBodySetRepositoryAsTeamDefaultDefault)
+ .describe(
+ "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise)."
),
})
@@ -12267,6 +12275,7 @@ export const experimentsShipVariantCreateBodyConclusionCommentMax = 4000
export const experimentsShipVariantCreateBodyOpenCleanupPrDefault = false
export const experimentsShipVariantCreateBodyRepositoryMax = 255
+export const experimentsShipVariantCreateBodySetRepositoryAsTeamDefaultDefault = false
export const experimentsShipVariantCreateBodyReleaseToEveryoneDefault = false
export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
@@ -12299,7 +12308,13 @@ export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
.max(experimentsShipVariantCreateBodyRepositoryMax)
.nullish()
.describe(
- "GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used."
+ "GitHub repository to open the cleanup pull request in, in `organization\/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
+ ),
+ set_repository_as_team_default: zod
+ .boolean()
+ .default(experimentsShipVariantCreateBodySetRepositoryAsTeamDefaultDefault)
+ .describe(
+ "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise)."
),
variant_key: zod.string().describe('The key of the variant to ship.'),
release_to_everyone: zod
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 1032debaecec..04d9a3b3a766 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -433,6 +433,9 @@ const experimentEnd = (): ToolBase<typeof ExperimentEndSchema, WithPostHogUrl<Sc
if (params.repository !== undefined) {
body['repository'] = params.repository
}
+ if (params.set_repository_as_team_default !== undefined) {
+ body['set_repository_as_team_default'] = params.set_repository_as_team_default
+ }
const result = await context.api.request<Schemas.Experiment>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/end/`,
@@ -1007,6 +1010,9 @@ const experimentShipVariant = (): ToolBase<typeof ExperimentShipVariantSchema, W
if (params.repository !== undefined) {
body['repository'] = params.repository
}
+ if (params.set_repository_as_team_default !== undefined) {
+ body['set_repository_as_team_default'] = params.set_repository_as_team_default
+ }
if (params.variant_key !== undefined) {
body['variant_key'] = params.variant_key
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
index c1821978ebc6..b61187163726 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
@@ -45,7 +45,12 @@
"type": "null"
}
],
- "description": "GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used."
+ "description": "GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
+ },
+ "set_repository_as_team_default": {
+ "default": false,
+ "description": "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise).",
+ "type": "boolean"
}
},
"required": ["id"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
index 4ac3774bb135..18d3a73cb0a8 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-ship-variant.json
@@ -50,7 +50,12 @@
"type": "null"
}
],
- "description": "GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository or the team's only connected repository is used."
+ "description": "GitHub repository to open the cleanup pull request in, in `organization/repository` format. Only used when open_cleanup_pr is true. It must be one of the team's connected repositories (see the flag_cleanup_target action); it is then saved as the experiment's repository. When omitted, the experiment's saved repository, the team's default cleanup repository, or the team's only connected repository is used."
+ },
+ "set_repository_as_team_default": {
+ "default": false,
+ "description": "When true, also save `repository` as this environment's default cleanup repository, used for experiments that have no repository of their own. Only acts when open_cleanup_pr is true and `repository` is provided and belongs to the team's GitHub installation. Requires project admin access (403 otherwise).",
+ "type": "boolean"
},
"variant_key": {
"description": "The key of the variant to ship.",