module-shape — правило для Claude Code: модули и установка
Правило module-shape помогает держать публичный интерфейс модулей узким, а сложность — внутри. Оно пригодится при проектировании и ревью кода.
MIT ★ 2 966 обновлён 2026-09-29
.cursor/rules/module-shape.mdcЧто делает module-shape
Правило предлагает оставлять у модуля небольшую публичную поверхность, скрывая внутри алгоритмы, ветвления, состояния, повторы и кэширование. Перед добавлением нового экспорта стоит проверить, может ли существующий принять эту логику. При удалении — не стал ли модуль слишком тонким для отдельного существования.
Внешние зависимости передаются через аргументы, а бизнес-логика не создаёт клиентов, не читает конфигурацию и не обращается к часам сама. Функции должны возвращать значения, а не менять входные объекты. Моки нужны на границах системы: для HTTP API, базы данных, часов, случайности и файловой системы. Если код внутри бизнес-логики сам создаёт внешний клиент, это нарушение правила. Для таких границ предлагаются моки, повторяющие форму конкретных конечных точек.
Какие задачи решает
- сузить публичный интерфейс модуля
- спрятать ветвления и состояние за API
- передать внешние зависимости через аргументы
- проверить границы для моков на ревью
Примеры запросов агенту
- Проверь этот модуль по правилу
module-shapeи укажи лишние публичные методы. - Перепиши функцию так, чтобы внешний клиент передавался аргументом, а бизнес-логика возвращала значение.
- Проведи ревью тестов: найди моки внутренних классов и замени их проверкой границ системы.
Как установить module-shape
Вручную: положить файлы
.cursor/rules/module-shape.mdcВо frontmatter: description, globs, alwaysApply
1Через маркетплейс плагинов
/plugin marketplace add rohitg00/pro-workflow/plugin install pro-workflow@pro-workflow2Вручную: положить файлы
.claude/rules/module-shape.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/module-shape.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/module-shape.mdВручную: положить файлы
.clinerules/module-shape.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о module-shape
Как установить module-shape в Claude Code?
Добавьте маркетплейс командой /plugin marketplace add rohitg00/pro-workflow, установите плагин через /plugin install pro-workflow@pro-workflow, затем разместите правило по пути .claude/rules/module-shape.md.
Что делает правило module-shape?
Оно задаёт принципы проектирования модулей: узкий публичный интерфейс, скрытая внутренняя сложность, передача зависимостей через аргументы и моки только на системных границах.
Что именно можно мокать по этому правилу?
Мокать следует внешние HTTP API, базы данных при отсутствии реального тестового экземпляра, часы, источники случайности и файловую систему. Собственные модули и внутренние классы предлагается создавать напрямую.
Исходный текст
module-shape.mdc · MIT
---
description: Prefer modules with a narrow public surface and a thick internal implementation. Inject external dependencies at the boundary. Mock only at system edges.
globs:
alwaysApply: true
---
# Module Shape
## Surface vs. depth
A module's **surface** is every symbol a caller can touch: exported
functions, class methods, config parameters, flags. A module's **depth**
is everything hidden behind that surface: algorithms, branching, state
machines, retries, caching.
Aim for **narrow surface, thick depth**. A three-method module that hides
a hundred lines of branching is strong. A thirty-method module whose
methods each forward a single call to a dependency is weak — it leaks
complexity upward without doing work.
When adding a public export, first ask whether an existing one can absorb
the new behavior. When removing, first ask whether the module has gone
shallow and should be inlined into its only caller.
## Dependency direction
Accept dependencies as arguments. Do not construct external clients,
fetch configuration, or read the clock inside business logic.
```ts
// strong: the caller owns lifecycle, the test swaps the gateway
function chargeOrder(order, gateway) { return gateway.charge(order.total); }
// weak: business logic welds itself to a vendor and a credential source
function chargeOrder(order) {
const gateway = new AcmePay(process.env.ACME_KEY);
return gateway.charge(order.total);
}
```
Return values, do not mutate inputs. `computeDiscount(cart) -> Discount`
beats `applyDiscount(cart) -> void`. Pure returns are traceable; hidden
mutation is not.
## Where mocks belong
Mock at system boundaries only: third-party HTTP APIs, databases when a
real test instance is not available, the clock, random sources, the
filesystem when tests must stay hermetic.
Do not mock your own modules, internal classes, or anything you can
instantiate cheaply. A test whose setup is twenty lines of mock wiring is
telling you the module underneath is too shallow — fix the shape, not
the test.
At the real boundaries, prefer **endpoint-shaped** mocks over generic
ones. `{ getUser(id), createOrder(data) }` beats `{ request(path, opts) }`
because each mock returns one shape, test setup contains no conditionals,
and a reader can see which calls a test exercises.
## Checklist when reviewing
- [ ] Does every public symbol justify its presence? Delete or merge the rest.
- [ ] Are dependencies passed in, or constructed inside?
- [ ] Do tests mock anything the module itself owns? If yes, the shape is wrong.
© Rohit Ghumare · MIT · rohitg00/pro-workflow