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): pick the repository for the flag cleanup PR (#75867)

Juraj Majerik8d9f8e3e4f91
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
index 1029eb09b336..72e174379b45 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentModals.tsx
@@ -1,12 +1,13 @@
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { IconCheckCircle, IconGlobe, IconList } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
LemonCheckbox,
+ LemonInputSelect,
LemonLabel,
LemonModal,
LemonSelect,
@@ -26,6 +27,7 @@ import { hasFrozenExposureStamps } from '../experimentActions'
import { experimentLogic } from '../experimentLogic'
import { modalsLogic } from '../modalsLogic'
import { getExperimentVariants } from '../utils'
+import { flagCleanupTargetLogic } from './flagCleanupTargetLogic'
import { VariantTag } from './VariantTag'
function ConclusionForm(): JSX.Element {
@@ -219,10 +221,25 @@ export function FinishExperimentModal(): JSX.Element {
const [selectedVariantKey, setSelectedVariantKey] = useState<string | null>()
const [releaseToEveryone, setReleaseToEveryone] = useState<boolean>(false)
const [openCleanupPr, setOpenCleanupPr] = useState<boolean>(false)
+ const [cleanupRepository, setCleanupRepository] = useState<string | null>(null)
+
+ // 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.
+ useEffect(() => {
+ if (isFinishExperimentModalOpen) {
+ setOpenCleanupPr(false)
+ setCleanupRepository(null)
+ }
+ }, [isFinishExperimentModalOpen])
+
+ const { cleanupTarget } = useValues(flagCleanupTargetLogic({ experimentId: experiment.id as number }))
// The cleanup PR runs as a PostHog Desktop task, so the user needs Code access on top of the rollout flag.
const cleanupPrAvailable =
!!featureFlags[FEATURE_FLAGS.EXPERIMENT_FLAG_CLEANUP_PR] && !!featureFlags[FEATURE_FLAGS.TASKS]
+ // 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'
const aggregationTargetName =
experiment.filters.aggregation_group_type_index != null
@@ -231,19 +248,22 @@ export function FinishExperimentModal(): JSX.Element {
const handleClose = (): void => {
setOpenCleanupPr(false)
+ setCleanupRepository(null)
restoreUnmodifiedExperiment()
closeFinishExperimentModal()
}
const handleEndExperiment = (): void => {
const withCleanupPr = cleanupPrAvailable && openCleanupPr
+ const repository = withCleanupPr && cleanupNeedsRepositoryPick ? cleanupRepository : null
if (isSingleVariantShipped || !selectedVariantKey) {
- endExperimentWithoutShipping(withCleanupPr)
+ endExperimentWithoutShipping(withCleanupPr, repository)
} else {
finishExperiment({
selectedVariantKey,
releaseToEveryone,
openCleanupPr: withCleanupPr,
+ repository,
})
}
}
@@ -281,7 +301,20 @@ export function FinishExperimentModal(): JSX.Element {
onClick={handleEndExperiment}
type="primary"
loading={endExperimentLoading}
- disabledReason={!experiment.conclusion && 'Select a conclusion'}
+ disabledReason={
+ (!experiment.conclusion && 'Select a conclusion') ||
+ // Until the target loads we don't know whether a pick is needed, and
+ // ending now would silently skip the requested cleanup PR.
+ (cleanupPrAvailable &&
+ openCleanupPr &&
+ !cleanupTarget &&
+ 'Checking which repository the cleanup PR would target') ||
+ (cleanupPrAvailable &&
+ openCleanupPr &&
+ cleanupNeedsRepositoryPick &&
+ !cleanupRepository &&
+ 'Select a repository for the cleanup PR')
+ }
>
End experiment
</LemonButton>
@@ -394,16 +427,41 @@ export function FinishExperimentModal(): JSX.Element {
)}
<ConclusionForm />
{cleanupPrAvailable && (
- <LemonCheckbox
- checked={openCleanupPr}
- onChange={setOpenCleanupPr}
- data-attr="experiment-open-cleanup-pr"
- label={
- <span>
- Open a draft PR removing <code>{experiment.feature_flag?.key}</code> from your code
- </span>
- }
- />
+ <div className="space-y-2">
+ <LemonCheckbox
+ checked={openCleanupPr}
+ onChange={setOpenCleanupPr}
+ data-attr="experiment-open-cleanup-pr"
+ disabledReason={
+ cleanupTarget?.source === 'no_integration' &&
+ 'Connect GitHub in your project settings to open cleanup PRs'
+ }
+ label={
+ <span>
+ Open a draft PR removing <code>{experiment.feature_flag?.key}</code> from your
+ code
+ </span>
+ }
+ />
+ {openCleanupPr && cleanupTarget?.repository && (
+ <div className="text-xs text-muted">
+ The PR will be opened in <code>{cleanupTarget.repository}</code>.
+ </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"
+ />
+ )}
+ </div>
)}
{!isSingleVariantShipped && (
<LemonBanner type="info" className="mb-4">
diff --git a/frontend/src/scenes/experiments/ExperimentView/flagCleanupTargetLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTargetLogic.test.ts
new file mode 100644
index 000000000000..27a09e620089
--- /dev/null
+++ b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTargetLogic.test.ts
@@ -0,0 +1,45 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { experimentsFlagCleanupTargetRetrieve } from 'products/experiments/frontend/generated/api'
+
+import { modalsLogic } from '../modalsLogic'
+import { flagCleanupTargetLogic } from './flagCleanupTargetLogic'
+
+jest.mock('products/experiments/frontend/generated/api', () => ({
+ experimentsFlagCleanupTargetRetrieve: jest.fn(),
+}))
+
+const mockRetrieve = experimentsFlagCleanupTargetRetrieve as jest.Mock
+
+describe('flagCleanupTargetLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ mockRetrieve.mockReset()
+ })
+
+ it('loads the target when the finish modal opens, only for users with the cleanup feature', async () => {
+ mockRetrieve.mockResolvedValue({ repository: null, source: 'ambiguous', candidates: ['acme/web', 'acme/api'] })
+ featureFlagLogic.mount()
+ const logic = flagCleanupTargetLogic({ experimentId: 1 })
+ logic.mount()
+
+ // Cleanup flags off: opening the modal must not hit the endpoint (it would 403).
+ modalsLogic.mount()
+ modalsLogic.actions.openFinishExperimentModal()
+ await Promise.resolve()
+ expect(mockRetrieve).not.toHaveBeenCalled()
+
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.EXPERIMENT_FLAG_CLEANUP_PR]: true,
+ [FEATURE_FLAGS.TASKS]: true,
+ })
+ modalsLogic.actions.openFinishExperimentModal()
+ await Promise.resolve()
+ expect(mockRetrieve).toHaveBeenCalledTimes(1)
+ await Promise.resolve()
+ expect(logic.values.cleanupTarget?.candidates).toEqual(['acme/web', 'acme/api'])
+ })
+})
diff --git a/frontend/src/scenes/experiments/ExperimentView/flagCleanupTargetLogic.ts b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTargetLogic.ts
new file mode 100644
index 000000000000..252e75b9d615
--- /dev/null
+++ b/frontend/src/scenes/experiments/ExperimentView/flagCleanupTargetLogic.ts
@@ -0,0 +1,89 @@
+import { MakeLogicType, connect, kea, key, listeners, path, props } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { experimentsFlagCleanupTargetRetrieve } from 'products/experiments/frontend/generated/api'
+import type { ExperimentFlagCleanupTargetApi } from 'products/experiments/frontend/generated/api.schemas'
+
+import { modalsLogic } from '../modalsLogic'
+
+export interface FlagCleanupTargetLogicProps {
+ experimentId: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagCleanupTargetLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentProjectId: number | null // projectLogic
+ cleanupTarget: ExperimentFlagCleanupTargetApi | null
+ cleanupTargetLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagCleanupTargetLogicActions {
+ openFinishExperimentModal: () => {
+ value: true
+ } // modalsLogic
+ loadCleanupTarget: () => any
+ loadCleanupTargetFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadCleanupTargetSuccess: (
+ cleanupTarget: ExperimentFlagCleanupTargetApi,
+ payload?: any
+ ) => {
+ cleanupTarget: ExperimentFlagCleanupTargetApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagCleanupTargetLogicMeta {
+ key: number
+}
+
+export type flagCleanupTargetLogicType = MakeLogicType<
+ flagCleanupTargetLogicValues,
+ flagCleanupTargetLogicActions,
+ FlagCleanupTargetLogicProps,
+ flagCleanupTargetLogicMeta
+>
+
+export const flagCleanupTargetLogic = kea<flagCleanupTargetLogicType>([
+ props({} as FlagCleanupTargetLogicProps),
+ key((props) => props.experimentId),
+ path((key) => ['scenes', 'experiments', 'flagCleanupTargetLogic', key]),
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],
+ actions: [modalsLogic, ['openFinishExperimentModal']],
+ })),
+ loaders(({ props, values }) => ({
+ cleanupTarget: [
+ null as ExperimentFlagCleanupTargetApi | null,
+ {
+ loadCleanupTarget: async () =>
+ await experimentsFlagCleanupTargetRetrieve(String(values.currentProjectId), props.experimentId),
+ },
+ ],
+ })),
+ listeners(({ actions, values }) => ({
+ // Loaded on modal open, not on mount: the modal component mounts with the scene,
+ // and most experiment page visits never open it.
+ openFinishExperimentModal: () => {
+ if (
+ values.featureFlags[FEATURE_FLAGS.EXPERIMENT_FLAG_CLEANUP_PR] &&
+ values.featureFlags[FEATURE_FLAGS.TASKS]
+ ) {
+ actions.loadCleanupTarget()
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index fc3b19b2b7d7..cfd8d6b9ed4a 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -865,23 +865,34 @@ export interface experimentLogicActions {
newUuid: string
sharedMetricId: number
}
- endExperiment: (openCleanupPr?: boolean) => {
+ endExperiment: (
+ openCleanupPr?: boolean,
+ repository?: string | null
+ ) => {
openCleanupPr: boolean
+ repository: string | null
}
- endExperimentWithoutShipping: (openCleanupPr?: boolean) => {
+ endExperimentWithoutShipping: (
+ openCleanupPr?: boolean,
+ repository?: string | null
+ ) => {
openCleanupPr: boolean
+ repository: string | null
}
finishExperiment: ({
selectedVariantKey,
releaseToEveryone,
openCleanupPr,
+ repository,
}: {
openCleanupPr?: boolean
releaseToEveryone: boolean
+ repository?: string | null
selectedVariantKey: string
}) => {
openCleanupPr: boolean
releaseToEveryone: boolean
+ repository: string | null
selectedVariantKey: string
}
freezeExposure: () => {
@@ -1514,17 +1525,30 @@ export const experimentLogic = kea<experimentLogicType>([
changeExperimentStartDate: (startDate: string) => ({ startDate }),
changeExperimentEndDate: (endDate: string) => ({ endDate }),
launchExperiment: true,
- endExperiment: (openCleanupPr: boolean = false) => ({ openCleanupPr }),
- endExperimentWithoutShipping: (openCleanupPr: boolean = false) => ({ openCleanupPr }),
+ endExperiment: (openCleanupPr: boolean = false, repository: string | null = null) => ({
+ openCleanupPr,
+ repository,
+ }),
+ endExperimentWithoutShipping: (openCleanupPr: boolean = false, repository: string | null = null) => ({
+ openCleanupPr,
+ repository,
+ }),
finishExperiment: ({
selectedVariantKey,
releaseToEveryone,
openCleanupPr,
+ repository,
}: {
selectedVariantKey: string
releaseToEveryone: boolean
openCleanupPr?: boolean
- }) => ({ selectedVariantKey, releaseToEveryone, openCleanupPr: openCleanupPr ?? false }),
+ repository?: string | null
+ }) => ({
+ selectedVariantKey,
+ releaseToEveryone,
+ openCleanupPr: openCleanupPr ?? false,
+ repository: repository ?? null,
+ }),
pauseExperiment: true,
resumeExperiment: true,
freezeExposure: true,
@@ -2397,7 +2421,7 @@ export const experimentLogic = kea<experimentLogicType>([
values.experiment && eventUsageLogic.actions.reportExperimentEndDateChange(values.experiment, endDate)
actions.refreshExperimentResults(true, 'config_change')
},
- endExperiment: async ({ openCleanupPr }) => {
+ endExperiment: async ({ openCleanupPr, repository }) => {
actions.setEndExperimentLoading(true)
try {
const response: Experiment = await api.create(
@@ -2406,6 +2430,7 @@ export const experimentLogic = kea<experimentLogicType>([
conclusion: values.experiment.conclusion,
conclusion_comment: values.experiment.conclusion_comment,
open_cleanup_pr: openCleanupPr,
+ ...(repository ? { repository } : {}),
}
)
actions.setExperiment(response)
@@ -2416,8 +2441,8 @@ export const experimentLogic = kea<experimentLogicType>([
actions.setEndExperimentLoading(false)
}
},
- endExperimentWithoutShipping: async ({ openCleanupPr }) => {
- actions.endExperiment(openCleanupPr)
+ endExperimentWithoutShipping: async ({ openCleanupPr, repository }) => {
+ actions.endExperiment(openCleanupPr, repository)
actions.closeFinishExperimentModal()
lemonToast.success('Experiment ended successfully')
@@ -2732,7 +2757,7 @@ export const experimentLogic = kea<experimentLogicType>([
})
}
},
- finishExperiment: async ({ selectedVariantKey, releaseToEveryone, openCleanupPr }) => {
+ finishExperiment: async ({ selectedVariantKey, releaseToEveryone, openCleanupPr, repository }) => {
actions.setEndExperimentLoading(true)
try {
const response: Experiment = await api.create(
@@ -2743,6 +2768,7 @@ export const experimentLogic = kea<experimentLogicType>([
conclusion: values.experiment.conclusion,
conclusion_comment: values.experiment.conclusion_comment,
open_cleanup_pr: openCleanupPr,
+ ...(repository ? { repository } : {}),
}
)
actions.setExperiment(response)
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 4c967b50c39a..d5482bdab06e 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -6,7 +6,7 @@ from collections.abc import Iterable, Mapping
from copy import deepcopy
from datetime import date, datetime, timedelta
from enum import Enum
-from typing import Any, Literal, get_args
+from typing import Any, Literal, TypedDict, get_args
from uuid import uuid4
from zoneinfo import ZoneInfo
@@ -115,6 +115,15 @@ 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"]
+
+
+class CleanupRepositoryTarget(TypedDict):
+ repository: str | None
+ source: CleanupRepositorySource
+ candidates: list[str]
+
+
DEFAULT_ROLLOUT_PERCENTAGE = 100
ExperimentCreationMode = Literal["new", "duplicate", "copy_to_project"]
@@ -2305,6 +2314,7 @@ class ExperimentService:
conclusion: str | None = None,
conclusion_comment: str | None = None,
open_cleanup_pr: bool = False,
+ repository: str | None = None,
request: Any | None = None,
) -> Experiment:
"""End a running experiment: set end_date and mark as stopped.
@@ -2323,7 +2333,9 @@ class ExperimentService:
experiment.conclusion_comment = conclusion_comment
experiment.save()
- self._report_experiment_ended(experiment, request=request, open_cleanup_pr=open_cleanup_pr)
+ self._report_experiment_ended(
+ experiment, request=request, open_cleanup_pr=open_cleanup_pr, repository=repository
+ )
return experiment
@@ -2342,7 +2354,9 @@ class ExperimentService:
)
)
- def _maybe_open_cleanup_pr(self, experiment: Experiment, open_cleanup_pr: bool) -> None:
+ def _maybe_open_cleanup_pr(
+ self, experiment: Experiment, open_cleanup_pr: bool, requested_repository: str | None = None
+ ) -> 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.
@@ -2355,7 +2369,8 @@ class ExperimentService:
return
flag_key = experiment.get_feature_flag_key()
- repository = self._resolve_cleanup_repository(experiment)
+ target = self.get_cleanup_repository_target(experiment, requested_repository=requested_repository)
+ repository = target["repository"]
if repository is None:
# No safe target — skipping beats opening a PR against the wrong repo.
logger.info(
@@ -2363,9 +2378,16 @@ class ExperimentService:
experiment_id=experiment.id,
team_id=experiment.team_id,
flag_key=flag_key,
+ requested_repository=requested_repository,
)
return
+ if requested_repository and target["source"] == "explicit":
+ # 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.save(update_fields=["repository"])
+
plan = cleanup_plan(conclusion, experiment.feature_flag.variants or [])
title, description = build_cleanup_prompt(experiment, flag_key, plan)
team = experiment.team
@@ -2409,31 +2431,53 @@ class ExperimentService:
except Exception:
logger.exception("experiment_cleanup_pr_failed", experiment_id=experiment.id)
- def _resolve_cleanup_repository(self, experiment: Experiment) -> str | None:
- """Repository the cleanup PR targets: the experiment's explicit `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.
+ def get_cleanup_repository_target(
+ 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.
+
+ 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.
"""
# Keeps the sandbox/LLM runtime the repo-selection module pulls in off the
# request import path.
from products.tasks.backend.facade import repo_selection as tasks_repo_selection # noqa: PLC0415
- github = tasks_repo_selection.resolve_team_github_integration(experiment.team_id, team=experiment.team)
+ # team_only: the candidates are shown to any experiment viewer with Code access, and the
+ # cleanup PR is opened by the team installation's bot identity — a personal-connection
+ # fallback would both leak someone's private repo names and target a repo the bot can't use.
+ github = tasks_repo_selection.resolve_team_github_integration(
+ experiment.team_id, team=experiment.team, team_only=True
+ )
if github is None:
- return None
+ return {"repository": None, "source": "no_integration", "candidates": []}
cached = {
- full_name.lower()
+ full_name.lower(): full_name
for repo in github.list_all_cached_repositories(max_repos=1000)
if (full_name := repo.get("full_name"))
}
- if experiment.repository:
+ candidates = sorted(cached.values(), key=str.lower)
+ if not cached:
+ # An integration with nothing to target is as good as none — without this, a
+ # stale saved repo would report "ambiguous" and the modal would show an empty picker.
+ return {"repository": None, "source": "no_integration", "candidates": []}
+ explicit = requested_repository or experiment.repository
+ if explicit:
# An explicit repo must still belong to this team's installation — GitHub
# installations can be shared, so an unchecked name could reach another
- # project's private repository through the shared credential.
- return experiment.repository if experiment.repository.lower() in cached else None
+ # project's private repository through the shared credential. A stale explicit
+ # value does not fall back to the single cached repo: the user pointed at a
+ # specific repo, so ask again rather than silently retarget.
+ if explicit.lower() in cached:
+ # 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}
if len(cached) == 1:
- return cached.pop()
- return None
+ return {"repository": candidates[0], "source": "single_repo", "candidates": candidates}
+ return {"repository": None, "source": "ambiguous", "candidates": candidates}
def _report_experiment_ended(
self,
@@ -2441,10 +2485,11 @@ class ExperimentService:
*,
request: Any | None = None,
open_cleanup_pr: bool = False,
+ repository: str | None = None,
) -> 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)
+ self._maybe_open_cleanup_pr(experiment, open_cleanup_pr, repository)
if request is None:
return
@@ -2618,6 +2663,7 @@ class ExperimentService:
conclusion: str | None = None,
conclusion_comment: str | None = None,
open_cleanup_pr: bool = False,
+ repository: str | None = None,
request: Any,
) -> Experiment:
"""Ship a variant and (optionally) end the experiment.
@@ -2697,7 +2743,9 @@ class ExperimentService:
experiment, variant_key=variant_key, release_to_everyone=release_to_everyone, request=request
)
if was_running:
- self._report_experiment_ended(experiment, request=request, open_cleanup_pr=open_cleanup_pr)
+ self._report_experiment_ended(
+ experiment, request=request, open_cleanup_pr=open_cleanup_pr, repository=repository
+ )
return experiment
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 6e1f12c49a9e..9a4e8fa35b4e 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -1058,6 +1058,26 @@ class EndExperimentSerializer(serializers.Serializer):
"(403 otherwise). Only acts for allowlisted teams; ignored otherwise."
),
)
+ repository = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ max_length=255,
+ help_text=(
+ "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."
+ ),
+ )
+
+ def validate_repository(self, value: str | None) -> str | None:
+ if not value:
+ return None
+ parts = value.split("/")
+ if len(parts) != 2 or not parts[0] or not parts[1]:
+ raise serializers.ValidationError("Repository must be in the format organization/repository")
+ return value.lower()
class ExperimentFlagCleanupTaskSerializer(serializers.Serializer):
@@ -1081,6 +1101,26 @@ class ExperimentFlagCleanupTaskSerializer(serializers.Serializer):
)
+class ExperimentFlagCleanupTargetSerializer(serializers.Serializer):
+ repository = serializers.CharField(
+ allow_null=True,
+ 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"],
+ 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 "
+ "connected repositories, so no cleanup PR can be opened)."
+ ),
+ )
+ candidates = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Repositories connected to the team's GitHub integration, to choose a target from.",
+ )
+
+
class ArchiveExperimentSerializer(serializers.Serializer):
disable_feature_flag = serializers.BooleanField(
default=False,
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index e5de03d47f20..ffb833a1dcdc 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -68,6 +68,7 @@ from products.experiments.backend.presentation.serializers import (
EndExperimentSerializer,
ExperimentActivityQuerySerializer,
ExperimentBasicSerializer,
+ ExperimentFlagCleanupTargetSerializer,
ExperimentFlagCleanupTaskSerializer,
ExperimentMetricsRecalculationSerializer,
ExperimentSerializer,
@@ -558,6 +559,7 @@ class EnterpriseExperimentsViewSet(
conclusion=request_serializer.validated_data.get("conclusion"),
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"),
request=request,
)
return Response(ExperimentSerializer(ended_experiment, context=self.get_serializer_context()).data)
@@ -605,6 +607,7 @@ class EnterpriseExperimentsViewSet(
conclusion=request_serializer.validated_data.get("conclusion"),
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"),
request=request,
)
return Response(ExperimentSerializer(shipped_experiment, context=self.get_serializer_context()).data)
@@ -656,6 +659,27 @@ class EnterpriseExperimentsViewSet(
)
return Response(response_serializer.data)
+ @extend_schema(
+ request=None,
+ responses=ExperimentFlagCleanupTargetSerializer,
+ )
+ @action(methods=["GET"], detail=True, url_path="flag_cleanup_target", required_scopes=["experiment:read"])
+ def flag_cleanup_target(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """
+ 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).
+ """
+ experiment: Experiment = self.get_object()
+ # The repository list mirrors what the cleanup checkbox needs, so gate it the same way.
+ self._check_cleanup_pr_access(request)
+ service = ExperimentService(team=self.team, user=request.user)
+ target = service.get_cleanup_repository_target(experiment)
+ return Response(ExperimentFlagCleanupTargetSerializer(target).data)
+
@validated_request(
query_serializer=ExperimentActivityQuerySerializer,
responses={
diff --git a/products/experiments/backend/test/test_experiment_cleanup_pr.py b/products/experiments/backend/test/test_experiment_cleanup_pr.py
index 222832d71b08..59896d74338e 100644
--- a/products/experiments/backend/test/test_experiment_cleanup_pr.py
+++ b/products/experiments/backend/test/test_experiment_cleanup_pr.py
@@ -9,6 +9,9 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework.test import APIRequestFactory
+from posthog.models.organization import OrganizationMembership
+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.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -106,7 +109,7 @@ class TestExperimentCleanupPr(APIBaseTest):
[{"full_name": "acme/monorepo"}, {"full_name": "acme/web"}],
"acme/monorepo",
),
- ("explicit_case_insensitive", "acme/monorepo", [{"full_name": "Acme/Monorepo"}], "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),
@@ -153,3 +156,84 @@ class TestExperimentCleanupPr(APIBaseTest):
else:
self.assertEqual(mock_create_task.call_args.kwargs["repository"], expected_repository)
self.assertIsNotNone(experiment.flag_cleanup_task_id)
+
+ @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_repository_picked_at_end_time_targets_the_task(
+ self,
+ mock_resolve_github,
+ mock_create_task,
+ _mock_feature_enabled,
+ _mock_report,
+ ):
+ # Several cached repos would otherwise be ambiguous and skip the cleanup — the
+ # repository picked in the end request must resolve it.
+ 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()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ ExperimentService(team=self.team, user=self.user).end_experiment(
+ experiment,
+ conclusion="won",
+ open_cleanup_pr=True,
+ repository="acme/api",
+ request=self._make_request(),
+ )
+
+ experiment.refresh_from_db()
+ self.assertEqual(mock_create_task.call_args.kwargs["repository"], "acme/api")
+ self.assertEqual(experiment.repository, "acme/api")
+
+ @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_repository_outside_the_installation_skips_and_is_not_persisted(
+ 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="evil/other",
+ request=self._make_request(),
+ )
+
+ experiment.refresh_from_db()
+ mock_create_task.assert_not_called()
+ self.assertIsNone(experiment.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
+ # experiment viewers, nor be used as a cleanup target.
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.OWNER
+ membership.save()
+ UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ config={"account": {"name": "someone", "type": "User"}},
+ repository_cache=[{"id": 1, "name": "private-repo", "full_name": "someone/private-repo"}],
+ repository_cache_updated_at=timezone.now(),
+ )
+ experiment = self._running_experiment()
+
+ target = ExperimentService(team=self.team, user=self.user).get_cleanup_repository_target(experiment)
+
+ self.assertEqual(target, {"repository": None, "source": "no_integration", "candidates": []})
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 95137428c8ca..e416e1d74322 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -5891,6 +5891,126 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(resp.json()["run_status"], "queued")
self.assertFalse(resp.json()["is_terminal"])
+ @parameterized.expand(
+ [
+ # (name, stored_repository, cached_repos, expected_body)
+ (
+ "no_integration",
+ None,
+ None,
+ {"repository": None, "source": "no_integration", "candidates": []},
+ ),
+ (
+ "single_repo",
+ None,
+ [{"full_name": "acme/web"}],
+ {"repository": "acme/web", "source": "single_repo", "candidates": ["acme/web"]},
+ ),
+ (
+ "ambiguous",
+ None,
+ [{"full_name": "acme/web"}, {"full_name": "acme/api"}],
+ {"repository": None, "source": "ambiguous", "candidates": ["acme/api", "acme/web"]},
+ ),
+ (
+ "explicit",
+ "acme/api",
+ [{"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",
+ [{"full_name": "acme/web"}],
+ {"repository": None, "source": "ambiguous", "candidates": ["acme/web"]},
+ ),
+ (
+ "stale_explicit_with_empty_cache",
+ "gone/repo",
+ [],
+ {"repository": None, "source": "no_integration", "candidates": []},
+ ),
+ ]
+ )
+ @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
+ ):
+ 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 cached_repos is None:
+ mock_resolve_github.return_value = None
+ else:
+ mock_resolve_github.return_value = SimpleNamespace(
+ list_all_cached_repositories=lambda max_repos: cached_repos
+ )
+
+ resp = self.client.get(f"/api/projects/{self.team.id}/experiments/{exp_id}/flag_cleanup_target/")
+
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ self.assertEqual(resp.json(), expected_body)
+
+ @patch("products.experiments.backend.presentation.views.has_tasks_access", return_value=False)
+ def test_flag_cleanup_target_requires_code_access(self, _mock_access):
+ exp_id = self._create_running_experiment(name="Cleanup Target Denied", flag_key="cleanup-target-denied-flag")[
+ "id"
+ ]
+ resp = self.client.get(f"/api/projects/{self.team.id}/experiments/{exp_id}/flag_cleanup_target/")
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN, resp.content)
+
+ @parameterized.expand(
+ [
+ # (name, open_cleanup_pr, repository, expected_status)
+ # Nothing persists in any of these: the value only sticks when a cleanup PR
+ # actually opens against it (team flag on + repo in the installation).
+ ("not_persisted_when_cleanup_does_not_run", True, "acme/web", status.HTTP_200_OK),
+ ("ignored_without_opt_in", False, "acme/web", status.HTTP_200_OK),
+ ("invalid_format_rejected", True, "not-a-repo", status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ @patch("products.experiments.backend.presentation.views.has_tasks_access", return_value=True)
+ @patch("products.experiments.backend.experiment_service.posthoganalytics.feature_enabled", return_value=False)
+ def test_end_endpoint_repository(
+ self, _name, open_cleanup_pr, repository, expected_status, _mock_flag, _mock_access
+ ):
+ exp_id = self._create_running_experiment(name="End With Repo", flag_key="end-with-repo-flag")["id"]
+
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_id}/end/",
+ {"conclusion": "won", "open_cleanup_pr": open_cleanup_pr, "repository": repository},
+ format="json",
+ )
+
+ self.assertEqual(resp.status_code, expected_status, resp.content)
+ self.assertIsNone(Experiment.objects.get(id=exp_id).repository)
+
+ @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_end_endpoint_repository_persists_normalized_when_cleanup_opens(
+ 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_id = self._create_running_experiment(name="End With Repo Live", flag_key="end-with-repo-live-flag")["id"]
+
+ with self.captureOnCommitCallbacks(execute=True):
+ resp = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{exp_id}/end/",
+ {"conclusion": "won", "open_cleanup_pr": True, "repository": "ACME/Web"},
+ format="json",
+ )
+
+ self.assertEqual(resp.status_code, status.HTTP_200_OK, resp.content)
+ self.assertEqual(mock_create_task.call_args.kwargs["repository"], "Acme/Web")
+ self.assertEqual(Experiment.objects.get(id=exp_id).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 b5f026b6dcfe..7fd20d05236d 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -1827,6 +1827,45 @@ export interface EndExperimentApi {
conclusion_comment?: string | null
/** 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.
+ * @maxLength 255
+ * @nullable
+ */
+ repository?: string | null
+}
+
+/**
+ * * `explicit` - explicit
+ * * `single_repo` - single_repo
+ * * `ambiguous` - ambiguous
+ * * `no_integration` - no_integration
+ */
+export type ExperimentFlagCleanupTargetSourceEnumApi =
+ (typeof ExperimentFlagCleanupTargetSourceEnumApi)[keyof typeof ExperimentFlagCleanupTargetSourceEnumApi]
+
+export const ExperimentFlagCleanupTargetSourceEnumApi = {
+ Explicit: 'explicit',
+ SingleRepo: 'single_repo',
+ Ambiguous: 'ambiguous',
+ NoIntegration: 'no_integration',
+} as const
+
+export interface ExperimentFlagCleanupTargetApi {
+ /**
+ * Repository a flag-cleanup pull request would be opened in, or null when none can be determined.
+ * @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).
+ *
+ * * `explicit` - explicit
+ * * `single_repo` - single_repo
+ * * `ambiguous` - ambiguous
+ * * `no_integration` - no_integration */
+ source: ExperimentFlagCleanupTargetSourceEnumApi
+ /** Repositories connected to the team's GitHub integration, to choose a target from. */
+ candidates: string[]
}
/**
@@ -2085,6 +2124,12 @@ export interface ShipVariantApi {
conclusion_comment?: string | null
/** 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.
+ * @maxLength 255
+ * @nullable
+ */
+ repository?: string | null
/** 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 cc99278e6344..2bda112fb713 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -15,6 +15,7 @@ import type {
CreateFromPromptInputApi,
EndExperimentApi,
ExperimentApi,
+ ExperimentFlagCleanupTargetApi,
ExperimentFlagCleanupTaskApi,
ExperimentHoldoutApi,
ExperimentHoldoutsListParams,
@@ -586,6 +587,29 @@ export const experimentsEndCreate = async (
})
}
+export const getExperimentsFlagCleanupTargetRetrieveUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/experiments/${id}/flag_cleanup_target/`
+}
+
+/**
+ * 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).
+ */
+export const experimentsFlagCleanupTargetRetrieve = async (
+ projectId: string,
+ id: number,
+ options?: RequestInit
+): Promise<ExperimentFlagCleanupTargetApi> => {
+ return apiMutator<ExperimentFlagCleanupTargetApi>(getExperimentsFlagCleanupTargetRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getExperimentsFlagCleanupTaskRetrieveUrl = (projectId: string, id: number) => {
return `/api/projects/${projectId}/experiments/${id}/flag_cleanup_task/`
}
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index 0a37f125d319..92753d9f218d 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -973,6 +973,7 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod
export const experimentsEndCreateBodyConclusionCommentMax = 4000
export const experimentsEndCreateBodyOpenCleanupPrDefault = false
+export const experimentsEndCreateBodyRepositoryMax = 255
export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
conclusion: zod
@@ -999,6 +1000,13 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
.describe(
"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."
),
+ repository: zod
+ .string()
+ .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."
+ ),
})
/**
@@ -1072,6 +1080,8 @@ export const ExperimentsRecalculateTimeseriesCreateBody = /* @__PURE__ */ zod
export const experimentsShipVariantCreateBodyConclusionCommentMax = 4000
export const experimentsShipVariantCreateBodyOpenCleanupPrDefault = false
+export const experimentsShipVariantCreateBodyRepositoryMax = 255
+
export const experimentsShipVariantCreateBodyReleaseToEveryoneDefault = false
export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
@@ -1099,6 +1109,13 @@ export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
.describe(
"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."
),
+ repository: zod
+ .string()
+ .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."
+ ),
variant_key: zod.string().describe('The key of the variant to ship.'),
release_to_everyone: zod
.boolean()
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yaml
index 711463c3bd46..b4c190708343 100644
--- a/products/experiments/mcp/tools.yaml
+++ b/products/experiments/mcp/tools.yaml
@@ -1254,6 +1254,9 @@ tools:
experiments-create-from-prompt-create:
operation: experiments_create_from_prompt_create
enabled: false
+ experiments-flag-cleanup-target-retrieve:
+ operation: experiments_flag_cleanup_target_retrieve
+ enabled: false
experiments-flag-cleanup-task-retrieve:
operation: experiments_flag_cleanup_task_retrieve
enabled: false
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index 83e9c2aa281a..2bf45c604350 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -91,7 +91,7 @@ def _first_user_github_integration(user_ids: Iterable[int]) -> UserIntegration |
def resolve_team_github_integration(
- team_id: int, team: Team | None = None, requester_user_id: int | None = None
+ team_id: int, team: Team | None = None, requester_user_id: int | None = None, team_only: bool = False
) -> GitHubIntegrationBase | None:
"""Resolve the GitHub source the agent should use for this team.
@@ -108,6 +108,10 @@ def resolve_team_github_integration(
The owner fallback still applies after the requester check, so an owner-connected source backs
a requester who has none of their own.
+
+ ``team_only=True`` disables both personal-connection fallbacks. Use it when the resolved
+ source's repository names are shown to other team members, or when the work runs under the
+ team installation's bot identity — a personal connection is a cross-account leak there.
"""
integration = (
Integration.objects.filter(team_id=team_id, kind="github")
@@ -125,6 +129,9 @@ def resolve_team_github_integration(
if integration is not None:
return GitHubIntegration(integration)
+ if team_only:
+ return None
+
# User-initiated path: the requester's own connected GitHub (their own credentials, not a leak)
# takes precedence over the owner fallback so they can reference repos only they have connected.
if requester_user_id is not None:
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 26a9c2615642..e8a908e67d29 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24045,6 +24045,12 @@ export namespace Schemas {
conclusion_comment?: string | null;
/** 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.
+ * @maxLength 255
+ * @nullable
+ */
+ repository?: string | null;
}
export interface EndpointBreakdownLimitExceededSignalExtra {
@@ -28039,6 +28045,39 @@ export namespace Schemas {
ensure_experience_continuity?: boolean | null;
}
+ /**
+ * * `explicit` - explicit
+ * * `single_repo` - single_repo
+ * * `ambiguous` - ambiguous
+ * * `no_integration` - no_integration
+ */
+ export type ExperimentFlagCleanupTargetSourceEnum = typeof ExperimentFlagCleanupTargetSourceEnum[keyof typeof ExperimentFlagCleanupTargetSourceEnum];
+
+
+ export const ExperimentFlagCleanupTargetSourceEnum = {
+ Explicit: 'explicit',
+ SingleRepo: 'single_repo',
+ Ambiguous: 'ambiguous',
+ NoIntegration: 'no_integration',
+ } as const;
+
+ export interface ExperimentFlagCleanupTarget {
+ /**
+ * Repository a flag-cleanup pull request would be opened in, or null when none can be determined.
+ * @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).
+ *
+ * * `explicit` - explicit
+ * * `single_repo` - single_repo
+ * * `ambiguous` - ambiguous
+ * * `no_integration` - no_integration */
+ source: ExperimentFlagCleanupTargetSourceEnum;
+ /** Repositories connected to the team's GitHub integration, to choose a target from. */
+ candidates: string[];
+ }
+
/**
* * `not_started` - not_started
* * `queued` - queued
@@ -63110,6 +63149,12 @@ export namespace Schemas {
conclusion_comment?: string | null;
/** 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.
+ * @maxLength 255
+ * @nullable
+ */
+ repository?: string | null;
/** 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 cef27959ca0d..631c83bbc503 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -12002,6 +12002,7 @@ export const ExperimentsEndCreateParams = /* @__PURE__ */ zod.object({
export const experimentsEndCreateBodyConclusionCommentMax = 4000
export const experimentsEndCreateBodyOpenCleanupPrDefault = false
+export const experimentsEndCreateBodyRepositoryMax = 255
export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
conclusion: zod
@@ -12028,6 +12029,13 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({
.describe(
"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."
),
+ repository: zod
+ .string()
+ .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."
+ ),
})
/**
@@ -12221,6 +12229,8 @@ export const ExperimentsShipVariantCreateParams = /* @__PURE__ */ zod.object({
export const experimentsShipVariantCreateBodyConclusionCommentMax = 4000
export const experimentsShipVariantCreateBodyOpenCleanupPrDefault = false
+export const experimentsShipVariantCreateBodyRepositoryMax = 255
+
export const experimentsShipVariantCreateBodyReleaseToEveryoneDefault = false
export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
@@ -12248,6 +12258,13 @@ export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
.describe(
"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."
),
+ repository: zod
+ .string()
+ .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."
+ ),
variant_key: zod.string().describe('The key of the variant to ship.'),
release_to_everyone: zod
.boolean()
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 6b490a6f64c6..201e1fd51d22 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -369,6 +369,9 @@ const experimentEnd = (): ToolBase<typeof ExperimentEndSchema, WithPostHogUrl<Sc
if (params.open_cleanup_pr !== undefined) {
body['open_cleanup_pr'] = params.open_cleanup_pr
}
+ if (params.repository !== undefined) {
+ body['repository'] = params.repository
+ }
const result = await context.api.request<Schemas.Experiment>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/end/`,
@@ -924,6 +927,9 @@ const experimentShipVariant = (): ToolBase<typeof ExperimentShipVariantSchema, W
if (params.open_cleanup_pr !== undefined) {
body['open_cleanup_pr'] = params.open_cleanup_pr
}
+ if (params.repository !== undefined) {
+ body['repository'] = params.repository
+ }
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 8a9a49449e19..c1821978ebc6 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-end.json
@@ -34,6 +34,18 @@
"default": false,
"description": "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.",
"type": "boolean"
+ },
+ "repository": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "type": "string"
+ },
+ {
+ "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."
}
},
"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 5ca554fe60d4..4ac3774bb135 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
@@ -40,6 +40,18 @@
"description": "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.",
"type": "boolean"
},
+ "repository": {
+ "anyOf": [
+ {
+ "maxLength": 255,
+ "type": "string"
+ },
+ {
+ "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."
+ },
"variant_key": {
"description": "The key of the variant to ship.",
"type": "string"