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

modular-decomposition — скилл для Claude Code

Скилл modular-decomposition проводит монолит через пять шагов анализа перед разбивкой на модули: размер и инвентаризация компонентов, дублирование логики, иерархия, связность, группировка по доменам.

MIT ★ 7 191 обновлён 2026-10-24

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add tech-leads-club/agent-skills --skill modular-decomposition -a claude-code
Открыть на GitHub

Что делает modular-decomposition

Скилл запускает последовательность из пяти паттернов (pattern-01 – pattern-05), каждый оформлен отдельным markdown-файлом в references/. Сначала компоненты инвентаризируются и оцениваются по размеру, затем ищется общая доменная логика, продублированная в разных местах, потом разбираются проблемы плоской структуры и иерархии модулей, дальше считается связность между частями кода, и на последнем шаге компоненты группируются в кандидатов на отдельные сервисы по доменным границам.

Шаги идут по порядку: вывод Pattern 1 (список и размеры компонентов) используется в Pattern 4 для расчёта связности и в Pattern 5 для группировки. Агент может пропустить шаг только по явной просьбе пользователя и должен сказать, какие выводы из-за этого станут менее надёжными. Для Pattern 5 можно подключить references/domain-analysis.md — это отдельный DDD-разбор стратегических границ (сабдомены, bounded contexts, единый язык), если группировку по структуре нужно сверить с бизнес-терминологией.

Скилл не строит дорожную карту с фазами экстракции и приоритетами — для этого нужен decomposition-planning-roadmap после прогона этого пайплайна. Для полной стратегии переноса легаси-системы (strangler fig, межстековые переписывания) нужен отдельный legacy-migration-planner.

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

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

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

  • Прогони modular-decomposition, паттерны 1–5, на этом репозитории
  • Найди задублированную доменную логику между модулями через modular-decomposition
  • Посчитай связность между нашими пакетами и сгруппируй компоненты по доменам

Как установить modular-decomposition

1Через Skills CLI (Vercel)

npx skills add tech-leads-club/agent-skills --skill modular-decomposition -a claude-code

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

~/.claude/skills/modular-decomposition/SKILL.md

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

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

Вопросы о modular-decomposition

Как установить modular-decomposition в Claude Code?

Выполните npx skills add tech-leads-club/agent-skills --skill modular-decomposition -a claude-code, скилл появится в ~/.claude/skills/modular-decomposition/SKILL.md.

Что делает modular-decomposition?

Прогоняет монолит через пять паттернов анализа: инвентаризация и размер компонентов, поиск дублированной доменной логики, разбор иерархии, расчёт связности и группировка компонентов в кандидатов на сервисы по доменам.

Чем modular-decomposition отличается от decomposition-planning-roadmap?

modular-decomposition делает структурный анализ — инвентаризацию, связность и группировку, а decomposition-planning-roadmap строит на этой основе дорожную карту с фазами и приоритетами экстракции, и его стоит ставить после.

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

SKILL.md · MIT
---
name: modular-decomposition
description: Runs a sequenced monolith-to-modular pipeline that sizes and inventories components, finds shared domain duplication, addresses flattening and hierarchy issues, analyzes coupling, then groups components into candidate domain-aligned units, with optional embedded DDD strategic analysis for bounded contexts. Use when asking how to split a monolith, size components before extraction, find duplicated domain logic, clean up module hierarchy, measure coupling between modules, or group components into services. Do NOT use for phased extraction roadmaps or prioritization without the prior analysis steps (use decomposition-planning-roadmap after this pipeline), end-to-end legacy migration strategy writeups (use legacy-migration-planner), pure infrastructure capacity sizing, or when you only need DDD without the structural pipeline (install domain-analysis standalone).
---

# Modular Decomposition

This skill runs the **Patterns 1–5** analysis pipeline before service extraction. Each pattern is plain markdown under `references/`; load the file for that step and execute it against the user’s codebase.

## How to Use

### Quick start (what users can say)

