Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计异常

feature-flags特征标志

Agent Skill

用于辅助云资源、部署、容器、基础设施和运维自动化任务。它适合让 Agent 检查配置、整理部署步骤、分析资源状态、生成排障思路或辅助云服务接入。使用时需要明确目标环境、账号权限、区域和资源组,区分本地测试与生产操作;涉及删除资源、重启服务、修改网络或权限配置时,应先确认影响范围。

总安装

734

周安装

30

GitHub Stars

18

下载量

238
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:feature-flags(特征标志)
来源仓库:https://github.com/bagelhole/devops-security-agent-skills
仓库路径:skills/feature-flags
安装命令:
npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill feature-flags
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill feature-flags

简介

用于控制功能发布节奏,支持渐进式 rollout、A/B 测试与运行时配置切换。

  • 适合实现金丝雀发布、实验性功能隔离及生产环境紧急禁用开关。
  • 可集成主流特征标记服务或自建方案,灵活适配不同技术栈。
  • 需在前端/后端代码中埋点调用,并确保配置变更具备原子性与一致性。
  • 操作时应记录变更历史,便于追溯问题并满足审计合规要求。

SKILL.md

Feature Flags

Control feature releases and enable progressive rollout with feature flag systems.

When to Use This Skill

Use this skill when:

  • Implementing gradual feature rollouts
  • Enabling trunk-based development
  • Running A/B tests and experiments
  • Managing feature lifecycles
  • Implementing kill switches for production

Prerequisites

  • Application code access
  • Feature flag service or self-hosted solution
  • Basic understanding of deployment patterns

Feature Flag Types

TypePurposeExample
ReleaseControl feature visibilityNew checkout flow
ExperimentA/B testingButton color test
OpsRuntime configurationRate limiting
PermissionUser access controlPremium features
Kill SwitchEmergency disableThird-party integration

LaunchDarkly

SDK Setup (Node.js)

const LaunchDarkly = require('launchdarkly-node-server-sdk');

const client = LaunchDarkly.init(process.env.LAUNCHDARKLY_SDK_KEY);

await client.waitForInitialization();

// Evaluate flag
const user = {
  key: 'user-123',
  email: 'user@example.com',
  custom: {
    plan: 'premium',
    company: 'acme'
  }
};

const showNewFeature = await client.variation('new-checkout', user, false);

if (showNewFeature) {
  // New feature code
} else {
  // Existing code
}

React SDK

import { withLDProvider, useFlags, useLDClient } from 'launchdarkly-react-client-sdk';

// Provider setup
export default withLDProvider({
  clientSideID: 'your-client-side-id',
  user: {
    key: 'user-123',
    email: 'user@example.com'
  }
})(App);

// Using flags in component
function FeatureComponent() {
  const { newCheckout, experimentVariant } = useFlags();
  const ldClient = useLDClient();

  // Track events
  const handleClick = () => {
    ldClient.track('checkout-started');
  };

  if (newCheckout) {
    return <NewCheckout onClick={handleClick} />;
  }
  return <OldCheckout onClick={handleClick} />;
}

Targeting Rules

# LaunchDarkly targeting configuration
flag: new-checkout
targeting:
  # Individual users
  targets:
    - variation: true
      values: ['user-123', 'user-456']

  # Rules
  rules:
    # Beta users
    - variation: true
      clauses:
        - attribute: email
          op: endsWith
          values: ['@company.com']

    # Premium plan
    - variation: true
      clauses:
        - attribute: plan
          op: in
          values: ['premium', 'enterprise']

    # Percentage rollout
    - variation: true
      rollout:
        variations:
          - variation: true
            weight: 20000  # 20%
          - variation: false
            weight: 80000  # 80%

  # Default
  fallthrough:
    variation: false

Unleash

Server Setup

# docker-compose.yml
version: '3.8'

services:
  unleash:
    image: unleashorg/unleash-server:latest
    ports:
      - "4242:4242"
    environment:
      - DATABASE_URL=postgres://postgres:password@db/unleash
      - DATABASE_SSL=false
    depends_on:
      - db

  db:
    image: postgres:15
    environment:
      - POSTGRES_PASSWORD=password
      - POSTGRES_DB=unleash
    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  postgres-data:

SDK Setup (Node.js)

const { initialize } = require('unleash-client');

const unleash = initialize({
  url: 'http://localhost:4242/api',
  appName: 'my-app',
  customHeaders: {
    Authorization: 'your-api-token'
  }
});

unleash.on('ready', () => {
  // Check feature
  const isEnabled = unleash.isEnabled('new-checkout');

  // With context
  const context = {
    userId: 'user-123',
    properties: {
      plan: 'premium'
    }
  };

  const isEnabledForUser = unleash.isEnabled('new-checkout', context);

  // Get variant
  const variant = unleash.getVariant('experiment-flag', context);
  console.log(variant.name); // 'control' or 'treatment'
});

Activation Strategies

# Standard strategies
strategies:
  - name: default
    # On/off for everyone

  - name: userWithId
    parameters:
      userIds: 'user-1,user-2,user-3'

  - name: gradualRolloutUserId
    parameters:
      percentage: 25
      groupId: 'new-feature'

  - name: gradualRolloutRandom
    parameters:
      percentage: 50

  - name: flexibleRollout
    parameters:
      rollout: 30
      stickiness: userId
      groupId: 'checkout-exp'

Custom Implementation

Database-Backed Flags

# models.py
from django.db import models

