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

explain-code — команда для Claude Code: разбор кода по шагам

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

Установить в Claude Code · Через claude-code-templates Все способы и платформы ↓
npx claude-code-templates@latest --command utilities/explain-code
Открыть на GitHub

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

Команда explain-code задаёт агенту порядок разбора: сначала контекст файла и его роль в проекте, потом общий смысл, структура, разбор отдельных строк, алгоритм, типы данных, работа с фреймворками, обработка ошибок, производительность и безопасность. Дальше идут тесты, зависимости, паттерны, возможные улучшения и точки для отладки.

Внутри — не скрипт, а инструкция из 16 шагов плюс примеры формата ответа: для сложных алгоритмов, кода интеграции с API и запросов к базе. Есть отдельные подсказки под JavaScript, Python, Java, C#, Go и Rust — что именно стоит пояснить в каждом языке.

Аргумент передаётся через $ARGUMENTS, то есть в вызове нужно указать, что разбирать. Без него команда не поймёт, к чему применять шаги. Разбор идёт по тексту, который агент видит в проекте, поэтому для больших файлов ответ выйдет длинным.

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

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

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

  • /explain-code src/auth/session.ts
  • /explain-code объясни функцию calculateDiscount в pricing.py
  • /explain-code разбери этот SQL-запрос с джойнами

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

1Через claude-code-templates

npx claude-code-templates@latest --command utilities/explain-code

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

.claude/commands/explain-code.md

Вызов — /explain-code. Для всех проектов — ~/.claude/commands/

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

Весь набор →
update-search-year Хук добавляет текущий год к запросам WebSearch, если года в них нет. Пригодится, когда нужны свежие результаты, а не прошлогодние. 3 412установок technical-researcher Субагент изучает чужие репозитории и документацию: собирает метрики, оценивает качество кода и выдаёт отчёт с рекомендациями. 3 344установок lint-on-save Хук запускает линтер сразу после того, как агент изменил файл. ESLint, Pylint и RuboCop срабатывают сами, без ручного вызова. 3 235установок todo Ведёт задачи проекта в файле todos.md прямо из чата: добавить, закрыть, удалить, посмотреть список. Пригодится, когда не хочется уходить из Claude ради таск-трекера. 2 723установок create-prd Слэш-команда превращает идею фичи в документ требований: проблема, объём работ, метрики успеха и критерии приёмки. 2 431установок workflow-orchestrator Оркестрирует цепочки задач автоматизации с графом зависимостей, расписанием и параллельным выполнением в проекте. 2 341установок devops-troubleshooter Субагент исследует логи, сбои развёртывания и проблемы мониторинга. Подключайте его, когда нужно найти причину инцидента и подготовить исправление. 2 328установок dependency-checker Хук на PostToolUse: после правки файла зависимостей запускает аудит пакетов и показывает, что устарело или уязвимо. 2 314установок

Похожие

understand-explain Egonex-AI Скилл объясняет файл, функцию или модуль по графу знаний проекта: связи, слои, поток данных. Пригодится, когда нужно разобраться в чужом коде. CX Codex +1 3 800установок audit-verify-explain-grade-5 MengTo Скилл заставляет агента проверить работу по фактам, а потом объяснить результат простыми словами. Пригодится, когда нужно разобрать чужой фикс или отчёт о тестах. CX Codex +1 1 400установок code-documentation-code-explain sickn33 Скилл превращает запутанный код в понятные объяснения с диаграммами и пошаговыми разборами. Пригодится, когда нужно быстро разобраться в чужом коде или подготовить материал для обучения. CX Codex +1 1 000установок cypress-explain cypress-io Разбирает сквозные и компонентные тесты Cypress, объясняет вызовы команд и проводит ревью кода без внесения правок в файлы проекта. CX Codex +1 8 000установок convex-explain-app convex Скилл строит понятную карту бэкенда Convex по схеме данных и функциям. Помогает быстро разобраться в незнакомом проекте перед правками или аудитом. CX Codex +1 35 900установок research microsoft Проводит многошаговое исследование темы по кодовой базе: читает реальные пути выполнения и требует источник для каждого утверждения. ★ 3 148звёзд репо

Рядом в теме «Код-ревью и рефакторинг»

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

Вопросы о explain-code

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

Выполните npx claude-code-templates@latest --command utilities/explain-code, файл появится по пути .claude/commands/explain-code.md.

Что делает explain-code?

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

Нужно ли указывать, какой код разбирать?

Да, команда подставляет аргумент через $ARGUMENTS. Передайте путь к файлу или название функции прямо в вызове.

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

explain-code.md · MIT
---
description: "Analyze and explain code functionality"
---

# Analyze and Explain Code Functionality

Analyze and explain code functionality

## Instructions

Follow this systematic approach to explain code: **$ARGUMENTS**

1. **Code Context Analysis**
   - Identify the programming language and framework
   - Understand the broader context and purpose of the code
   - Identify the file location and its role in the project
   - Review related imports, dependencies, and configurations

2. **High-Level Overview**
   - Provide a summary of what the code does
   - Explain the main purpose and functionality
   - Identify the problem the code is solving
   - Describe how it fits into the larger system

