gap-analysis — правило для Claude Code: анализ разрыва между требованиями и кодом
Правило gap-analysis помогает структурировать анализ существующей кодовой базы, выявить, чего не хватает для реализации требований, и выбрать стратегию разработки.
MIT ★ 3 774 обновлён 2026-10-22
.claude/rules/gap-analysis.mdЧто делает gap-analysis
Правило проводит вас через четыре этапа: сначала вы инвентаризируете текущее состояние — ключевые файлы, компоненты, паттерны и ограничения архитектуры. Затем анализируете требования, выделяя нужные данные, API, бизнес-логику и неизвестные области для исследования. На третьем этапе рассматриваете три подхода: расширить существующие компоненты (быстро, но риск усложнить), создать новые (чистое разделение забот, но больше файлов) или гибридный способ для сложных фич.
В выводе даёте карту требований и пропусков, оцениваете усилия (S — 1–3 дня, M — 3–7 дней, L — 1–2 недели, XL — 2+ недели) и риск (Low, Medium, High). Правило фокусируется на анализе и вариантах, не на финальном выборе — это инструмент для согласованного решения в команде, не автоматический генератор планов.
Какие задачи решает
- Понять, какие части кода можно переиспользовать для новой фичи
- Выявить пропуски в текущей архитектуре перед разработкой
- Выбрать между расширением существующих компонентов и созданием новых
- Оценить объём работ и риски до начала проектирования
- Согласовать стратегию разработки в команде на основе фактов о кодовой базе
Примеры запросов агенту
- Проведи gap-analysis для фичи авторизации: что есть в текущей кодовой базе, где пропуски, какие подходы возможны
- Сделай анализ разрыва между требованиями к API и существующей структурой эндпоинтов
- Используя gap-analysis, определи, нужно ли создавать новый сервис или расширить текущий для обработки платежей
Как установить gap-analysis
Вручную: положить файлы
.claude/rules/gap-analysis.mdПоле paths во frontmatter ограничивает файлы
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.cursor/rules/gap-analysis.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.github/instructions/gap-analysis.instructions.mdПоле applyTo задаёт, к каким файлам применять
Вручную: положить файлы
.devin/rules/gap-analysis.mdВручную: положить файлы
.clinerules/gap-analysis.mdПо шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать
Вопросы о gap-analysis
Как установить gap-analysis в Claude Code?
Скопируй содержимое правила в файл .claude/rules/gap-analysis.md в корне проекта. Claude Code будет автоматически загружать его при анализе кодовой базы.
Что делает правило gap-analysis?
Правило структурирует процесс анализа разрыва между требованиями и существующей кодовой базой. Оно помогает инвентаризировать текущее состояние, выявить пропуски и ограничения, а затем рассмотреть несколько вариантов реализации с оценкой усилий и рисков.
Когда нужна gap-analysis: расширить компонент или создать новый?
Правило предлагает три подхода. Расширяйте существующий компонент, если фича органично встраивается в его структуру и не усложнит его. Создавайте новый, если фича имеет отличную ответственность или текущие компоненты уже перегружены. Гибридный подход подходит для сложных фич, которые требуют и расширения, и новых компонентов.
Исходный текст
gap-analysis.md · MIT
# Gap Analysis Process
## Objective
Analyze the gap between requirements and existing codebase to inform implementation strategy decisions.
## Analysis Framework
### 1. Current State Investigation
- Scan for domain-related assets:
- Key files/modules and directory layout
- Reusable components/services/utilities
- Dominant architecture patterns and constraints
- Extract conventions:
- Naming, layering, dependency direction
- Import/export patterns and dependency hotspots
- Testing placement and approach
- Note integration surfaces:
- Data models/schemas, API clients, auth mechanisms
### 2. Requirements Feasibility Analysis
- From EARS requirements, list technical needs:
- Data models, APIs/services, UI/components
- Business rules/validation
- Non-functionals: security, performance, scalability, reliability
- Identify gaps and constraints:
- Missing capabilities in current codebase
- Unknowns to be researched later (mark as "Research Needed")
- Constraints from existing architecture and patterns
- Note complexity signals:
- Simple CRUD / algorithmic logic / workflows / external integrations
### 3. Implementation Approach Options
#### Option A: Extend Existing Components
**When to consider**: Feature fits naturally into existing structure
- **Which files/modules to extend**:
- Identify specific files requiring changes
- Assess impact on existing functionality
- Evaluate backward compatibility concerns
- **Compatibility assessment**:
- Check if extension respects existing interfaces
- Verify no breaking changes to consumers
- Assess test coverage impact
- **Complexity and maintainability**:
- Evaluate cognitive load of additional functionality
- Check if single responsibility principle is maintained
- Assess if file size remains manageable
**Trade-offs**:
- ✅ Minimal new files, faster initial development
- ✅ Leverages existing patterns and infrastructure
- ❌ Risk of bloating existing components
- ❌ May complicate existing logic
#### Option B: Create New Components
**When to consider**: Feature has distinct responsibility or existing components are already complex
- **Rationale for new creation**:
- Clear separation of concerns justifies new file
- Existing components are already complex
- Feature has distinct lifecycle or dependencies
- **Integration points**:
- How new components connect to existing system
- APIs or interfaces exposed
- Dependencies on existing components
- **Responsibility boundaries**:
- Clear definition of what new component owns
- Interfaces with existing components
- Data flow and control flow
**Trade-offs**:
- ✅ Clean separation of concerns
- ✅ Easier to test in isolation
- ✅ Reduces complexity in existing components
- ❌ More files to navigate
- ❌ Requires careful interface design
#### Option C: Hybrid Approach
**When to consider**: Complex features requiring both extension and new creation
- **Combination strategy**:
- Which parts extend existing components
- Which parts warrant new components
- How they interact
- **Phased implementation**:
- Initial phase: minimal viable changes
- Subsequent phases: refactoring or new components
- Migration strategy if needed
- **Risk mitigation**:
- Incremental rollout approach
- Feature flags or configuration
- Rollback strategy
**Trade-offs**:
- ✅ Balanced approach for complex features
- ✅ Allows iterative refinement
- ❌ More complex planning required
- ❌ Potential for inconsistency if not well-coordinated
### 4. Out-of-Scope for Gap Analysis
- Defer deep research activities to the design phase.
- Record unknowns as concise "Research Needed" items only.
### 5. Implementation Complexity & Risk
- Effort:
- S (1–3 days): existing patterns, minimal deps, straightforward integration
- M (3–7 days): some new patterns/integrations, moderate complexity
- L (1–2 weeks): significant functionality, multiple integrations or workflows
- XL (2+ weeks): architectural changes, unfamiliar tech, broad impact
- Risk:
- High: unknown tech, complex integrations, architectural shifts, unclear perf/security path
- Medium: new patterns with guidance, manageable integrations, known perf solutions
- Low: extend established patterns, familiar tech, clear scope, minimal integration
### Output Checklist
- Requirement-to-Asset Map with gaps tagged (Missing / Unknown / Constraint)
- Options A/B/C with short rationale and trade-offs
- Effort (S/M/L/XL) and Risk (High/Medium/Low) with one-line justification each
- Recommendations for design phase:
- Preferred approach and key decisions
- Research items to carry forward
## Principles
- **Information over decisions**: Provide analysis and options, not final choices
- **Multiple viable options**: Offer credible alternatives when applicable
- **Explicit gaps and assumptions**: Flag unknowns and constraints clearly
- **Context-aware**: Align with existing patterns and architecture limits
- **Transparent effort and risk**: Justify labels succinctly
© gotalab · MIT · gotalab/cc-sdd