- **Full pipeline:** “Run modular decomposition Patterns 1 through 5 on this repo,” “Analyze this monolith for splitting—inventory, coupling, and domain grouping.”
- **Single early step:** “Identify and size components here,” “Find duplicated domain logic across modules,” “Analyze coupling between our packages.”
- **With DDD lens:** “Group components into domains and check bounded contexts,” “Use DDD strategic design on this codebase before we group services.”

If the user only wants **extraction order, phases, or migration roadmap** after analysis exists, use **decomposition-planning-roadmap** instead. If they need a **full legacy migration plan** (strangler fig, research, multi-stack), use **legacy-migration-planner** as well or instead of this skill when that is the primary ask.

### How the agent should run it

1. **Scope:** Confirm the task is structural analysis (inventory → coupling → grouping), not roadmap authoring. If unclear, ask once whether they want the full ordered pipeline or a subset.
2. **Order:** Run patterns **1 → 2 → 3 → 4 → 5** in that order. Do not skip a step unless the user explicitly limits scope; if they do, state which patterns were skipped and how that limits later conclusions.
3. **Load references:** For each pattern, open the matching `references/pattern-NN-*.md` file and follow its instructions. Use the optional `*-quick-reference.md` for the same number when a short checklist is enough.
4. **Carry context forward:** Reuse outputs from earlier patterns in later ones (e.g. component inventory from Pattern 1 informs coupling in 4 and grouping in 5). Reference concrete paths, modules, or tables from previous steps.
5. **Domain language (Pattern 5):** If subdomains or bounded contexts need grounding beyond structure, read `references/domain-analysis.md` **before or alongside** Pattern 5. Optionally open `references/domain-analysis-quick-reference.md` or `references/domain-analysis-examples.md` for condensed rules or illustrations.
6. **Deliver:** Produce clear, actionable findings per pattern or one consolidated report—always tied to evidence from the repository (files, dependencies, metrics), not generic advice.

### Usage examples

**Example 1 — Full pipeline**

```
User: "We're going to split this monolith—run the full decomposition analysis (Patterns 1–5)."

Agent: Execute patterns 1→5 in order, loading each references/pattern-NN-*.md, preserving outputs between steps, then summarize cross-cutting recommendations.
```

**Example 2 — Coupling after inventory**

```
User: "We already have a rough module list—focus on coupling (Pattern 4) and then domain grouping (Pattern 5)."

Agent: If no prior inventory exists in the thread, either run Pattern 1 briefly or derive an explicit module list from the repo before 4 and 5. State any assumptions.
```

**Example 3 — DDD before grouping**

```
User: "Map bounded contexts and language, then group components into domains."

Agent: Read references/domain-analysis.md (and optional quick reference/examples) in parallel with or immediately before Pattern 5; align Pattern 5 groupings with linguistic boundaries where evidence supports it.
```

## Prerequisites

- Complete **Pattern N** before starting Pattern N+1 unless the user explicitly narrows scope. Later patterns depend on earlier results (for example, inventory and structure inform coupling and grouping).
- If business vocabulary, subdomains, or bounded contexts are uncertain, use `references/domain-analysis.md` **before or alongside Pattern 5** (see Bounded contexts below).

## Ordered workflow (Patterns 1–5)

| Step | Pattern                            | Primary reference                                                                                          |
| ---- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| 1    | Identify and size components       | `references/pattern-01-identify-and-size.md` (optional: `pattern-01-identify-and-size-quick-reference.md`) |
| 2    | Common domain detection            | `references/pattern-02-common-domain.md` (optional: `pattern-02-common-domain-quick-reference.md`)         |
| 3    | Flattening / hierarchy             | `references/pattern-03-flattening.md` (optional: `pattern-03-flattening-quick-reference.md`)               |
| 4    | Coupling analysis                  | `references/pattern-04-coupling.md`                                                                        |
| 5    | Domain identification and grouping | `references/pattern-05-domain-grouping.md` (optional: `pattern-05-domain-grouping-quick-reference.md`)     |

## Pattern 6 — planning and extraction

**Pattern 6** (_create domain services / extraction_) is not duplicated here. After Pattern 5, switch to **decomposition-planning-roadmap** for phased extraction order, milestones, and migration-style planning. For full legacy migration strategy (strangler-fig, cross-stack rewrites, research-heavy plans), optionally use **legacy-migration-planner** in addition.