3. **Code Structure Breakdown**
   - Break down the code into logical sections
   - Identify classes, functions, and methods
   - Explain the overall architecture and design patterns
   - Map out data flow and control flow

4. **Line-by-Line Analysis**
   - Explain complex or non-obvious lines of code
   - Describe variable declarations and their purposes
   - Explain function calls and their parameters
   - Clarify conditional logic and loops

5. **Algorithm and Logic Explanation**
   - Describe the algorithm or approach being used
   - Explain the logic behind complex calculations
   - Break down nested conditions and loops
   - Clarify recursive or asynchronous operations

6. **Data Structures and Types**
   - Explain data types and structures being used
   - Describe how data is transformed or processed
   - Explain object relationships and hierarchies
   - Clarify input and output formats

7. **Framework and Library Usage**
   - Explain framework-specific patterns and conventions
   - Describe library functions and their purposes
   - Explain API calls and their expected responses
   - Clarify configuration and setup code

8. **Error Handling and Edge Cases**
   - Explain error handling mechanisms
   - Describe exception handling and recovery
   - Identify edge cases being handled
   - Explain validation and defensive programming

9. **Performance Considerations**
   - Identify performance-critical sections
   - Explain optimization techniques being used
   - Describe complexity and scalability implications
   - Point out potential bottlenecks or inefficiencies

10. **Security Implications**
    - Identify security-related code sections
    - Explain authentication and authorization logic
    - Describe input validation and sanitization
    - Point out potential security vulnerabilities

11. **Testing and Debugging**
    - Explain how the code can be tested
    - Identify debugging points and logging
    - Describe mock data or test scenarios
    - Explain test helpers and utilities

12. **Dependencies and Integrations**
    - Explain external service integrations
    - Describe database operations and queries
    - Explain API interactions and protocols
    - Clarify third-party library usage

**Explanation Format Examples:**

**For Complex Algorithms:**
```
This function implements a depth-first search algorithm:

1. Line 1-3: Initialize a stack with the starting node and a visited set
2. Line 4-8: Main loop - continue until stack is empty
3. Line 9-11: Pop a node and check if it's the target
4. Line 12-15: Add unvisited neighbors to the stack
5. Line 16: Return null if target not found

Time Complexity: O(V + E) where V is vertices and E is edges
Space Complexity: O(V) for the visited set and stack
```

**For API Integration Code:**
```
This code handles user authentication with a third-party service:

1. Extract credentials from request headers
2. Validate credential format and required fields
3. Make API call to authentication service
4. Handle response and extract user data
5. Create session token and set cookies
6. Return user profile or error response

Error Handling: Catches network errors, invalid credentials, and service unavailability
Security: Uses HTTPS, validates inputs, and sanitizes responses
```

**For Database Operations:**
```
This function performs a complex database query with joins:

1. Build base query with primary table
2. Add LEFT JOIN for related user data
3. Apply WHERE conditions for filtering
4. Add ORDER BY for consistent sorting
5. Implement pagination with LIMIT/OFFSET
6. Execute query and handle potential errors
7. Transform raw results into domain objects

Performance Notes: Uses indexes on filtered columns, implements connection pooling
```

13. **Common Patterns and Idioms**
    - Identify language-specific patterns and idioms
    - Explain design patterns being implemented
    - Describe architectural patterns in use
    - Clarify naming conventions and code style

14. **Potential Improvements**
    - Suggest code improvements and optimizations
    - Identify possible refactoring opportunities
    - Point out maintainability concerns
    - Recommend best practices and standards

15. **Related Code and Context**
    - Reference related functions and classes
    - Explain how this code interacts with other components
    - Describe the calling context and usage patterns
    - Point to relevant documentation and resources

16. **Debugging and Troubleshooting**
    - Explain how to debug issues in this code
    - Identify common failure points
    - Describe logging and monitoring approaches
    - Suggest testing strategies

**Language-Specific Considerations:**

**JavaScript/TypeScript:**
- Explain async/await and Promise handling
- Describe closure and scope behavior
- Clarify this binding and arrow functions
- Explain event handling and callbacks

**Python:**
- Explain list comprehensions and generators
- Describe decorator usage and purpose
- Clarify context managers and with statements
- Explain class inheritance and method resolution

**Java:**
- Explain generics and type parameters
- Describe annotation usage and processing
- Clarify stream operations and lambda expressions
- Explain exception hierarchy and handling

**C#:**
- Explain LINQ queries and expressions
- Describe async/await and Task handling
- Clarify delegate and event usage
- Explain nullable reference types

**Go:**
- Explain goroutines and channel usage
- Describe interface implementation
- Clarify error handling patterns
- Explain package structure and imports

**Rust:**
- Explain ownership and borrowing
- Describe lifetime annotations
- Clarify pattern matching and Option/Result types
- Explain trait implementations

Remember to:
- Use clear, non-technical language when possible
- Provide examples and analogies for complex concepts
- Structure explanations logically from high-level to detailed
- Include visual diagrams or flowcharts when helpful
- Tailor the explanation level to the intended audience

© davila7 · MIT · davila7/claude-code-templates

Смотрите также

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

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