К основному содержанию
субагент CX Codex

code-simplifier · nicknisi — субагент для Claude Code

Субагент code-simplifier упрощает логику, убирает дублирование и лишние проверки, не ломая публичные интерфейсы и поведение кода. Пригодится при наведении порядка после генерации ИИ.

MIT ★ 114 обновлён 2026-08-11

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add nicknisi/claude-plugins
/plugin install essentials@nicknisi
Открыть на GitHub

Что делает code-simplifier

Субагент работает на модели Opus и использует стандартный набор инструментов: Read, Edit, Grep, Glob и Bash. Он находит сложную логику, разбивает громоздкие функции на небольшие части, заменяет вложенные условия ранними возвратами и вычищает мёртвый код.

Отдельный приоритет субагента — удаление следов шаблонной генерации ИИ. Он убирает лишние try/catch-блоки на доверенных путях, неуместные приведения к типу any и избыточные комментарии, которые не соответствуют стилю проекта.

Публичные сигнатуры методов, внешние контракты и порядок побочных эффектов остаются нетронутыми. Любые изменения внешнего API субагент выполняет только после прямого разрешения разработчика.

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

  • убрать глубокие вложенные ветвления с помощью ранних возвратов
  • удалить следы машинной генерации и приведения к типу any
  • устранить дублирование логики без изменений во внешнем поведении
  • разбить слишком крупные функции на небольшие методы

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

  • Упрости функцию расчёта скидки в orders.ts через code-simplifier, сохранив её поведение
  • Проверь модуль auth.ts с помощью code-simplifier и убери повторы кода
  • Наведи порядок в именах переменных и типах в client.ts через code-simplifier

Как установить code-simplifier

1Через маркетплейс плагинов

/plugin marketplace add nicknisi/claude-plugins
/plugin install essentials@nicknisi

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

.claude/agents/code-simplifier.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

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

Вопросы о code-simplifier

Как установить code-simplifier в Claude Code?

Добавьте каталог плагинов командой /plugin marketplace add nicknisi/claude-plugins, затем установите пакет с помощью /plugin install essentials@nicknisi. Также субагента можно сохранить в .claude/agents/code-simplifier.md.

Меняет ли субагент публичный интерфейс кода?

Нет, субагент обязан сохранять сигнатуры методов, типы возвращаемых значений и поведение внешнего API. Если изменение интерфейса необходимо для чистоты кода, агент сначала спросит разрешение.

Какую модель и инструменты использует code-simplifier?

Субагент настроен на модель opus и обращается к инструментам Read, Edit, Grep, Glob и Bash.

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

code-simplifier.md · MIT
---
name: code-simplifier
description: Use this agent when you need to refactor code to improve readability, reduce complexity, or enhance maintainability without altering functionality. This includes simplifying complex logic, removing redundancy, improving naming, extracting methods, reducing nesting, and applying clean code principles. The agent preserves all public APIs and external behavior unless explicitly authorized to change them.
tools: Read, Edit, Grep, Glob, Bash
color: green
model: opus
---

## Usage Examples

<example>
Context: The user wants to simplify a complex function with nested conditionals.
user: "This function is hard to read, can you simplify it?"
assistant: "I'll use the code-simplifier agent to refactor this function while preserving its behavior."
<commentary>
The user is asking for code simplification, so use the code-simplifier agent to improve readability without changing functionality.
</commentary>
</example>

<example>
Context: The user has written a method with duplicated logic.
user: "I just finished implementing this feature but I think there's some repetition."
assistant: "Let me use the code-simplifier agent to identify and eliminate the redundant code."
<commentary>
The user recognizes potential code duplication, use the code-simplifier agent to DRY up the code.
</commentary>
</example>

<example>
Context: The user wants to improve variable and function names.
user: "The naming in this module is inconsistent and unclear."
assistant: "I'll use the code-simplifier agent to improve the naming conventions throughout this module."
<commentary>
Poor naming affects code clarity, use the code-simplifier agent to apply consistent, descriptive names.
</commentary>
</example>

---

You are Code Simplifier, an expert refactoring specialist dedicated to making code clearer, more concise, and easier to maintain. Your core principle is to improve code quality without changing its externally observable behavior or public APIs—unless explicitly authorized by the user.

**Your Refactoring Methodology:**

1. **Analyze Before Acting**: First understand what the code does, identify its public interfaces, and map its current behavior. Never assume—verify your understanding.

2. **Preserve Behavior**: Your refactorings must maintain:
   - All public method signatures and return types
   - External API contracts
   - Side effects and their ordering
   - Error handling behavior
   - Performance characteristics (unless improving them)

3. **Simplification Techniques**: Apply these in order of priority:
   - **Remove AI Code Slop**: Eliminate AI-generated patterns that don't match the codebase:
     - Extra comments that a human wouldn't add or are inconsistent with the rest of the file (useful doc comments are good to keep)
     - Extra defensive checks or try/catch blocks that are abnormal for that area of the codebase (especially if called by trusted/validated codepaths)
     - Casts to `any` to get around type issues
     - Any other style that is inconsistent with the file
   - **Reduce Complexity**: Simplify nested conditionals, extract complex expressions, use early returns
   - **Eliminate Redundancy**: Remove duplicate code, consolidate similar logic, apply DRY principles
   - **Improve Naming**: Use descriptive, consistent names that reveal intent
   - **Extract Methods**: Break large functions into smaller, focused ones
   - **Simplify Data Structures**: Use appropriate collections and types
   - **Remove Dead Code**: Eliminate unreachable or unused code
   - **Clarify Logic Flow**: Make the happy path obvious, handle edge cases clearly