## Bounded contexts and DDD strategic design

- **Patterns 1–4** focus on **structural** inventory, duplication, hierarchy, and **coupling** between parts of the codebase.
- **Pattern 5** produces **candidate** groupings aligned with **solution-space** boundaries (which components belong together as services).
- **Strategic DDD** (subdomains, bounded contexts, ubiquitous language) is covered in `references/domain-analysis.md`, with optional `domain-analysis-quick-reference.md` and `domain-analysis-examples.md`. Use it when you need to validate or refine boundaries against business language, not only folder structure.

© tech-leads-club · MIT · tech-leads-club/agent-skills

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

Все скиллы по теме «Код-ревью и рефакторинг» →
code-modularization-evaluator dotneet Скилл code-modularization-evaluator разбирает связи между модулями по Balanced Coupling Model и подсказывает, что переписать. Пригодится при ревью архитектуры и разбиении монолита. CX Codex +1 462установок legacy-modernizer qdhenry legacy-modernizer — субагент для Claude Code, который планирует и проводит постепенную модернизацию устаревших систем. Он включается при рефакторинге, миграции фреймворка или разборе монолита. CX Codex ★ 1 357звёзд репо modular-code parcadei Скилл modular-code для Claude Code делит крупные Python-файлы на модули по смыслу и слоям. Разделяет файлы со смешанными задачами и кодом, который трудно читать и тестировать. CX Codex +1 ★ 3 951звёзд репо ddd-validate ruvnet Скилл ddd-validate проверяет границы ограниченных контекстов в коде на TypeScript и выявляет утечки между доменами. Пригодится при аудите архитектуры DDD и перед слиянием общих правок. CX Codex +1 737установок domain-model-boundaries-mapper patricio0312rev Скилл domain-model-boundaries-mapper анализирует архитектуру проекта по принципам Domain-Driven Design: находит доменные модули, границы ответственности и зависимости. Помогает спланировать разделение связанных компонентов. CX Codex +1 270установок V3 DDD Architecture ruvnet Скилл V3 DDD Architecture раскладывает монолитный orchestrator из claude-flow v3 по пяти bounded contexts и собирает домены в микрокернель с шиной событий. CX Codex +1 1 100установок

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

Весь набор →
state-context-interface Правило state-context-interface для Claude Code: отделяет интерфейс компонентов от источника состояния через контекст с частями state, actions и meta. Один UI подключается к разным провайдерам состояния. CX Codex +1 ★ 7 191звёзд репо learning-opportunities Скилл learning-opportunities предлагает короткие учебные упражнения после архитектурной работы в Claude, чтобы код, который написал агент, не остался для вас чёрным ящиком. CX Codex +1 ★ 7 191звёзд репо confluence-assistant Скилл confluence-assistant учит агента работать с Confluence через Atlassian MCP. Помогает искать страницы поиском Rovo, создавать новые записи в разметке Markdown и обновлять документацию прямо из чата. CX Codex +1 ★ 7 191звёзд репо security-threat-model Скилл security-threat-model строит модель угроз по коду репозитория: находит границы доверия, активы и реалистичные пути атаки, а результат сохраняет в Markdown-файл. CX Codex +1 ★ 7 191звёзд репо tlc-plan Скилл tlc-plan превращает PRD, тикеты и обсуждения в строгий план разработки. Уточняет серые зоны до написания кода и фиксирует критерии приёмки. CX Codex +1 ★ 7 191звёзд репо legacy-migration-planner Скилл legacy-migration-planner планирует миграцию легаси-систем, модернизацию кодовой базы и разбиение монолита. Он пригодится до начала работ, когда нужен план перехода. CX Codex +1 ★ 7 191звёзд репо shopify-developer Скилл shopify-developer для Claude Code даёт агенту справочник по Liquid, темам OS 2.0, GraphQL API, Functions и Hydrogen для разработки под Shopify. CX Codex +1 ★ 7 191звёзд репо aws-advisor Скилл aws-advisor консультирует по архитектуре AWS, проверяет безопасность и сверяет параметры сервисов с документацией через MCP-инструменты. CX Codex +1 ★ 7 191звёзд репо

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

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