class FeatureFlag(models.Model):
    name = models.CharField(max_length=100, unique=True)
    enabled = models.BooleanField(default=False)
    rollout_percentage = models.IntegerField(default=0)
    allowed_users = models.JSONField(default=list)
    rules = models.JSONField(default=dict)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

# service.py
import hashlib

class FeatureFlagService:
    def __init__(self):
        self._cache = {}

    def is_enabled(self, flag_name, user_id=None, context=None):
        flag = self._get_flag(flag_name)

        if not flag or not flag.enabled:
            return False

        # Check user allowlist
        if user_id and user_id in flag.allowed_users:
            return True

        # Check rules
        if context and self._evaluate_rules(flag.rules, context):
            return True

        # Check percentage rollout
        if flag.rollout_percentage > 0 and user_id:
            return self._is_in_rollout(flag_name, user_id, flag.rollout_percentage)

        return flag.rollout_percentage == 100

    def _is_in_rollout(self, flag_name, user_id, percentage):
        hash_input = f"{flag_name}:{user_id}"
        hash_value = int(hashlib.md5(hash_input.encode()).hexdigest(), 16)
        return (hash_value % 100) < percentage

    def _evaluate_rules(self, rules, context):
        for rule in rules.get('rules', []):
            if self._evaluate_rule(rule, context):
                return True
        return False

Redis-Backed Flags

import redis
import json

class RedisFeatureFlags:
    def __init__(self, redis_url):
        self.redis = redis.from_url(redis_url)
        self.prefix = 'feature_flag:'

    def set_flag(self, name, config):
        key = f"{self.prefix}{name}"
        self.redis.set(key, json.dumps(config))

    def is_enabled(self, name, user_id=None):
        key = f"{self.prefix}{name}"
        data = self.redis.get(key)

        if not data:
            return False

        config = json.loads(data)

        if not config.get('enabled', False):
            return False

        # User allowlist
        if user_id in config.get('users', []):
            return True

        # Percentage rollout
        percentage = config.get('percentage', 0)
        if percentage == 100:
            return True

        if percentage > 0 and user_id:
            return self._hash_user(name, user_id) < percentage

        return False

    def _hash_user(self, flag, user_id):
        import hashlib
        hash_input = f"{flag}:{user_id}"
        return int(hashlib.sha256(hash_input.encode()).hexdigest(), 16) % 100

Testing with Feature Flags

Unit Testing

// Jest mocking
jest.mock('launchdarkly-node-server-sdk', () => ({
  init: jest.fn(() => ({
    waitForInitialization: jest.fn().mockResolvedValue(undefined),
    variation: jest.fn()
  }))
}));

describe('Checkout', () => {
  it('shows new checkout when flag enabled', async () => {
    const ldClient = require('launchdarkly-node-server-sdk').init();
    ldClient.variation.mockResolvedValue(true);

    const result = await renderCheckout(user);
    expect(result).toContain('NewCheckout');
  });

  it('shows old checkout when flag disabled', async () => {
    const ldClient = require('launchdarkly-node-server-sdk').init();
    ldClient.variation.mockResolvedValue(false);

    const result = await renderCheckout(user);
    expect(result).toContain('OldCheckout');
  });
});

Integration Testing

# pytest fixtures
import pytest

@pytest.fixture
def feature_flags():
    """Provide controllable feature flags for testing."""
    flags = {}

    class TestFlags:
        def set(self, name, value):
            flags[name] = value

        def is_enabled(self, name, **kwargs):
            return flags.get(name, False)

    return TestFlags()

def test_new_checkout(feature_flags):
    feature_flags.set('new-checkout', True)

    response = client.get('/checkout')
    assert 'new-checkout-form' in response.content

Monitoring and Analytics

Flag Usage Tracking

// Track flag evaluations
const flagMetrics = {
  evaluations: new Map(),

  track(flagName, variation, user) {
    const key = `${flagName}:${variation}`;
    const count = this.evaluations.get(key) || 0;
    this.evaluations.set(key, count + 1);

    // Send to analytics
    analytics.track('feature_flag_evaluated', {
      flag: flagName,
      variation: variation,
      userId: user.key
    });
  }
};

Stale Flag Detection

from datetime import datetime, timedelta

def detect_stale_flags():
    """Find flags that haven't been evaluated recently."""
    stale_threshold = timedelta(days=30)
    now = datetime.utcnow()

    stale_flags = []
    for flag in FeatureFlag.objects.all():
        if flag.last_evaluated:
            age = now - flag.last_evaluated
            if age > stale_threshold:
                stale_flags.append({
                    'name': flag.name,
                    'last_evaluated': flag.last_evaluated,
                    'age_days': age.days
                })

    return stale_flags

Common Issues

Issue: Inconsistent Flag Evaluation

Problem: Same user sees different variations Solution: Use consistent hashing, check caching strategy

Issue: Flag Debt Accumulation

Problem: Too many old flags in codebase Solution: Implement flag lifecycle, regular cleanup sprints

Issue: Performance Impact

Problem: Flag evaluation slowing requests Solution: Use local caching, batch evaluations

Best Practices

  • Use consistent naming conventions
  • Document flag purpose and owner
  • Set expiration dates for temporary flags
  • Implement flag lifecycle management
  • Use gradual rollouts (not 0→100)
  • Monitor flag evaluation metrics
  • Clean up old flags regularly
  • Test both variations in CI

Related Skills

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

32.3%
按下载量换算77

Claude

29.66%
按下载量换算71

Cursor

18.21%
按下载量换算43

Gemini CLI

10.24%
按下载量换算24

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

未通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills