:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): add a project setting that requires tags on new feature flags (#89785)
posthog[bot]ed01085b5ef6
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 39b4c34d4bb0..de69d1185605 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -202,6 +202,9 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"TeamDataWarehouseConfig","TeamExperimentsConfig","TeamFeatureFlagsConfig",+ # OneToOne extension of Team keyed on team_id, only ever read as get(team=team) via+ # get_or_create_team_extension; no endpoint looks it up by a user-supplied ID.+ "TeamFeatureFlagPolicyConfig","TeamTasksConfig","TeamLogsConfig","TeamMarketingAnalyticsConfig",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2148ff462194..a116768c576e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8465,9 +8465,9 @@ snapshots:scenes-app-settings-environment--settings-environment-error-tracking-configuration--light:hash: v1.k794b7964.7d62fa47841096cceaa13c9a7cb15c1152b2f929ee030674bc0d97c5bc66c239.GptZ3dbdhoABnDP-dWhaqUCQOTeKYOsMFokkyWuNjwQscenes-app-settings-environment--settings-environment-feature-flags--dark:- hash: v1.k794b7964.c624ec79ffb024f5c696bfcbad8b9064bd14c5a9dcd5bf8cbede79619a7e49e6.dH9TnaljbVHGlDeLswbLC1fMhgjhpV1m9vMIflWx8A0+ hash: v1.k794b7964.b10b0d44a944587b42d8c7369bc746632ef40cd09a985ab89d6647524ddb7e22.EB3gl1Yu16ppdEPDAxUjwGLikaBqzg3dq_rwpopPzRQscenes-app-settings-environment--settings-environment-feature-flags--light:- hash: v1.k794b7964.4600cafc552dd45dd31dd0fa332c43520ac385fe26989554d0d96ae64853ebd4.yLyNFD0f4Xs0aAkEwfdeGR1acGWM1K8NAMMYocpUFBM+ hash: v1.k794b7964.2f076d1ef742d49b00aa32917731f4472b7d34d24c8234027f3b06904321b891.0nDUQXOOcKn-uP9uloS5A3wCt9LT9cFX-3xo0un5XBEscenes-app-settings-environment--settings-environment-heatmaps--dark:hash: v1.k794b7964.e217c83d622c4dcf42234a33170cdeea692e1688ea84cacd41891af1b1c8eab5.PfryefOdpcOK2e69VOc4ShxwiAjxVzXciIhVF3-s9jUscenes-app-settings-environment--settings-environment-heatmaps--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex de923f5ac82b..89a6922feb47 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -1807,6 +1807,11 @@ export interface TeamWorkflowsConfigApi {email_tracking_consent_mode?: EmailTrackingConsentModeEnumApi}+export interface TeamFeatureFlagPolicyConfigApi {+ /** When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag. */+ require_tags?: boolean+}+/*** * `0` - Disabled* * `1` - Stateless@@ -2629,6 +2634,7 @@ export interface ProjectBackwardCompatApi {marketing_analytics_config?: TeamMarketingAnalyticsConfigApicustomer_analytics_config?: TeamCustomerAnalyticsConfigApiworkflows_config?: TeamWorkflowsConfigApi+ feature_flag_policy_config?: TeamFeatureFlagPolicyConfigApibase_currency?: BaseCurrencyEnumApi/*** Enables capturing clicks that had no effect (rage-click detection).@@ -3489,6 +3495,7 @@ export interface PatchedProjectBackwardCompatApi {marketing_analytics_config?: TeamMarketingAnalyticsConfigApicustomer_analytics_config?: TeamCustomerAnalyticsConfigApiworkflows_config?: TeamWorkflowsConfigApi+ feature_flag_policy_config?: TeamFeatureFlagPolicyConfigApibase_currency?: BaseCurrencyEnumApi/*** Enables capturing clicks that had no effect (rage-click detection).diff --git a/frontend/src/lib/api.mock.ts b/frontend/src/lib/api.mock.tsindex 303f543d5a34..aaa99faaf0c0 100644--- a/frontend/src/lib/api.mock.ts+++ b/frontend/src/lib/api.mock.ts@@ -185,6 +185,9 @@ export const MOCK_DEFAULT_TEAM: TeamType = {managed_viewsets: { revenue_analytics: true },receive_org_level_activity_logs: false,require_evaluation_contexts: false,+ feature_flag_policy_config: {+ require_tags: false,+ },logs_settings: {capture_console_logs: false,},diff --git a/frontend/src/lib/components/BulkActions/BulkUpdateTagsForm.tsx b/frontend/src/lib/components/BulkActions/BulkUpdateTagsForm.tsxindex 63e43914c099..a1a95d20b263 100644--- a/frontend/src/lib/components/BulkActions/BulkUpdateTagsForm.tsx+++ b/frontend/src/lib/components/BulkActions/BulkUpdateTagsForm.tsx@@ -70,8 +70,10 @@ export function BulkUpdateTagsForm({onClose()loadTags()onSuccess?.(response)- } catch {- lemonToast.error('Failed to update tags')+ } catch (error: any) {+ // The server explains rule failures such as a project that requires tags, so show its+ // message rather than a generic one the user cannot act on.+ lemonToast.error(error?.detail || 'Failed to update tags')} finally {setLoading(false)}diff --git a/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.test.tsx b/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.test.tsxnew file mode 100644index 000000000000..f4ce00bee57c--- /dev/null+++ b/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.test.tsx@@ -0,0 +1,24 @@+import '@testing-library/jest-dom'++import { render, within } from '@testing-library/react'++import { LemonCollapse } from './LemonCollapse'++describe('LemonCollapse', () => {+ const panels = [{ key: 'only', header: 'Header', content: <div>Body</div> }]++ // A collapsed panel unmounts its content, so a caller that drives the panel from outside needs+ // "closed" to hold. Reading `activeKey` by value instead of by presence loses that, because the+ // panel then falls back on whatever the person last clicked.+ it('honors a controlled close over the internal state', () => {+ const { container } = render(<LemonCollapse panels={panels} defaultActiveKey="only" activeKey={null} />)++ expect(within(container).queryByText('Body')).not.toBeInTheDocument()+ })++ it('still seeds itself from defaultActiveKey when left uncontrolled', () => {+ const { container } = render(<LemonCollapse panels={panels} defaultActiveKey="only" />)++ expect(within(container).getByText('Body')).toBeInTheDocument()+ })+})diff --git a/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.tsx b/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.tsxindex 994fd107009d..a6100f703b6f 100644--- a/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.tsx+++ b/frontend/src/lib/lemon-ui/LemonCollapse/LemonCollapse.tsx@@ -28,7 +28,8 @@ interface LemonCollapsePropsBase<K extends React.Key> {}interface LemonCollapsePropsSingle<K extends React.Key> extends LemonCollapsePropsBase<K> {- activeKey?: K+ /** Pass this to control the panel. `null` or `undefined` then means closed, not uncontrolled. */+ activeKey?: K | nulldefaultActiveKey?: KonChange?: (activeKey: K | null) => voidmultiple?: false@@ -76,7 +77,10 @@ export function LemonCollapse<K extends React.Key>({} else {// eslint-disable-next-line react-hooks/rules-of-hooksconst [localActiveKey, setLocalActiveKey] = useState<K | null>(props.defaultActiveKey ?? null)- const effectiveActiveKey = props.activeKey ?? localActiveKey+ // Read the presence of `activeKey` rather than its value. A caller that controls the panel+ // has no other way to say "closed", so falling back on a nullish value would reopen the+ // panel from whatever the user last clicked.+ const effectiveActiveKey = 'activeKey' in props ? (props.activeKey ?? null) : localActiveKeyisPanelExpanded = (key: K) => key === effectiveActiveKeyonPanelChange = (key: K, isExpanded: boolean): void => {props.onChange?.(isExpanded ? key : null)diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsxindex 198c4efaae4d..c77b8f76e7fb 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx@@ -163,7 +163,7 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {showImplementation,openVariants,payloadExpanded,- expandAdvancedOnEdit,+ advancedPanelOpen,hasEncryptedPayloadBeenSaved,hasEarlyAccessFeatures,} = useValues(featureFlagLogic)@@ -182,6 +182,7 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {setShowImplementation,setOpenVariants,setPayloadExpanded,+ setAdvancedExpanded,resetEncryptedPayload,} = useActions(featureFlagLogic)const { tags: availableTags } = useValues(tagsModel)@@ -518,10 +519,12 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {</LemonField></div>- {/* Advanced options - collapsed by default unless opened via overview pencil */}+ {/* Advanced options - collapsed by default. Controlled rather than seeded,+ because a failed save has to open the panel to show a tag error inside it. */}<LemonCollapseclassName="bg-bg-light"- defaultActiveKey={expandAdvancedOnEdit ? 'advanced' : undefined}+ activeKey={advancedPanelOpen ? 'advanced' : null}+ onChange={(key) => setAdvancedExpanded(key === 'advanced')}panels={[{key: 'advanced',diff --git a/frontend/src/scenes/feature-flags/RequireFeatureFlagTags.tsx b/frontend/src/scenes/feature-flags/RequireFeatureFlagTags.tsxnew file mode 100644index 000000000000..27e33d91f7e1--- /dev/null+++ b/frontend/src/scenes/feature-flags/RequireFeatureFlagTags.tsx@@ -0,0 +1,31 @@+import { useActions, useValues } from 'kea'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'+import { teamLogic } from 'scenes/teamLogic'++export function RequireFeatureFlagTags(): JSX.Element {+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)+ const { updateCurrentTeam } = useActions(teamLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ const handleToggle = (enabled: boolean): void => {+ updateCurrentTeam({ feature_flag_policy_config: { require_tags: enabled } })+ }++ return (+ <LemonSwitch+ data-attr="require-feature-flag-tags-switch"+ onChange={handleToggle}+ label="Require tags on feature flags"+ bordered+ checked={currentTeam?.feature_flag_policy_config?.require_tags || false}+ disabled={currentTeamLoading}+ disabledReason={restrictedReason}+ />+ )+}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 42f6ba8e3c41..9d43c3e45cc4 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -15,6 +15,7 @@ import { dayjs } from 'lib/dayjs'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'@@ -63,6 +64,7 @@ import {scheduleDateToProjectTzISO,slugifyFeatureFlagKey,validateFeatureFlagKey,+ validateFeatureFlagTags,validateFeatureFlagVariantKey,validateVariantRolloutSum,} from './featureFlagLogic'@@ -3029,6 +3031,63 @@ describe('validateVariantRolloutSum', () => {})})+describe('validateFeatureFlagTags', () => {+ it.each([+ { desc: 'the project does not require tags', tags: [], required: false, isNewFlag: true, hadTags: false },+ { desc: 'a new flag carries a tag', tags: ['billing'], required: true, isNewFlag: true, hadTags: false },+ // `hadTags` exists for this case: turning the setting on must not freeze the flags that+ // predate it. Collapsing the check to a plain length test would block this save.+ {+ desc: 'a flag that predates the setting is edited while still untagged',+ tags: [],+ required: true,+ isNewFlag: false,+ hadTags: false,+ },+ ])('allows the save when $desc', ({ tags, required, isNewFlag, hadTags }) => {+ expect(validateFeatureFlagTags(tags, { required, isNewFlag, hadTags })).toBeUndefined()+ })++ it.each([+ {+ desc: 'a new flag has no tags',+ tags: [],+ required: true,+ isNewFlag: true,+ hadTags: false,+ error: 'Add at least one tag',+ },+ // A blank tag is not a tag: the server normalizes it away, so accepting it here would only+ // buy a rejected save.+ {+ desc: 'a new flag has only a blank tag',+ tags: [' '],+ required: true,+ isNewFlag: true,+ hadTags: false,+ error: 'Add at least one tag',+ },+ {+ desc: 'a tagged flag loses its last tag',+ tags: [],+ required: true,+ isNewFlag: false,+ hadTags: true,+ error: 'Keep at least one tag',+ },+ {+ desc: 'a tagged flag has its last tag replaced by a blank one',+ tags: [''],+ required: true,+ isNewFlag: false,+ hadTags: true,+ error: 'Keep at least one tag',+ },+ ])('blocks the save when $desc', ({ tags, required, isNewFlag, hadTags, error }) => {+ expect(validateFeatureFlagTags(tags, { required, isNewFlag, hadTags })).toContain(error)+ })+})+describe('variant rollout sum validation', () => {let logic: ReturnType<typeof featureFlagLogic.build>@@ -3116,6 +3175,59 @@ describe('variant rollout sum validation', () => {})})+describe('required tags on a collapsed advanced panel', () => {+ let logic: ReturnType<typeof featureFlagLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [+ 200,+ MOCK_FEATURE_FLAG,+ ],+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/status`]: () => [+ 200,+ MOCK_FEATURE_FLAG_STATUS,+ ],+ },+ })+ initKeaTests()+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ feature_flag_policy_config: { require_tags: true },+ })+ logic = featureFlagLogic({ id: 1 })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ // The tag input sits inside the advanced panel, and a collapsed LemonCollapse unmounts its+ // children, so without this the save is blocked with no field on screen to explain why.+ it('opens the panel when a save is blocked for emptying the last tag', async () => {+ logic.actions.setOriginalFeatureFlag({ ...MOCK_FEATURE_FLAG, tags: ['billing'] } as FeatureFlagType)+ logic.actions.setFeatureFlag({ ...MOCK_FEATURE_FLAG, tags: [] } as FeatureFlagType)+ expect(logic.values.advancedPanelOpen).toBe(false)++ await expectLogic(logic, () => {+ logic.actions.submitFeatureFlag()+ }).toFinishAllListeners()++ expect(logic.values.advancedPanelOpen).toBe(true)+ })++ // A flag that predates the setting stays editable, so an untagged one must not be held back.+ it('leaves the panel closed when an untagged flag saves cleanly', async () => {+ logic.actions.setOriginalFeatureFlag({ ...MOCK_FEATURE_FLAG, tags: [] } as FeatureFlagType)+ logic.actions.setFeatureFlag({ ...MOCK_FEATURE_FLAG, tags: [] } as FeatureFlagType)++ expect(logic.values.featureFlagHasErrors).toBe(false)+ expect(logic.values.advancedPanelOpen).toBe(false)+ })+})+describe('variant reordering', () => {let logic: ReturnType<typeof featureFlagLogic.build>diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex bc0b635ddcd0..ff8a1fa22d23 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -488,6 +488,23 @@ export function validateVariantRolloutSum(variants?: MultivariateFlagVariant[]):return `Percentage rollouts for variants must sum to 100 (currently ${displayedSum}).`}+/** Reason string when the project requires flag tags and none are set, otherwise undefined. */+export function validateFeatureFlagTags(+ tags: string[] | undefined,+ { required, isNewFlag, hadTags }: { required: boolean; isNewFlag: boolean; hadTags: boolean }+): string | undefined {+ // Count named tags, not entries. `cleanTag` trims without dropping empties, so a `['']` would+ // otherwise pass here and be rejected by the server, which normalizes blanks away.+ if (!required || tags?.some((tag) => tag.trim().length > 0)) {+ return undefined+ }+ if (isNewFlag) {+ return 'Add at least one tag. This project requires new feature flags to be tagged.'+ }+ // Flags that predate the setting stay editable, so only block emptying one that already has tags.+ return hadTags ? 'Keep at least one tag. This project requires feature flags to stay tagged.' : undefined+}+function validatePayloadRequired(is_remote_configuration: boolean, payload?: JsonType): string | undefined {if (!is_remote_configuration) {return undefined@@ -745,6 +762,8 @@ export interface featureFlagLogicValues {activeRecurringSchedules: ScheduledChangeType[]activeSchedules: ScheduledChangeType[]activeTab: FeatureFlagsTab+ advancedExpanded: boolean | null+ advancedPanelOpen: booleanaggregationTargetName: stringavailableTabs: FeatureFlagsTab[]breadcrumbs: Breadcrumb[]@@ -935,6 +954,7 @@ export interface featureFlagLogicValues {showImplementation: booleanshowStaleFlagBanner: booleansidePanelContext: SidePanelSceneContext | null+ tagsRequired: booleantemplateExpanded: booleantemplates: Array<{description: string@@ -1397,6 +1417,9 @@ export interface featureFlagLogicActions {setAccessDeniedToFeatureFlag: () => {value: true}+ setAdvancedExpanded: (expanded: boolean) => {+ expanded: boolean+ }setBucketingIdentifier: (bucketingIdentifier: FeatureFlagBucketingIdentifier | null) => {bucketingIdentifier: FeatureFlagBucketingIdentifier | null}@@ -1930,6 +1953,13 @@ export interface featureFlagLogicMeta {sidePanelContext: (featureFlag: FeatureFlagType) => SidePanelSceneContext | nullrecordingFilterForFlag: (featureFlag: FeatureFlagType) => Partial<RecordingUniversalFilters>hasEarlyAccessFeatures: (featureFlag: FeatureFlagType) => boolean+ tagsRequired: (currentTeam: TeamPublicType | TeamType | null) => boolean+ advancedPanelOpen: (+ advancedExpanded: boolean | null,+ expandAdvancedOnEdit: boolean,+ tagsRequired: boolean,+ featureFlag: FeatureFlagType+ ) => booleanearlyAccessFeaturesList: (featureFlag: FeatureFlagType) => MinimalEarlyAccessFeatureType[]featureFlagKey: (featureFlag: FeatureFlagType) => stringcanCreateEarlyAccessFeature: (featureFlag: FeatureFlagType, variants: MultivariateFlagVariant[]) => boolean@@ -2107,6 +2137,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// V2 form UI actionssetShowImplementation: (show: boolean) => ({ show }),setOpenVariants: (openVariants: string[]) => ({ openVariants }),+ setAdvancedExpanded: (expanded: boolean) => ({ expanded }),setPayloadExpanded: (expanded: boolean) => ({ expanded }),setTemplateExpanded: (expanded: boolean) => ({ expanded }),applyUrlTemplate: (templateId: string) => ({ templateId }),@@ -2121,10 +2152,17 @@ export const featureFlagLogic = kea<featureFlagLogicType>([...NEW_FLAG,ensure_experience_continuity: values.currentTeam?.flags_persistence_default || false,},- errors: ({ key, filters, is_remote_configuration }) => {+ errors: ({ key, filters, is_remote_configuration, tags }) => {const rolloutSumError = validateVariantRolloutSum(filters?.multivariate?.variants)return {key: validateFeatureFlagKey(key),+ // Cast because kea-forms types a `string[]` field's error as `string[]`, while+ // LemonField only renders a plain string.+ tags: validateFeatureFlagTags(tags, {+ required: values.tagsRequired,+ isNewFlag: !values.featureFlag.id,+ hadTags: !!values.originalFeatureFlag?.tags?.length,+ }) as any,filters: {multivariate: {variants: filters?.multivariate?.variants?.map(@@ -2630,6 +2668,16 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},},],+ advancedExpanded: [+ // `null` means the person has not touched the panel yet, so `advancedPanelOpen` still+ // decides for them. Re-entering edit mode returns to that, so the overview pencil can+ // reopen the panel after they collapsed it in an earlier edit.+ null as boolean | null,+ {+ setAdvancedExpanded: (_, { expanded }) => expanded,+ editFeatureFlag: () => null,+ },+ ],payloadExpanded: [false,{@@ -3567,6 +3615,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([if (filtersErrors?.payloads?.true && !values.payloadExpanded) {actions.setPayloadExpanded(true)}+ if (formErrors?.tags && !values.advancedPanelOpen) {+ actions.setAdvancedExpanded(true)+ }// Yield so React flushes the expand-actions re-render before scrollToFormError schedules// its requestAnimationFrame callback — otherwise on browsers/scheduler combinations where// the render lands after RAF, `.Field--error` isn't in the DOM yet and the fallback toast@@ -4177,7 +4228,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.setOriginalFeatureFlag({ ...values.originalFeatureFlag, tags: previousTags })}actions.updateFlag({ ...flag, tags: previousTags })- lemonToast.error('Failed to save tags')+ // The server explains rule failures such as a project that requires tags, so show+ // its message rather than a generic one the user cannot act on.+ lemonToast.error(error?.detail || 'Failed to save tags')}},editFeatureFlag: async ({ editing }) => {@@ -4415,6 +4468,23 @@ export const featureFlagLogic = kea<featureFlagLogicType>([return (featureFlag?.features?.length || 0) > 0},],+ tagsRequired: [+ (s) => [s.currentTeam],+ (currentTeam: TeamPublicType | TeamType | null): boolean =>+ !!currentTeam?.feature_flag_policy_config?.require_tags,+ ],+ advancedPanelOpen: [+ (s) => [s.advancedExpanded, s.expandAdvancedOnEdit, s.tagsRequired, s.featureFlag],+ (+ advancedExpanded: boolean | null,+ expandAdvancedOnEdit: boolean,+ tagsRequired: boolean,+ featureFlag: FeatureFlagType+ ): boolean =>+ // A new flag that needs a tag opens the panel up front, so the person sees the tag+ // input before they submit rather than after a rejected save.+ advancedExpanded ?? (expandAdvancedOnEdit || (!featureFlag.id && tagsRequired)),+ ],earlyAccessFeaturesList: [(s) => [s.featureFlag],(featureFlag: FeatureFlagType) => {diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex e8aec9acad6a..c428aef4b820 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -105,6 +105,7 @@ import {FlagPersistenceSettings,FlagsSecureApiKeys,RequireEvaluationContexts,+ RequireFeatureFlagTags,} from './environment/FeatureFlagSettings'import { GroupAnalyticsConfig } from './environment/GroupAnalyticsConfig'import { HeatmapsSettings } from './environment/HeatmapsSettings'@@ -755,6 +756,14 @@ export const SETTINGS_MAP: SettingSection[] = [component: <FlagChangeConfirmationSettings />,keywords: ['confirmation', 'safety', 'change', 'release'],},+ {+ id: 'feature-flag-require-tags',+ title: 'Require tags',+ description:+ 'Require every new feature flag to have at least one tag, and stop a tagged flag losing its last one, so flags stay attributable to a team or workstream. Flags created for surveys, experiments, early access features, product tours, and web experiments are exempt.',+ component: <RequireFeatureFlagTags />,+ keywords: ['tag', 'tags', 'require', 'governance'],+ },{id: 'feature-flag-require-evaluation-contexts',title: 'Require evaluation contexts',diff --git a/frontend/src/scenes/settings/environment/FeatureFlagSettings.tsx b/frontend/src/scenes/settings/environment/FeatureFlagSettings.tsxindex 1e8b42a041c9..dac3079fff02 100644--- a/frontend/src/scenes/settings/environment/FeatureFlagSettings.tsx+++ b/frontend/src/scenes/settings/environment/FeatureFlagSettings.tsx@@ -4,6 +4,7 @@ export {FlagsSecureApiKeys,} from 'scenes/feature-flags/FeatureFlagSettings'export { RequireEvaluationContexts } from 'scenes/feature-flags/RequireEvaluationContexts'+export { RequireFeatureFlagTags } from 'scenes/feature-flags/RequireFeatureFlagTags'export { EvaluationContextSuggestions } from 'scenes/feature-flags/EvaluationContextSuggestions'export { DefaultEvaluationContexts } from 'scenes/feature-flags/DefaultEvaluationContexts'export { DefaultReleaseConditions } from 'scenes/feature-flags/DefaultReleaseConditions'diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 4352a62cd786..dabc4ab89ce0 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -168,6 +168,7 @@ export type SettingId =| 'feature-flag-default-evaluation-contexts'| 'feature-flag-default-release-conditions'| 'feature-flag-evaluation-context-suggestions'+ | 'feature-flag-require-tags'| 'feature-flag-require-evaluation-contexts'| 'feature-flag-secure-api-key'| 'feature-flags-interface'diff --git a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx b/frontend/src/scenes/team-activity/teamActivityDescriber.tsxindex 3029b8d80d5e..f8195c9d93d5 100644--- a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx+++ b/frontend/src/scenes/team-activity/teamActivityDescriber.tsx@@ -754,6 +754,7 @@ const TEAM_PROPERTIES_MAPPING: Record<keyof TeamType, (change: ActivityChange) =web_analytics_pre_aggregated_tables_version: () => null,managed_viewsets: () => null,workflows_config: () => null,+ feature_flag_policy_config: () => null,event_retention_months: () => null,events_retention_enforced: () => null,}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex fab7d7d21a37..0f1d2e52b078 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -897,6 +897,8 @@ export interface TeamType extends TeamBasicType {receive_org_level_activity_logs: boolean | nullcustomer_analytics_config: CustomerAnalyticsConfigworkflows_config: WorkflowsConfig+ // Optional so cached team objects from before this field shipped still typecheck.+ feature_flag_policy_config?: FeatureFlagPolicyConfigbusiness_model?: 'b2b' | 'b2c' | 'other' | null}@@ -906,6 +908,10 @@ export interface WorkflowsConfig {email_tracking_consent_mode?: 'off' | 'opt_out' | 'opt_in'}+export interface FeatureFlagPolicyConfig {+ require_tags: boolean+}+export interface ProductIntentType {product_type: stringcreated_at: stringdiff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.pyindex 3f96fd2e80bd..9a239ebb1904 100644--- a/posthog/api/event_definition.py+++ b/posthog/api/event_definition.py@@ -575,6 +575,7 @@ class EventDefinitionViewSet(# The single-object event-definition update path logs under the "changed" verb.activity="changed",)+ self.validate_bulk_tag_changes(objects, validated["action"], validated["tags"])updated = apply_bulk_tag_changes(objects, validated["action"], validated["tags"], activity_context=activity_context)diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 01bbc951e8bd..ffc82cd92f7b 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -36,6 +36,7 @@ from posthog.api.team import (EvaluationContextSuggestionResponseSerializer,EventIngestionRestrictionSerializer,TeamCustomerAnalyticsConfigSerializer,+ TeamFeatureFlagPolicyConfigSerializer,TeamMarketingAnalyticsConfigSerializer,TeamRevenueAnalyticsConfigSerializer,TeamSerializer,@@ -269,6 +270,31 @@ def update_team_workflows_config(team: Team, validated_data: dict[str, Any], *,capture_team_config_diff(team, "workflows_config", old_config, new_config, context=context)+def update_team_feature_flag_policy_config(team: Team, validated_data: dict[str, Any], *, context: dict) -> None:+ user_access_control = context.get("user_access_control")+ old_config = {+ field: getattr(team.feature_flag_policy_config, field)+ for field in TeamFeatureFlagPolicyConfigSerializer.Meta.fields+ }++ serializer = TeamFeatureFlagPolicyConfigSerializer(+ team.feature_flag_policy_config,+ data=validated_data,+ partial=True,+ context={**context, "user_access_control": user_access_control},+ )+ if not serializer.is_valid():+ raise serializers.ValidationError(_format_serializer_errors(serializer.errors))++ serializer.save()++ new_config = {+ field: getattr(team.feature_flag_policy_config, field)+ for field in TeamFeatureFlagPolicyConfigSerializer.Meta.fields+ }+ capture_team_config_diff(team, "feature_flag_policy_config", old_config, new_config, context=context)++def verify_team_session_recording_retention_period(team: Team, new_retention_period: str) -> None:retention_feature = team.organization.get_available_feature(AvailableFeature.SESSION_REPLAY_DATA_RETENTION)highest_retention_entitlement = parse_feature_to_entitlement(retention_feature)@@ -577,6 +603,7 @@ class ProjectBackwardCompatSerializer(marketing_analytics_config = TeamMarketingAnalyticsConfigSerializer(required=False) # Compat with TeamSerializercustomer_analytics_config = TeamCustomerAnalyticsConfigSerializer(required=False) # Compat with TeamSerializerworkflows_config = TeamWorkflowsConfigSerializer(required=False) # Compat with TeamSerializer+ feature_flag_policy_config = TeamFeatureFlagPolicyConfigSerializer(required=False) # Compat with TeamSerializer# No `default` on purpose: a default value would be auto-injected into every create payload, which trips the# admin-only-fields-on-creation gate in validate_team_attrs and blocks members allowed to create projects.base_currency = serializers.ChoiceField(choices=CURRENCY_CODE_CHOICES, required=False) # Compat with TeamSerializer@@ -683,6 +710,7 @@ class ProjectBackwardCompatSerializer("marketing_analytics_config", # Compat with TeamSerializer"customer_analytics_config", # Compat with TeamSerializer"workflows_config", # Compat with TeamSerializer+ "feature_flag_policy_config", # Compat with TeamSerializer"base_currency", # Compat with TeamSerializer"capture_dead_clicks", # Compat with TeamSerializer"cookieless_server_hash_mode", # Compat with TeamSerializer@@ -796,6 +824,7 @@ class ProjectBackwardCompatSerializer("marketing_analytics_config","customer_analytics_config","workflows_config",+ "feature_flag_policy_config","event_retention_months",}@@ -927,6 +956,10 @@ class ProjectBackwardCompatSerializer(def validate_workflows_config(value):return TeamSerializer.validate_workflows_config(value)+ @staticmethod+ def validate_feature_flag_policy_config(value):+ return TeamSerializer.validate_feature_flag_policy_config(value)+def get_effective_membership_level(self, project: Project) -> Optional[OrganizationMembership.Level]:team = project.passthrough_teamreturn self.user_permissions.team(team).effective_membership_level@@ -1075,6 +1108,7 @@ class ProjectBackwardCompatSerializer("marketing_analytics_config","customer_analytics_config","workflows_config",+ "feature_flag_policy_config",):validated_data.pop(config_field, None)@@ -1156,6 +1190,9 @@ class ProjectBackwardCompatSerializer(if config_data := validated_data.pop("workflows_config", None):update_team_workflows_config(team, config_data, context=config_context)+ if config_data := validated_data.pop("feature_flag_policy_config", None):+ update_team_feature_flag_policy_config(team, config_data, context=config_context)+if "session_recording_retention_period" in validated_data:verify_team_session_recording_retention_period(team, validated_data["session_recording_retention_period"])diff --git a/posthog/api/tagged_item.py b/posthog/api/tagged_item.pyindex abfa5e2b0cf6..d7d2b058e1c8 100644--- a/posthog/api/tagged_item.py+++ b/posthog/api/tagged_item.py@@ -1,5 +1,5 @@import dataclasses-from collections.abc import Sequence+from collections.abc import Iterable, Sequencefrom typing import TYPE_CHECKING, Any, Optional, castfrom django.db import models@@ -49,6 +49,30 @@ def cleanup_orphan_tags(team_id: int) -> None:Tag.objects.filter(Q(team_id=team_id) & Q(tagged_items__isnull=True)).delete()+def normalize_tag_names(tags: Iterable[str]) -> set[str]:+ """The tag names a request's raw strings resolve to, minus the blanks.++ ``tagify`` strips whitespace, so a payload of ``[""]`` or ``[" "]`` would otherwise reach+ ``Tag.objects.get_or_create`` and leave an empty tag that renders as nothing.+ """+ return {name for name in (tagify(tag) for tag in tags) if name}+++def current_tag_names(obj: Any) -> set[str]:+ """The object's tags, preferring a ``prefetched_tags`` attribute over a fresh query."""+ tagged_items = obj.prefetched_tags if hasattr(obj, "prefetched_tags") else obj.tagged_items.select_related("tag")+ return {tagged_item.tag.name for tagged_item in tagged_items}+++def resolve_bulk_tags(current_tags: set[str], tag_action: str, normalized_tags: set[str]) -> set[str]:+ """The tags an object ends up with after an add/remove/set bulk mutation."""+ if tag_action == "add":+ return current_tags | normalized_tags+ if tag_action == "remove":+ return current_tags - normalized_tags+ return set(normalized_tags)++@dataclasses.dataclass(frozen=True)class BulkTagActivityContext:"""Context needed to write an activity-log entry for each object mutated in bulk.@@ -84,26 +108,15 @@ def apply_bulk_tag_changes(recorded for every object whose tags actually change, mirroring the single-object update pathso the bulk endpoint leaves the same audit trail."""- normalized_tags = {tagify(t) for t in tags}+ normalized_tags = normalize_tag_names(tags)updated: list[dict[str, Any]] = []team_ids: set[int] = set()activity_entries: list[LogActivityEntry] = []for obj in objects:team_ids.add(obj.team_id)- current_tags = {- ti.tag.name- for ti in (- obj.prefetched_tags if hasattr(obj, "prefetched_tags") else obj.tagged_items.select_related("tag").all()- )- }-- if tag_action == "add":- new_tags = current_tags | normalized_tags- elif tag_action == "remove":- new_tags = current_tags - normalized_tags- else: # set- new_tags = set(normalized_tags)+ current_tags = current_tag_names(obj)+ new_tags = resolve_bulk_tags(current_tags, tag_action, normalized_tags)set_tags_on_object(list(new_tags), obj)updated.append({"id": obj.id, "tags": sorted(new_tags)})@@ -300,6 +313,17 @@ class TaggedItemViewSetMixin(viewsets.GenericViewSet):activity="updated",)+ def validate_bulk_tag_changes(self, objects: Sequence, tag_action: str, tags: list[str]) -> None:+ """Hook for resources whose tags carry a rule the bulk path must honor.++ Raise ``serializers.ValidationError`` to reject the whole request. Rejecting beats skipping+ here: the bulk-tag form reports skipped objects as permission failures, so a rule-based skip+ would reach the user as the wrong reason.++ A viewset that reimplements ``bulk_update_tags`` must call this itself before+ ``apply_bulk_tag_changes``, or its resource silently opts out of its own rule.+ """+def prefetch_tagged_items_if_available(self, queryset: QuerySet | models.query.RawQuerySet) -> QuerySet:if isinstance(queryset, models.query.RawQuerySet):return queryset # type: ignore[return-value] # ty: ignore[invalid-return-type]@@ -386,6 +410,8 @@ class TaggedItemViewSetMixin(viewsets.GenericViewSet):if obj_id not in found_ids:errors.append({"id": obj_id, "reason": "Not found"})+ self.validate_bulk_tag_changes(editable_objects, tag_action, tags)+updated = apply_bulk_tag_changes(editable_objects, tag_action, tags, activity_context=self._bulk_tag_activity_context())diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 2b7ab2d62750..c1f1c4657559 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -118,6 +118,7 @@ from products.access_control.backend.presentation.access_control import (from products.access_control.backend.presentation.access_control_settings import AccessControlSettingsViewSetMixinfrom products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfigfrom products.feature_flags.backend.models.evaluation_context import EvaluationContext, normalize_context_name+from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfigfrom products.logs.backend.models import TeamLogsConfigfrom products.workflows.backend.models.team_workflows_config import EmailTrackingConsentMode, TeamWorkflowsConfig@@ -471,6 +472,7 @@ TEAM_CONFIG_FIELDS = ("feature_flag_confirmation_message","default_evaluation_contexts_enabled","require_evaluation_contexts",+ "feature_flag_policy_config","capture_dead_clicks","default_data_theme","revenue_analytics_config",@@ -787,6 +789,22 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContrfields = ["capture_workflows_engagement_events", "email_tracking_consent_mode"]+class TeamFeatureFlagPolicyConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):+ require_tags = serializers.BooleanField(+ required=False,+ help_text=(+ "When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its "+ "last one. A create that declares it comes from a survey, experiment, early access feature, "+ "product tour, or web experiment is exempt, because those forms have no tag input. The caller "+ "sets that declaration, so a flag can still be created without a tag."+ ),+ )++ class Meta:+ model = TeamFeatureFlagPolicyConfig+ fields = ["require_tags"]++class TeamCustomerAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):activity_event = serializers.JSONField(required=False, help_text="Event used as the activity signal (DAU/WAU/MAU).")signup_pageview_event = serializers.JSONField(@@ -1038,6 +1056,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixinmarketing_analytics_config = TeamMarketingAnalyticsConfigSerializer(required=False)customer_analytics_config = TeamCustomerAnalyticsConfigSerializer(required=False)workflows_config = TeamWorkflowsConfigSerializer(required=False)+ feature_flag_policy_config = TeamFeatureFlagPolicyConfigSerializer(required=False)base_currency = serializers.ChoiceField(choices=CURRENCY_CODE_CHOICES, default=DEFAULT_CURRENCY)event_retention_months = serializers.IntegerField(read_only=True,@@ -1232,6 +1251,16 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixinraise exceptions.ValidationError(_format_serializer_errors(serializer.errors))return serializer.validated_data+ @staticmethod+ def validate_feature_flag_policy_config(value):+ if value is None:+ return None++ serializer = TeamFeatureFlagPolicyConfigSerializer(data=value)+ if not serializer.is_valid():+ raise exceptions.ValidationError(_format_serializer_errors(serializer.errors))+ return serializer.validated_data+@staticmethoddef validate_session_recording_linked_flag(value) -> dict | None:if value is None:@@ -1851,6 +1880,9 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixinif config_data := validated_data.pop("workflows_config", None):self._update_workflows_config(instance, config_data)+ if config_data := validated_data.pop("feature_flag_policy_config", None):+ self._update_feature_flag_policy_config(instance, config_data)+if "session_recording_retention_period" in validated_data:self._verify_update_session_recording_retention_period(instance, validated_data["session_recording_retention_period"]@@ -2102,6 +2134,30 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixinself._capture_diff(instance, "workflows_config", old_config, new_config)return instance+ def _update_feature_flag_policy_config(self, instance: Team, validated_data: dict[str, Any]) -> Team:+ old_config = {+ field: getattr(instance.feature_flag_policy_config, field)+ for field in TeamFeatureFlagPolicyConfigSerializer.Meta.fields+ }++ serializer = TeamFeatureFlagPolicyConfigSerializer(+ instance.feature_flag_policy_config,+ data=validated_data,+ partial=True,+ context={**self.context, "user_access_control": self.user_access_control},+ )+ if not serializer.is_valid():+ raise serializers.ValidationError(_format_serializer_errors(serializer.errors))++ serializer.save()++ new_config = {+ field: getattr(instance.feature_flag_policy_config, field)+ for field in TeamFeatureFlagPolicyConfigSerializer.Meta.fields+ }+ self._capture_diff(instance, "feature_flag_policy_config", old_config, new_config)+ return instance+def _verify_update_session_recording_retention_period(self, instance: Team, new_retention_period: str):retention_feature = instance.organization.get_available_feature(AvailableFeature.SESSION_REPLAY_DATA_RETENTION)highest_retention_entitlement = parse_feature_to_entitlement(retention_feature)diff --git a/posthog/api/test/test_team_project_differential.py b/posthog/api/test/test_team_project_differential.pyindex 1b823ab0291d..101c748c1858 100644--- a/posthog/api/test/test_team_project_differential.py+++ b/posthog/api/test/test_team_project_differential.py@@ -203,6 +203,7 @@ FIELD_VALUES: dict[str, Any] = {"marketing_analytics_config": {"attribution_window_days": 14},"customer_analytics_config": {"activity_event": "$pageview"},"workflows_config": {"capture_workflows_engagement_events": True},+ "feature_flag_policy_config": {"require_tags": True},"onboarding_tasks": {"task_x": "completed"},"base_currency": "EUR","web_analytics_pre_aggregated_tables_enabled": True,diff --git a/posthog/models/team/README.md b/posthog/models/team/README.mdindex 68d6d68044d2..342ac341f88a 100644--- a/posthog/models/team/README.md+++ b/posthog/models/team/README.md@@ -69,3 +69,8 @@ config = get_or_create_team_extension(team, TeamMyProductConfig)Some older extensions still have `team.<product>_config` descriptors on the Team model.These are transitional and should not be used as a pattern for new extensions.++An extension exposed as a nested field on the team or project serializer is the exception, and does+need the descriptor.+DRF skips a `required=False` field whose attribute is missing, so removing the descriptor drops the+setting from every API response without raising.diff --git a/posthog/models/team/team.py b/posthog/models/team/team.pyindex 09a8f238bc07..bac66c841855 100644--- a/posthog/models/team/team.py+++ b/posthog/models/team/team.py@@ -756,6 +756,12 @@ class Team(UUIDTClassicModel):# TRANSITIONAL: These accessors exist for backward compat with existing# `team.<product>_config` call sites. New products should NOT add accessors# here — use get_or_create_team_extension() at call sites instead.+ #+ # One exception, and the reason every config below is also a team/project serializer field: a+ # config exposed that way needs the attribute. DRF skips a required=False field whose attribute+ # is missing, so dropping one of these accessors strips the setting from every API response+ # without raising. A config no serializer exposes needs no accessor here, and is reached through+ # the helper the way TeamFeatureFlagDefaultsConfig is.@cached_propertydef revenue_analytics_config(self):@@ -783,6 +789,12 @@ class Team(UUIDTClassicModel):return get_or_create_team_extension(self, TeamWorkflowsConfig)+ @cached_property+ def feature_flag_policy_config(self):+ from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig++ return get_or_create_team_extension(self, TeamFeatureFlagPolicyConfig)+@propertydef default_modifiers(self) -> dict:# Deferred: posthog.schema (the pydantic models) stays off django.setup(),diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 910ce7d2fa41..7ccce54ad9c5 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -6,7 +6,7 @@ import jsonimport mathimport loggingimport functools-from collections.abc import Iterable, Iterator+from collections.abc import Iterable, Iterator, Sequencefrom dataclasses import asdictfrom datetime import datetime, timedeltafrom typing import Any, NoReturn, Optional, cast@@ -39,7 +39,13 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.services.flags_service import RETRYABLE_FLAGS_SERVICE_EXCEPTIONS, get_flags_from_servicefrom posthog.api.shared import UserBasicSerializer-from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin+from posthog.api.tagged_item import (+ TaggedItemSerializerMixin,+ TaggedItemViewSetMixin,+ current_tag_names,+ normalize_tag_names,+ resolve_bulk_tags,+)from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, ServiceRequest, actionfrom posthog.auth import (IDJagAccessTokenAuthentication,@@ -116,6 +122,7 @@ from products.feature_flags.backend.flag_status import (from products.feature_flags.backend.local_evaluation import _get_flag_properties_from_filtersfrom products.feature_flags.backend.models.evaluation_context import normalize_context_namefrom products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboards+from products.feature_flags.backend.models.team_feature_flag_policy_config import team_requires_flag_tagsfrom products.feature_flags.backend.session_recording_links import (REPLAY_LINKED_FLAG_DELETE_ERROR,replay_linked_flag_ids,@@ -454,6 +461,15 @@ FEATURE_FLAG_CREATION_CONTEXT_CHOICES = ("product_tours",)+# A flag created to back one of these objects never passes through a form with a tag input, so the+# team's "require tags" setting would dead-end those flows rather than get anything tagged. The+# caller declares its own creation_context, so this exempts flows rather than enforcing anything on+# them - the setting is bookkeeping, not an access boundary.+TAG_REQUIREMENT_EXEMPT_CREATION_CONTEXTS = frozenset(FEATURE_FLAG_CREATION_CONTEXT_CHOICES) - {"feature_flags"}++REQUIRE_TAGS_ON_CREATE_ERROR = "Add at least one tag. This project requires new feature flags to be tagged."+REQUIRE_TAGS_ON_UPDATE_ERROR = "Keep at least one tag. This project requires feature flags to stay tagged."+def find_dependent_flags(flag_to_check: FeatureFlag) -> list[FeatureFlag]:"""Find all active flags that depend on the given flag via flag-type filter properties."""@@ -1328,26 +1344,38 @@ class FeatureFlagSerializer(if not request:return attrs- # Survey flags are exempt from evaluation tag requirements- # They are created automatically by the survey system and don't need manual tagging+ # Note: for creation_context, we use initial_data since it's metadata not part of the modelcreation_context = self.initial_data.get("creation_context") if hasattr(self, "initial_data") else None- if creation_context == "surveys":- return attrs- # Get the team to check if evaluation contexts are required# The context uses a lambda for lazy evaluationget_team = self.context.get("get_team")if not get_team:return attrsteam = get_team()- if not team or not team.require_evaluation_contexts:+ if not team:return attrs+ self._validate_evaluation_contexts_requirement(attrs, request, team, creation_context)+ self._validate_tags_requirement(attrs, team, creation_context)++ return attrs++ def _validate_evaluation_contexts_requirement(+ self, attrs: dict, request: Any, team: Team, creation_context: str | None+ ) -> None:+ """Enforce the team's "require evaluation contexts" setting."""+ # Survey flags are exempt from evaluation tag requirements+ # They are created automatically by the survey system and don't need manual tagging+ if creation_context == "surveys":+ return++ if not team.require_evaluation_contexts:+ return+if not self._is_evaluation_contexts_feature_enabled():- return attrs+ return- # Note: for creation_context, we use initial_data since it's metadata not part of the modelevaluation_contexts = attrs.get("evaluation_contexts")if request.method == "POST":@@ -1373,7 +1401,32 @@ class FeatureFlagSerializer("because this flag already has evaluation contexts and the team requires them.")- return attrs+ def _validate_tags_requirement(self, attrs: dict, team: Team, creation_context: str | None) -> None:+ """Enforce the team's "require tags" setting."""+ if creation_context in TAG_REQUIREMENT_EXEMPT_CREATION_CONTEXTS:+ return++ if not team_requires_flag_tags(team.id):+ return++ tags = attrs.get("tags")+ named_tags = normalize_tag_names([tag for tag in tags or [] if isinstance(tag, str)])++ # Branch on the instance rather than request.method. Products that write a flag as a side+ # effect of their own request - launching an experiment, saving an early access feature,+ # editing a product tour - drive this serializer with the real POST request that triggered+ # them, and those updates carry no tags. Reading POST as "create" would reject them.+ if self.instance is None:+ if not named_tags:+ raise serializers.ValidationError({"tags": REQUIRE_TAGS_ON_CREATE_ERROR})+ return++ # Only block emptying a flag that already has tags. Flags that predate the setting stay+ # editable, so turning it on doesn't freeze the existing untagged ones. Normalize what the+ # flag already carries too: a blank tag row is not a tag on the way in, so it must not read+ # as one on the way out.+ if tags is not None and not named_tags and normalize_tag_names(current_tag_names(self.instance)):+ raise serializers.ValidationError({"tags": REQUIRE_TAGS_ON_UPDATE_ERROR})def _validate_device_bucketing_with_persist_auth(self, attrs):"""Validate that persist across auth is not enabled with device ID bucketing"""@@ -3180,6 +3233,27 @@ class FeatureFlagViewSet(queryset = FeatureFlag.objects_including_soft_deleted.all()serializer_class = FeatureFlagSerializer+ def validate_bulk_tag_changes(self, objects: Sequence, tag_action: str, tags: list[str]) -> None:+ """Stop a bulk edit from stripping the last tag off a flag when the project requires one.++ Without this the flags list's bulk tag action defeats the setting in one click, since the+ bulk path writes TaggedItem rows directly and never reaches FeatureFlagSerializer.+ """+ if tag_action == "add" or not objects:+ return++ if not team_requires_flag_tags(self.team_id):+ return++ normalized_tags = normalize_tag_names(tags)+ # Normalize the resolved set: a flag left holding only a blank tag row keeps no real tag,+ # so the edit has to be rejected the same way an empty result is.+ if any(+ not normalize_tag_names(resolve_bulk_tags(current_tag_names(flag), tag_action, normalized_tags))+ for flag in objects+ ):+ raise serializers.ValidationError({"tags": REQUIRE_TAGS_ON_UPDATE_ERROR})+@extend_schema(request=FeatureFlagCreateRequestSchemaSerializer)def create(self, request, *args, **kwargs):return super().create(request, *args, **kwargs)diff --git a/products/feature_flags/backend/api/test/test_feature_flag_require_tags.py b/products/feature_flags/backend/api/test/test_feature_flag_require_tags.pynew file mode 100644index 000000000000..31a8579b21e2--- /dev/null+++ b/products/feature_flags/backend/api/test/test_feature_flag_require_tags.py@@ -0,0 +1,209 @@+from posthog.test.base import APIBaseTest++from parameterized import parameterized+from rest_framework import status+from rest_framework.test import APIRequestFactory++from posthog.models import Tag++from products.feature_flags.backend.api.feature_flag import TAG_REQUIREMENT_EXEMPT_CREATION_CONTEXTS+from products.feature_flags.backend.facade.api import update_flag+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig+++class TestFeatureFlagRequireTags(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/feature_flags/"++ def _require_tags(self, required: bool) -> None:+ TeamFeatureFlagPolicyConfig.objects.update_or_create(team=self.team, defaults={"require_tags": required})+ self.team.refresh_from_db()++ def _tag_flag(self, flag: FeatureFlag, name: str) -> None:+ tag, _ = Tag.objects.get_or_create(name=name, team_id=self.team.id)+ flag.tagged_items.create(tag_id=tag.id)++ def test_create_without_tags_is_allowed_when_not_required(self) -> None:+ self._require_tags(False)++ response = self.client.post(self.url, {"key": "untagged-flag"}, format="json")++ assert response.status_code == status.HTTP_201_CREATED++ def test_create_without_tags_is_rejected_when_required(self) -> None:+ self._require_tags(True)++ response = self.client.post(self.url, {"key": "untagged-flag"}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Add at least one tag" in response.json()["detail"]+ assert not FeatureFlag.objects.filter(key="untagged-flag", team=self.team).exists()++ def test_create_with_empty_tag_list_is_rejected_when_required(self) -> None:+ self._require_tags(True)++ response = self.client.post(self.url, {"key": "untagged-flag", "tags": []}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_create_with_tags_is_allowed_when_required(self) -> None:+ self._require_tags(True)++ response = self.client.post(self.url, {"key": "tagged-flag", "tags": ["billing"]}, format="json")++ assert response.status_code == status.HTTP_201_CREATED+ flag = FeatureFlag.objects.get(key="tagged-flag", team=self.team)+ assert list(flag.tagged_items.values_list("tag__name", flat=True)) == ["billing"]++ @parameterized.expand(sorted(TAG_REQUIREMENT_EXEMPT_CREATION_CONTEXTS))+ def test_flags_created_for_another_object_stay_exempt(self, creation_context: str) -> None:+ self._require_tags(True)++ response = self.client.post(+ self.url,+ {"key": f"{creation_context}-flag", "creation_context": creation_context},+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED++ def test_update_cannot_remove_the_last_tag_when_required(self) -> None:+ flag = FeatureFlag.objects.create(key="tagged-flag", team=self.team, created_by=self.user)+ self._tag_flag(flag, "billing")+ self._require_tags(True)++ response = self.client.patch(f"{self.url}{flag.id}/", {"tags": []}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Keep at least one tag" in response.json()["detail"]+ assert flag.tagged_items.count() == 1++ def test_update_can_swap_tags_when_required(self) -> None:+ flag = FeatureFlag.objects.create(key="tagged-flag", team=self.team, created_by=self.user)+ self._tag_flag(flag, "billing")+ self._require_tags(True)++ response = self.client.patch(f"{self.url}{flag.id}/", {"tags": ["growth"]}, format="json")++ assert response.status_code == status.HTTP_200_OK+ assert list(flag.tagged_items.values_list("tag__name", flat=True)) == ["growth"]++ def test_update_of_a_flag_that_predates_the_setting_is_allowed(self) -> None:+ flag = FeatureFlag.objects.create(key="legacy-flag", team=self.team, created_by=self.user)+ self._require_tags(True)++ response = self.client.patch(f"{self.url}{flag.id}/", {"name": "Renamed"}, format="json")++ assert response.status_code == status.HTTP_200_OK++ def test_update_driven_by_a_post_request_is_not_read_as_a_create(self) -> None:+ # Experiments, early access features, and product tours write a flag as a side effect of+ # their own POST, so the flag serializer sees a POST it must still treat as an update.+ flag = FeatureFlag.objects.create(key="experiment-flag", team=self.team, created_by=self.user)+ self._require_tags(True)+ request = APIRequestFactory().post("/")+ request.user = self.user++ updated = update_flag(flag, {"name": "Renamed"}, team=self.team, user=self.user, request=request)++ assert updated.name == "Renamed"++ def test_create_with_a_blank_tag_is_rejected_when_required(self) -> None:+ self._require_tags(True)++ response = self.client.post(self.url, {"key": "blank-tag-flag", "tags": [" "]}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_update_can_clear_tags_on_a_flag_whose_only_tag_is_blank(self) -> None:+ # A flag reaches this state through a create that carried a blank tag while the setting was+ # off. The person editing it sees no tag, so "keep at least one tag" would be a refusal they+ # cannot act on. The guard has to read what the flag holds the same way it reads the payload.+ flag = FeatureFlag.objects.create(key="blank-tag-only-flag", team=self.team, created_by=self.user)+ self._tag_flag(flag, "")+ self._require_tags(True)++ response = self.client.patch(f"{self.url}{flag.id}/", {"tags": []}, format="json")++ assert response.status_code == status.HTTP_200_OK++ @parameterized.expand([("set", []), ("set", [" "]), ("remove", ["billing"])])+ def test_bulk_update_cannot_strip_the_last_tag_when_required(self, tag_action: str, tags: list[str]) -> None:+ flag = FeatureFlag.objects.create(key="tagged-flag", team=self.team, created_by=self.user)+ self._tag_flag(flag, "billing")+ self._require_tags(True)++ response = self.client.post(+ f"{self.url}bulk_update_tags/",+ {"ids": [flag.id], "action": tag_action, "tags": tags},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert flag.tagged_items.count() == 1++ def test_bulk_update_reads_a_blank_existing_tag_as_no_tag(self) -> None:+ # A create that mixes a blank tag in with a real one writes both rows, so a flag can hold a+ # blank tag today. Removing the real tag leaves nothing a person can see, which is the state+ # the setting exists to prevent, so counting the blank row would let the edit through.+ flag = FeatureFlag.objects.create(key="blank-and-real-flag", team=self.team, created_by=self.user)+ self._tag_flag(flag, "billing")+ self._tag_flag(flag, "")+ self._require_tags(True)++ response = self.client.post(+ f"{self.url}bulk_update_tags/",+ {"ids": [flag.id], "action": "remove", "tags": ["billing"]},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "billing" in flag.tagged_items.values_list("tag__name", flat=True)++ def test_bulk_update_rejects_the_request_when_only_one_selected_flag_would_be_stripped(self) -> None:+ # A mixed selection is what exercises the any() in validate_bulk_tag_changes: with one flag+ # per request, checking every flag and checking only the first read the same.+ #+ # The flag that loses its last tag sits between two that keep one, and that placement is+ # load-bearing. Neither the viewset nor the model sets an ordering, so the flag the check+ # would reach first is whichever end the database returns. A keeper at both ends means a+ # check that stops after the first flag misses the violation either way.+ keeps_a_tag = FeatureFlag.objects.create(key="first-keeper-flag", team=self.team, created_by=self.user)+ self._tag_flag(keeps_a_tag, "billing")+ self._tag_flag(keeps_a_tag, "growth")+ loses_its_last = FeatureFlag.objects.create(key="one-tag-flag", team=self.team, created_by=self.user)+ self._tag_flag(loses_its_last, "billing")+ also_keeps_a_tag = FeatureFlag.objects.create(key="last-keeper-flag", team=self.team, created_by=self.user)+ self._tag_flag(also_keeps_a_tag, "billing")+ self._tag_flag(also_keeps_a_tag, "growth")+ self._require_tags(True)++ response = self.client.post(+ f"{self.url}bulk_update_tags/",+ {+ "ids": [keeps_a_tag.id, loses_its_last.id, also_keeps_a_tag.id],+ "action": "remove",+ "tags": ["billing"],+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ for flag in (keeps_a_tag, loses_its_last, also_keeps_a_tag):+ assert "billing" in flag.tagged_items.values_list("tag__name", flat=True)++ def test_bulk_update_can_still_swap_tags_when_required(self) -> None:+ flag = FeatureFlag.objects.create(key="tagged-flag", team=self.team, created_by=self.user)+ self._tag_flag(flag, "billing")+ self._require_tags(True)++ response = self.client.post(+ f"{self.url}bulk_update_tags/",+ {"ids": [flag.id], "action": "set", "tags": ["growth"]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert list(flag.tagged_items.values_list("tag__name", flat=True)) == ["growth"]diff --git a/products/feature_flags/backend/max_tools.py b/products/feature_flags/backend/max_tools.pyindex d23bb19891b8..9e906c1de620 100644--- a/products/feature_flags/backend/max_tools.py+++ b/products/feature_flags/backend/max_tools.py@@ -49,7 +49,8 @@ class FeatureFlagCreationSchema(BaseModel):)tags: list[str] = Field(default_factory=list,- description="Tags for organizing and categorizing the flag",+ description="Tags for organizing and categorizing the flag. Some projects require at least one "+ "tag on every new flag, and reject a create that carries none.",)variants: list[MultivariateVariant] | None = Field(default=None,diff --git a/products/feature_flags/backend/migrations/0016_teamfeatureflagpolicyconfig.py b/products/feature_flags/backend/migrations/0016_teamfeatureflagpolicyconfig.pynew file mode 100644index 000000000000..74983a2c8ab8--- /dev/null+++ b/products/feature_flags/backend/migrations/0016_teamfeatureflagpolicyconfig.py@@ -0,0 +1,31 @@+# Generated by Django 5.2.17 on 2026-08-26 22:06++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("feature_flags", "0015_clamp_rollout_percentages_over_100"),+ ("posthog", "1321_add_user_facet_settings"),+ ]++ operations = [+ migrations.CreateModel(+ name="TeamFeatureFlagPolicyConfig",+ fields=[+ (+ "team",+ models.OneToOneField(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ primary_key=True,+ related_name="+",+ serialize=False,+ to="posthog.team",+ ),+ ),+ ("require_tags", models.BooleanField(default=False)),+ ],+ ),+ ]diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txtindex a2e9cf6faa89..ee240fa25047 100644--- a/products/feature_flags/backend/migrations/max_migration.txt+++ b/products/feature_flags/backend/migrations/max_migration.txt@@ -1 +1 @@-0015_clamp_rollout_percentages_over_100+0016_teamfeatureflagpolicyconfigdiff --git a/products/feature_flags/backend/models/__init__.py b/products/feature_flags/backend/models/__init__.pyindex 09b8ba14bddc..44a9dc1b9423 100644--- a/products/feature_flags/backend/models/__init__.py+++ b/products/feature_flags/backend/models/__init__.py@@ -2,6 +2,7 @@ from .evaluation_context import EvaluationContext, FeatureFlagEvaluationContext,from .feature_flag import FeatureFlag, FeatureFlagDashboards, FeatureFlagHashKeyOverride, FeatureFlagOverridefrom .scheduled_change import ScheduledChangefrom .team_feature_flag_defaults_config import TeamFeatureFlagDefaultsConfig+from .team_feature_flag_policy_config import TeamFeatureFlagPolicyConfigfrom .team_feature_flags_config import TeamFeatureFlagsConfig__all__ = [@@ -13,6 +14,7 @@ __all__ = ["FeatureFlagOverride","ScheduledChange","TeamFeatureFlagDefaultsConfig",+ "TeamFeatureFlagPolicyConfig","TeamFeatureFlagsConfig","TeamDefaultEvaluationContext",]diff --git a/products/feature_flags/backend/models/team_feature_flag_policy_config.py b/products/feature_flags/backend/models/team_feature_flag_policy_config.pynew file mode 100644index 000000000000..8627fee3a126--- /dev/null+++ b/products/feature_flags/backend/models/team_feature_flag_policy_config.py@@ -0,0 +1,49 @@+import logging++from django.db import models++from posthog.models.team.extensions import register_team_extension_signal++logger = logging.getLogger(__name__)+++class TeamFeatureFlagPolicyConfig(models.Model):+ """Customer-editable rules that guard how a team's members create flags.++ Distinct from TeamFeatureFlagsConfig, which holds staff-only rollout switches and is never+ exposed to customers. This one is reachable by project admins as `feature_flag_policy_config`+ on the team/project API.++ These rules are bookkeeping, and they do not hold on every write path. The exemptions are+ declared by the caller, and a path that builds a serializer context without `get_team` skips+ the rules entirely: the organization-level flag copy and the approvals apply path both do.+ """++ # db_constraint=False: a real FK constraint would take a SHARE ROW EXCLUSIVE+ # lock on posthog_team (a hot table) while migrating.+ # related_name="+": the relation crosses a product boundary, so it must not add a reverse+ # accessor to Team. Readers come in through `Team.feature_flag_policy_config` instead.+ team = models.OneToOneField(+ "posthog.Team", on_delete=models.CASCADE, primary_key=True, db_constraint=False, related_name="+"+ )++ # Blocks creating a flag with no tags, and blocks removing the last tag from a flag that has+ # one. Only applies to flags a person creates directly. Flags generated to back a survey,+ # experiment, early access feature, product tour, or web experiment are exempt, because those+ # forms have no tag input and would otherwise dead-end.+ require_tags = models.BooleanField(default=False)+++register_team_extension_signal(TeamFeatureFlagPolicyConfig, logger=logger)+++def team_requires_flag_tags(team_id: int) -> bool:+ """Whether this team requires tags on flags.++ Queries the row rather than going through ``get_or_create_team_extension`` so a read on the+ flag-write path does not create the row for every team that never touched the setting.+ """+ return (+ TeamFeatureFlagPolicyConfig.objects.filter(team_id=team_id).values_list("require_tags", flat=True).first()+ is True+ )diff --git a/products/feature_flags/backend/test/test_team_feature_flag_policy_config.py b/products/feature_flags/backend/test/test_team_feature_flag_policy_config.pynew file mode 100644index 000000000000..4a760ba1feb6--- /dev/null+++ b/products/feature_flags/backend/test/test_team_feature_flag_policy_config.py@@ -0,0 +1,51 @@+from posthog.test.base import APIBaseTest++from rest_framework import status++from posthog.models import OrganizationMembership++from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig+++class TestTeamFeatureFlagPolicyConfig(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.url = f"/api/environments/{self.team.id}/"++ def test_defaults_to_tags_not_required(self) -> None:+ response = self.client.get(self.url)++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["feature_flag_policy_config"] == {"require_tags": False}++ def test_admin_can_toggle_require_tags(self) -> None:+ response = self.client.patch(self.url, {"feature_flag_policy_config": {"require_tags": True}})++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["feature_flag_policy_config"]["require_tags"] is True+ assert TeamFeatureFlagPolicyConfig.objects.get(team=self.team).require_tags is True++ response = self.client.patch(self.url, {"feature_flag_policy_config": {"require_tags": False}})++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["feature_flag_policy_config"]["require_tags"] is False+ assert TeamFeatureFlagPolicyConfig.objects.get(team=self.team).require_tags is False++ def test_member_cannot_toggle_require_tags(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ response = self.client.patch(self.url, {"feature_flag_policy_config": {"require_tags": True}})++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert TeamFeatureFlagPolicyConfig.objects.get(team=self.team).require_tags is False++ def test_patching_other_team_fields_leaves_require_tags_alone(self) -> None:+ self.client.patch(self.url, {"feature_flag_policy_config": {"require_tags": True}})++ response = self.client.patch(self.url, {"name": "renamed team"})++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["feature_flag_policy_config"]["require_tags"] is Truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6eab38df784a..d29b7ef9d45a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -64738,6 +64738,11 @@ export namespace Schemas {email_tracking_consent_mode?: EmailTrackingConsentModeEnum;}+ export interface TeamFeatureFlagPolicyConfig {+ /** When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag. */+ require_tags?: boolean;+ }+/*** A project and its settings, including the settings that live on its passthrough Team.*@@ -65546,6 +65551,7 @@ export namespace Schemas {marketing_analytics_config?: TeamMarketingAnalyticsConfig;customer_analytics_config?: TeamCustomerAnalyticsConfig;workflows_config?: TeamWorkflowsConfig;+ feature_flag_policy_config?: TeamFeatureFlagPolicyConfig;base_currency?: BaseCurrencyEnum;/*** Enables capturing clicks that had no effect (rage-click detection).@@ -67703,6 +67709,7 @@ export namespace Schemas {* @nullable*/require_evaluation_contexts?: boolean | null;+ feature_flag_policy_config?: TeamFeatureFlagPolicyConfig;/** @nullable */capture_dead_clicks?: boolean | null;/**@@ -69948,6 +69955,7 @@ export namespace Schemas {marketing_analytics_config?: TeamMarketingAnalyticsConfig;customer_analytics_config?: TeamCustomerAnalyticsConfig;workflows_config?: TeamWorkflowsConfig;+ feature_flag_policy_config?: TeamFeatureFlagPolicyConfig;base_currency?: BaseCurrencyEnum;/*** Enables capturing clicks that had no effect (rage-click detection).@@ -85699,6 +85707,7 @@ export namespace Schemas {* @nullable*/require_evaluation_contexts?: boolean | null;+ feature_flag_policy_config?: TeamFeatureFlagPolicyConfig;/** @nullable */capture_dead_clicks?: boolean | null;/**diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex 9dd5eef922f0..36d00b88a7ec 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -2466,6 +2466,16 @@ export const OrganizationsProjectsPartialUpdateBody = () => zod),}).optional(),+ feature_flag_policy_config: zod+ .object({+ require_tags: zod+ .boolean()+ .optional()+ .describe(+ 'When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag.'+ ),+ })+ .optional(),base_currency: zod.enum(['AED',diff --git a/services/mcp/src/tools/generated/core.ts b/services/mcp/src/tools/generated/core.tsindex e5ee55be871f..cf75e632c51d 100644--- a/services/mcp/src/tools/generated/core.ts+++ b/services/mcp/src/tools/generated/core.ts@@ -353,6 +353,9 @@ const projectSettingsUpdate = (): ToolBase<if (params.workflows_config !== undefined) {body['workflows_config'] = params.workflows_config}+ if (params.feature_flag_policy_config !== undefined) {+ body['feature_flag_policy_config'] = params.feature_flag_policy_config+ }if (params.base_currency !== undefined) {body['base_currency'] = params.base_currency}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.jsonindex b391b2ddbc2a..ac6fdd78aa69 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json@@ -383,6 +383,15 @@}]},+ "feature_flag_policy_config": {+ "properties": {+ "require_tags": {+ "description": "When enabled, a new feature flag needs at least one tag, and a tagged flag cannot lose its last one. A create that declares it comes from a survey, experiment, early access feature, product tour, or web experiment is exempt, because those forms have no tag input. The caller sets that declaration, so a flag can still be created without a tag.",+ "type": "boolean"+ }+ },+ "type": "object"+ },"flags_persistence_default": {"anyOf": [{