К основному содержанию
скилл CX Codex

launchdarkly-flag-cleanup — скилл для Claude Code: установка и обзор

Безопасно удаляет фиче-флаги LaunchDarkly из кодовой базы после завершения раскатки. Скилл проверяет готовность через MCP и оставляет только активную ветку кода.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add launchdarkly/ai-tooling --skill launchdarkly-flag-cleanup -a claude-code
Открыть на GitHub

Что делает launchdarkly-flag-cleanup

Скилл автоматизирует очистку кодовой базы от отработавших фиче-флагов LaunchDarkly. Сначала агент ищет все упоминания ключа флага в коде, вызовах SDK, тестах и файлах конфигурации. Затем инструмент check-removal-readiness параллельно запрашивает статус таргетинга, зависимости и окружения в LaunchDarkly. Если значения в критических средах расходятся, процесс останавливается. Это защищает от поломки продакшена.

Перед правками агент показывает детальный план: итоговое значение флага, список файлов и планируемые изменения. Удаление начинается только после явного подтверждения пользователя. Агент оставляет ветку с победившей вариацией, вырезает мёртвый код и убирает ненужные импорты. Рефакторить соседний код правилами скилла прямо запрещено.

Для работы требуется настроенный удалённый LaunchDarkly MCP-сервер с инструментами check-removal-readiness и get-flag. Без подключённого MCP-сервера скилл не сможет запросить конфигурацию флагов и откажется менять код. После правок агент помогает оформить pull request по готовому шаблону и проверяет проект тестами и сборкой.

Какие задачи решает

  • удалить отработавший фиче-флаг LaunchDarkly из кодовой базы
  • проверить готовность флага к удалению через MCP
  • захардкодить победившую вариацию и очистить мёртвые ветки кода
  • составить структурированный pull request с отчётом о проверках

Примеры запросов агенту

  • Удали фиче-флаг new-checkout-flow из кодовой базы
  • Проверь готовность флага beta-dashboard к удалению и захардкодь победившую вариацию
  • Очисти код от флага auth-v2 и подготовь pull request

Как установить launchdarkly-flag-cleanup

1Через Skills CLI (Vercel)

npx skills add launchdarkly/ai-tooling --skill launchdarkly-flag-cleanup -a claude-code

2Вручную: положить файлы

~/.claude/skills/launchdarkly-flag-cleanup/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/launchdarkly-flag-cleanup/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о launchdarkly-flag-cleanup

Как установить launchdarkly-flag-cleanup в Claude Code?

Выполните команду npx skills add launchdarkly/ai-tooling --skill launchdarkly-flag-cleanup -a claude-code в терминале.

Что делает launchdarkly-flag-cleanup?

Скилл проверяет безопасность удаления флага через LaunchDarkly MCP, определяет нужное значение для подстановки, вырезает вызовы SDK с мёртвыми ветками кода и готовит pull request.

Что нужно настроить перед запуском скилла?

В окружении должен быть подключён удалённый LaunchDarkly MCP-сервер с доступными инструментами check-removal-readiness и get-flag. Без них скилл не сможет запросить состояние флага.

Исходный текст

SKILL.md · Apache-2.0
---
name: launchdarkly-flag-cleanup
description: "Safely remove a feature flag from code while preserving production behavior. Use when the user wants to remove a flag from code, delete flag references, or create a PR that hardcodes the winning variation after a rollout is complete."
license: Apache-2.0
compatibility: Requires the remotely hosted LaunchDarkly MCP server
metadata:
  author: launchdarkly
  version: "1.0.0-experimental"
---

# LaunchDarkly Flag Cleanup

You're using a skill that will guide you through safely removing a feature flag from a codebase while preserving production behavior. Your job is to explore the codebase to understand how the flag is used, query LaunchDarkly to determine the correct forward value, remove the flag code cleanly, and verify the result.

If you haven't already identified which flag to clean up, use the [flag discovery skill](../launchdarkly-flag-discovery/SKILL.md) first to audit the landscape and find candidates.

## Prerequisites

This skill requires the remotely hosted LaunchDarkly MCP server to be configured in your environment.

**Required MCP tools:**
- `check-removal-readiness`: detailed safety check (orchestrates flag config, cross-env status, dependencies, code references, and expiring targets in parallel)
- `get-flag`: fetch flag configuration for a specific environment

**Optional MCP tools:**
- `archive-flag`: archive the flag in LaunchDarkly after code removal
- `delete-flag`: permanently delete the flag (irreversible, prefer archive)

## Core Principles

1. **Safety First**: Always preserve current production behavior.
2. **LaunchDarkly as Source of Truth**: Never guess the forward value. Query the actual configuration.
3. **Follow Conventions**: Respect existing code style and structure.
4. **Minimal Change**: Only remove flag-related code. No unrelated refactors.