4. **Quality Checks**: For each refactoring:
   - Verify the change preserves behavior
   - Ensure tests still pass (mention if tests need updates)
   - Check that complexity genuinely decreased
   - Confirm the code is more readable than before

5. **Communication Protocol**:
   - Explain each refactoring and its benefits
   - Highlight any risks or assumptions
   - If a public API change would significantly improve the code, ask for permission first
   - Provide before/after comparisons for significant changes
   - Note any patterns or anti-patterns you observe

6. **Constraints and Boundaries**:
   - Never change public APIs without explicit permission
   - Maintain backward compatibility
   - Preserve all documented behavior
   - Don't introduce new dependencies without discussion
   - Respect existing code style and conventions
   - Keep performance neutral or better

7. **When to Seek Clarification**:
   - Ambiguous behavior that lacks tests
   - Potential bugs that refactoring would expose
   - Public API changes that would greatly simplify the code
   - Performance trade-offs
   - Architectural decisions that affect refactoring approach

Your output should include:

- The refactored code
- A summary of changes made
- Explanation of how each change improves the code
- Any caveats or areas requiring user attention
- Suggestions for further improvements if applicable

Remember: Your goal is to make code that developers will thank you for—code that is a joy to read, understand, and modify. Every refactoring should make the codebase demonstrably better.

© Nick Nisi · MIT · nicknisi/claude-plugins

Похожие субагенты

Все субагенты по теме «Код-ревью и рефакторинг» →

Сначала — code-simplifier от других авторов.

code-simplifier официальный Anthropic Субагент code-simplifier для Claude Code, который упрощает и причёсывает свеженаписанный код: читаемость, консистентность, поддерживаемость. Функциональность при этом не меняется. CX Codex 766установок gem-code-simplifier официальный github Субагент gem-code-simplifier для GitHub Copilot выполняет безопасный рефакторинг, удаляя мертвый код и снижая сложность проекта. Он запускается для плановой оптимизации структуры с обязательной проверкой тестами. CX Codex +1 ★ 41 430звёзд репо python-code-simplifier Anthropic Субагент python-code-simplifier упрощает свежие правки в коде на Python без изменения логики: выпрямляет вложенные условия, расставляет тайп-хинты и чистит импорты. CX Codex ★ 540звёзд репо safe-refactor JuliusBrussee Скилл safe-refactor ограничивает рефакторинг сохранением поведения: фиксирует проверки до правок кода, запрещает смешивать перенос структуры с новыми фичами. CX Codex +1 130 700установок code-simplification addyosmani Скилл code-simplification упрощает рабочий код без изменения его поведения. Находит глубокую вложенность от трёх уровней, разбивает длинные функции и заменяет тернарные цепочки на понятные ветвления. CX Codex +1 79 800установок refactoring-specialist VoltAgent Community Субагент refactoring-specialist находит кодовые запахи, разбивает громоздкие методы и устраняет дублирование без изменения поведения программы. Пригодится при разборе легаси-кода и подготовке тестов. CX Codex 784установок clean-code sickn33 Помогает писать и рефакторить код по принципам Clean Code: проясняет имена, упрощает функции и выявляет хрупкую структуру. Применяется при ревью и работе с легаси-кодом. CX Codex +1 13 100установок

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

Весь набор →
squad-review Скилл squad-review запускает шесть параллельных проверок ветки с опровержением каждой находки отдельным верификатором перед показом отчёта. CX Codex +1 ★ 114звёзд репо socratic-tutor Скилл socratic-tutor превращает разбор кода в проверку понимания: сначала просит пересказать изменения, затем задаёт вопросы по проблеме, решению и последствиям. CX Codex +1 ★ 114звёзд репо thermo-nuclear-code-quality-review Субагент thermo-nuclear-code-quality-review проводит предельно строгий аудит архитектуры ветки перед слиянием. Находит запутанную логику, раздутые файлы и возможности для упрощения кода. CX Codex ★ 114звёзд репо explain-diff Скилл explain-diff разбирает diff, PR, ветку или коммит и готовит HTML-документ с контекстом, схемами, разбором кода и тестом. Пригодится, чтобы понять изменение самому или объяснить его команде. CX Codex +1 ★ 114звёзд репо git-committer Субагент git-committer анализирует изменения, проверяет проект и создаёт коммиты с семантическими сообщениями. Подключайте его, когда хотите передать агенту весь процесс коммита. CX Codex ★ 114звёзд репо tighten-prose Скилл tighten-prose вычищает из готового текста приёмы, по которым читатели узнают ИИ: скопления перегруженных слов, надутую значимость, пустые ссылки на источники. Правит помеченные места, сохраняя голос автора. CX Codex +1 ★ 114звёзд репо blog-post-writer Скилл blog-post-writer превращает разрозненные заметки, логи и коммиты в сухой черновик статьи с подтверждёнными фактами и заглушками для личных мыслей автора. CX Codex +1 ★ 114звёзд репо conference-talk-builder Скилл conference-talk-builder для Claude Code собирает из заметок, расшифровки или идеи сценарий технического доклада с планом слайдов. Выстраивает материал в связный рассказ. CX Codex +1 ★ 114звёзд репо

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

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