## Workflow

### Step 1: Explore the Codebase

Before touching LaunchDarkly or removing code, understand how this flag is used in the codebase.

1. **Find all references to the flag key.** Search for the flag key string (e.g., `new-checkout-flow`) across the codebase. Check for:
   - Direct SDK evaluation calls (`variation()`, `boolVariation()`, `useFlags()`, etc.)
   - Constants/enums that reference the key
   - Wrapper/service patterns that abstract the SDK
   - Configuration files, tests, and documentation
   - See [SDK Patterns](references/sdk-patterns.md) for the full list of patterns by language

2. **Understand the branching.** For each reference, identify:
   - What code runs when the flag is `true` (or variation A)?
   - What code runs when the flag is `false` (or variation B)?
   - Are there side effects, early returns, or nested conditions?

3. **Note the scope.** How many files, components, or modules does this flag touch? A flag used in one `if` block is simpler than one threaded through multiple layers.

### Step 2: Run the Removal Readiness Check

Use `check-removal-readiness` to get a detailed safety assessment. This single tool call orchestrates multiple checks in parallel:
- Flag configuration and targeting state
- Cross-environment status
- Dependent flags (prerequisites)
- Expiring targets
- Code reference statistics

The tool returns a readiness verdict:

**`safe`**: No blockers or warnings. Proceed with removal.

**`caution`**: No hard blockers but warnings exist (e.g., code references in other repos, expiring targets scheduled, flag marked as permanent). Present warnings and let the user decide.

**`blocked`**: Hard blockers prevent safe removal (e.g., dependent flags, actively receiving requests, targeting is on with active rules). Present blockers: the user must resolve them first.

### Step 3: Determine the Forward Value

Use `get-flag` to fetch the flag configuration in each critical environment. The **forward value** is the variation that replaces the flag in code.

| Scenario | Forward Value |
|----------|---------------|
| All critical envs ON, same fallthrough, no rules/targets | Use `fallthrough.variation` |
| All critical envs OFF, same offVariation | Use `offVariation` |
| Critical envs differ in ON/OFF state | **NOT SAFE**: stop and inform the user |
| Critical envs serve different variations | **NOT SAFE**: stop and inform the user |

### Step 4: Present the Cleanup Plan

Before modifying any code, present a summary to the user and wait for confirmation:

1. **The forward value** — which variation will be hardcoded and why (based on the flag's current state).
2. **All code references found** — file paths and line numbers from Step 1.
3. **Planned changes** — for each reference, describe what will be removed and what will be kept.
4. **Readiness verdict** — the result from `check-removal-readiness` (safe, caution, or blocked) and any warnings.
5. **LaunchDarkly action** — confirm the flag will be archived after code changes are complete.

**Do not proceed with code changes until the user explicitly confirms.**

### Step 5: Remove the Flag from Code

Now execute the removal using what you learned in Step 1.

1. **Replace flag evaluations with the forward value.**
   - Preserve the code branch matching the forward value
   - Remove the dead branch entirely
   - If the flag value was assigned to a variable, replace the variable with the literal value or inline it

2. **Clean up dead code.**
   - Remove imports, constants, and type definitions that only existed for the flag
   - Remove functions, components, or files that only existed for the dead branch
   - Check for orphaned exports, hooks, helpers, styles, and test files
   - If the repo uses an unused-export tool (Knip, ts-prune, lint rules), run it and remove any flag-related orphans

3. **Don't over-clean.**
   - Only remove code directly related to the flag
   - Don't refactor, optimize, or "improve" surrounding code
   - Don't change formatting or style of untouched code

**Example transformation (boolean flag, forward value = `true`):**

```typescript
// Before
const showNewCheckout = await ldClient.variation('new-checkout-flow', user, false);
if (showNewCheckout) {
  return renderNewCheckout();
} else {
  return renderOldCheckout();
}

// After
return renderNewCheckout();
```

### Step 6: Create Pull Request

Use the template in [references/pr-template.md](references/pr-template.md) for a structured PR description. The PR should clearly communicate:
- What flag was removed and why
- What the forward value is and why it's correct
- The readiness assessment results (from `check-removal-readiness`)
- What code was removed and what behavior is preserved
- Whether other repos still reference this flag

### Step 7: Verify

Before considering the job done:

1. **Code compiles and lints.** Run the project's build and lint steps.
2. **Tests pass.** If the flag was used in tests, the tests should be updated to reflect the hardcoded behavior.
3. **No remaining references.** Search the codebase one more time for the flag key to make sure nothing was missed.
4. **PR is complete.** The description covers the readiness assessment, forward value rationale, and any cross-repo coordination needed.

## Edge Cases

| Situation | Action |
|-----------|--------|
| Flag not found in LaunchDarkly | Inform user, check for typos in the key |
| Flag already archived | Ask if code cleanup is still needed (flag is gone from LD but code may still reference it) |
| Multiple SDK patterns in codebase | Search all patterns: `variation()`, `boolVariation()`, `variationDetail()`, `allFlags()`, `useFlags()`, plus any wrappers |
| Dynamic flag keys (`flag-${id}`) | Warn that automated removal may be incomplete: manual review required |
| Different default values in code vs LD | Flag as inconsistency in the PR description |
| Orphaned exports/files remain after removal | Run unused-export checks and remove dead files |

## What NOT to Do

- Don't change code unrelated to flag cleanup.
- Don't refactor or optimize beyond flag removal.
- Don't remove flags still being actively rolled out.
- Don't guess the forward value: always query LaunchDarkly.

## After Cleanup

Once the PR is merged and deployed:
1. **Archive the flag in LaunchDarkly** using `archive-flag`. Archival is reversible; deletion is not. Always archive first.
2. **Notify other teams** if `check-removal-readiness` reported code references in other repositories.
3. **If the flag had targeting changes pending,** they can be ignored: the flag is being removed.

## References

- [PR Template](references/pr-template.md): Structured PR description for flag removal
- [SDK Patterns](references/sdk-patterns.md): Flag evaluation patterns by language/framework
- [Flag Discovery](../launchdarkly-flag-discovery/SKILL.md): Find cleanup candidates before using this skill
- [Flag Targeting](../launchdarkly-flag-targeting/SKILL.md): If you need to change targeting instead of removing

© launchdarkly · Apache-2.0 · launchdarkly/ai-tooling

Похожие скиллы

Всё по теме «Код-ревью и рефакторинг» →
feature-flags devops-skills Скилл для ИИ-агента, который помогает внедрять фиче-флаги: постепенная раскатка, A/B-тесты, kill switch. Пригодится, когда релиз нужно отделить от деплоя. CX Codex +1 329установок cleaning-up-stale-feature-flags PostHog Находит устаревшие фича-флаги в проекте PostHog и убирает код, который их проверяет. Пригодится, когда флагов накопилось много и непонятно, какие уже можно удалить. CX Codex +1 434установок codebase-cleanup Seth Hobson Плагин для Claude, Codex и Cursor, который берёт на себя обновление зависимостей и рефакторинг кода. Пригодится, когда в проекте накопился технический долг. CX Codex ★ 41 729звёзд репо branch-cleanup davila7 Слэш-команда для Claude, которая находит слитые и устаревшие ветки, проверяет их перед удалением и наводит порядок в локальном и удалённом репозитории. 342установок deploy-checklist официальный anthropics Собирает чек-лист перед релизом: проверки CI, ревью, миграций, флагов, выката и отката. Пригодится перед изменениями в продакшене. CX Codex +1 5 700установок github-sensitive-data-cleanup daymade Ищет и удаляет секреты, токены и приватные данные из истории Git, а затем безопасно пушит изменения в GitHub. Пригодится при случайной утечке ключей в публичный репозиторий. CX Codex +1 353установок

Из того же набора29

launchdarkly-flag-discovery Проводит аудит фиче-флагов LaunchDarkly, находит устаревшие тумблеры и проверяет безопасность их удаления. Пригодится для устранения долга по флагам в проекте. CX Codex +1 4 200установок launchdarkly-flag-targeting Скилл для управления таргетингом фича-флагов LaunchDarkly: включение, процентные раскатки, правила и отдельные пользователи. CX Codex +1 4 100установок launchdarkly-flag-create Проводит агента по шагам: изучить, как флаги уже используются в проекте, создать новый в LaunchDarkly и вписать проверку в код по существующим паттернам. CX Codex +1 4 100установок launchdarkly-metric-instrument Добавляет вызовы track() для метрик LaunchDarkly в клиентский или серверный код и проверяет отправку событий. CX Codex +1 3 200установок launchdarkly-metric-create Проведёт от выбора типа метрики до её создания в LaunchDarkly: сначала наладит события, потом заведёт метрику и проверит результат. CX Codex +1 3 200установок launchdarkly-metric-choose Помогает выбрать метрики для эксперимента, guarded rollout или release policy в LaunchDarkly и показывает, что уже подцепится автоматически. CX Codex +1 3 200установок aiconfig-variations Устаревший скилл-редирект: сам ничего не делает, только отправляет к актуальному скиллу configs-variations. Нужен, если в ваших скриптах или промптах осталось старое имя. CX Codex +1 2 800установок aiconfig-create Устаревший скилл-переадресация для старых ссылок на aiconfig-create. Он направляет к актуальному скиллу configs-create. CX Codex +1 2 800установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой