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

convention-learner — скилл для Claude Code: учит стиль проекта

Разбирает существующий код и выводит из него правила проекта: имена, структуру папок, оформление тестов. Пригодится, когда агент пишет код не в том стиле.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add codewithmukesh/dotnet-claude-kit --skill convention-learner -a claude-code
Открыть на GitHub

Что делает convention-learner

Скилл сначала смотрит на код, а потом что-то требует. Он проходит по проекту и собирает сводку: как называются классы и файлы, где лежат фичи, как организованы тесты, какие правила уже прописаны в .editorconfig и Directory.Build.props. Только после этого он применяет найденное к новому коду.

Внутри — пошаговый разбор: граф проекта, публичный API нескольких ключевых типов, структура папок, файлы конфигурации. Результат складывается в отчёт с разделами про имена, структуру и стиль. Дальше скилл предлагает дописать найденные правила в CLAUDE.md, чтобы они не потерялись.

Главная оговорка: явные правила проекта всегда сильнее дефолтов набора. Если в .editorconfig стоит csharp_style_expression_bodied_methods = false, скилл не будет навязывать обратное. И наоборот: проект на 200 обработчиков internal sealed class не получит новый public class. Это повод проверить свои конфиги перед первым запуском.

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

  • выяснить, какие соглашения уже приняты в чужом проекте
  • писать новый код в стиле существующих обработчиков и DTO
  • найти отклонения от стиля при ревью
  • подобрать правила .editorconfig под фактический код
  • зафиксировать договорённости в CLAUDE.md, пока авторы на месте

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

  • Изучи соглашения проекта и опиши их: имена, структуру папок, оформление тестов
  • Сгенерируй CreateProductHandler так, чтобы он совпадал со стилем остальных обработчиков
  • Проверь этот файл на отклонения от соглашений проекта

Как установить convention-learner

1Через Skills CLI (Vercel)

npx skills add codewithmukesh/dotnet-claude-kit --skill convention-learner -a claude-code

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

~/.claude/skills/convention-learner/SKILL.md

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

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

Вопросы о convention-learner

Как установить convention-learner в Claude?

Выполните npx skills add codewithmukesh/dotnet-claude-kit --skill convention-learner -a claude-code. Скилл окажется в ~/.claude/skills/convention-learner/SKILL.md.

Что делает convention-learner?

Анализирует существующий код и выводит из него соглашения проекта: имена типов, структуру папок, организацию тестов, стиль. Потом применяет их при генерации и ревью кода.

Что будет, если правила проекта расходятся с настройками набора?

Побеждают правила проекта. Явные записи в .editorconfig и Directory.Build.props скилл не переопределяет, даже если дефолт набора другой.

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

SKILL.md · MIT
---
name: convention-learner
description: >
  Detects and enforces project-specific coding conventions by analyzing
  existing codebase patterns. Learns naming conventions, folder structure,
  test organization, and coding style from the existing code.
  Load when: "conventions", "coding standards", "project patterns",
  "enforce style", "detect patterns", "learn conventions", "code consistency".
---

# Convention Learner

## Core Principles

1. **Observe before enforcing** — Never impose conventions without first analyzing the existing codebase. A project with 200 `internal sealed class` handlers should not get a new `public class` handler. Detect first, then match.
2. **Project conventions override generic rules** — If the project uses `*Service` instead of `*Handler`, follow the project's convention even if the kit default is different. Explicit `.editorconfig` and `Directory.Build.props` rules always win.
3. **Use MCP tools for analysis** — `get_public_api` reveals naming patterns, `get_project_graph` shows structure conventions, `detect_antipatterns` tracks quality trends. Tools provide objective data; file reads provide confirmation.
4. **Document findings** — After detecting conventions, suggest adding them to the project's CLAUDE.md. Undocumented conventions are lost when the original developers leave.
5. **Consistency over perfection** — A project with consistent `snake_case` database columns is better than a project with half `snake_case` and half `PascalCase`. Match the existing pattern, even if another convention is theoretically superior.

## Patterns

### Convention Detection Flow

Systematic analysis to understand a project's coding conventions. Run this when joining an existing project or before generating new code.

**Step 1: Project Structure Analysis**
```
→ get_project_graph
  Detect:
  - Project naming: PascalCase? Dots? (MyApp.Domain vs Domain)
  - Layer organization: by layer (Domain/Application/Infrastructure) or by feature?
  - Test project naming: *.Tests, *.UnitTests, *.IntegrationTests?
  - Shared project: Common/, Shared/, BuildingBlocks/?
```

**Step 2: Type Naming Patterns**
```
→ get_public_api (on 3-5 key types across different layers)
  Detect:
  - Class modifiers: sealed? internal? internal sealed?
  - Interface prefix: I* (standard) or no prefix?
  - Suffix conventions: Handler, Service, Repository, Validator, Endpoint?
  - Record usage: for DTOs? for value objects? for commands/queries?
  - Primary constructor usage: consistently? selectively?
```

**Step 3: Folder Structure Patterns**
Scan the file system for structural conventions:
- Feature folders: `Features/{FeatureName}/` with all files together?
- Layer folders: `Controllers/`, `Services/`, `Repositories/` separate?
- Shared patterns: `Common/`, `Extensions/`, `Middleware/`?
- Configuration location: root? `Config/` folder? `Infrastructure/`?

**Step 4: Configuration Detection**
Check for explicit convention enforcers:

```
→ Look for Directory.Build.props
  - TreatWarningsAsErrors?
  - Nullable enabled globally?
  - ImplicitUsings?
  - AnalysisLevel?

→ Look for .editorconfig
  - Naming rules: camelCase fields? _prefixed privates?
  - Code style: var preferences, expression bodies, using placement

→ Look for global.json
  - SDK version pinned?
  - Roll-forward policy?
```

**Step 5: Build Convention Summary**
Compile findings into a structured summary:

```markdown
## Detected Conventions

### Naming
- Classes: `internal sealed class` (95% of handlers/services)
- Suffixes: Handlers end in `Handler`, validators in `Validator`
- Records: Used for DTOs and commands/queries

### Structure
- Architecture: Vertical Slice Architecture
- Features: `Features/{Name}/` with command, handler, validator, endpoint in one file

### Code Style
- Primary constructors: Used consistently for DI injection
- Nullable: Enabled globally, no suppressions (`!`) used
- File-scoped namespaces: 100% consistent
```

Add categories as needed: EF Core (configurations, naming, migrations), Testing (framework, naming, fixtures), etc.

### Convention Enforcement

Apply detected conventions when generating new code or reviewing existing code.

**When Generating Code:**
Match every detected pattern:

```csharp
// If existing handlers are: internal sealed class + primary constructor
// Generate matching:
internal sealed class CreateProductHandler(AppDbContext db, TimeProvider clock)
{
    // Not: public class CreateProductHandler
    // Not: internal class CreateProductHandler (missing sealed)
}
```

```csharp
// If existing DTOs are records with init properties
// Generate matching:
public record ProductResponse(Guid Id, string Name, decimal Price);
// Not: public class ProductResponse { public Guid Id { get; set; } }
```

**When Reviewing Code:**
Flag deviations from detected conventions:

```
⚠️ Convention violation: CreateOrderHandler is `public class` but project convention
   is `internal sealed class` (detected in 12/12 existing handlers).
   Change to: internal sealed class CreateOrderHandler
```

**Suggesting Enforcement Rules:**
After detecting conventions, suggest `.editorconfig` rules to enforce them automatically:

```ini
# Key .editorconfig rules to suggest based on detected conventions
dotnet_diagnostic.CA1852.severity = warning           # Seal internal types
csharp_style_namespace_declarations = file_scoped:warning
csharp_style_prefer_primary_constructors = true:suggestion
# Add dotnet_naming_rule entries for private field prefix (_camelCase) if detected
```

### Anti-pattern Tracking

Use `detect_antipatterns` to track recurring quality issues across sessions.

**Periodic Check:**
```
→ detect_antipatterns (scope: solution)
  Track over time:
  - Are the same patterns recurring? (DateTime.Now keeps appearing)
  - Are new patterns emerging? (new HttpClient() in a new module)
  - Is the count trending up or down?
```

**Prioritization:**
```
| Anti-pattern | Count | Trend | Priority |
|-------------|-------|-------|----------|
| DateTime.Now | 12 | ↑ +3 | High — add to CLAUDE.md conventions |
| async void | 1 | → same | Medium — one-off fix |
| new HttpClient | 0 | ↓ -2 | Low — already fixing |
```

When patterns recur, add explicit rules to CLAUDE.md:
```markdown
## Conventions
- **NEVER use DateTime.Now** — Use TimeProvider.GetUtcNow() (12 violations found, fixing)
```

## Anti-patterns

### Enforcing Without Detecting

```
# BAD — Imposing kit defaults on a project with its own conventions
"All handlers should be internal sealed class"
# But this project uses public class with interfaces for testing
```

```
# GOOD — Detect first, then follow what exists
→ get_public_api reveals: 8/8 handlers are `public class` implementing `IHandler<T>`
"This project uses public handlers with interfaces. Matching that convention."
```

### Overriding Explicit Project Rules

```
# BAD — Ignoring .editorconfig because kit says otherwise
# .editorconfig says: csharp_style_expression_bodied_methods = false
# But generating expression-bodied methods anyway
```

```
# GOOD — .editorconfig and Directory.Build.props always win
"Your .editorconfig disables expression-bodied methods.
I'll use block-bodied methods to match your project settings."
```

### Applying Generic Conventions to Unconventional Projects

```
# BAD — Forcing Clean Architecture naming on a VSA project
"You need a Services/ folder and a Repositories/ folder"
# But this project uses feature folders with everything co-located
```

```
# GOOD — Match the project's organizational convention
"This project uses feature folders. I'll add the new feature
at Features/Shipping/ with all related files together."
```

### Documenting Conventions Without Evidence

```
# BAD — "Conventions" based on reading one file
"Convention: Use var everywhere" (based on seeing var in one method)
```

```
# GOOD — Document only patterns confirmed across multiple files
→ get_public_api on 5 types: 100% use explicit types for non-obvious cases
"Convention: Use explicit types for non-obvious cases (e.g., method returns),
var for obvious cases (e.g., new MyClass()). Confirmed across 5 files."
```

## Decision Guide

| Scenario | Action | Tool |
|----------|--------|------|
| Joining existing project | Run full convention detection flow | get_project_graph, get_public_api |
| Generating new code | Check detected conventions first | Previous detection results |
| Reviewing code | Flag convention deviations | get_public_api + comparison |
| Convention conflict (kit vs project) | **Project wins** | — |
| Convention conflict (team disagreement) | Document both, suggest .editorconfig | — |
| No conventions detected | Use kit defaults, document them | architecture-advisor skill |
| Recurring anti-pattern | Add to CLAUDE.md conventions | detect_antipatterns |
| New team member onboarding | Run detection, generate convention doc | Full detection flow |
| .editorconfig exists | Trust it, don't override | Read .editorconfig |
| No .editorconfig | Suggest creating one based on detected patterns | Detection + generation |
| Pattern seen once | Create instinct at 0.3 confidence via `instinct-system` skill | instinct-system |
| Pattern confirmed 3+ times | Instinct auto-promotes to 0.7, suggest adding to CLAUDE.md | instinct-system |

© codewithmukesh · MIT · codewithmukesh/dotnet-claude-kit

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

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
code-style-consistency-cursorrules-prompt-file PatrickJS Правило заставляет агента сначала изучить стиль проекта, а потом писать код под него. Пригодится, когда в репозитории уже есть свои конвенции. ★ 41 011звёзд репо konsistent-config vercel-labs Настраивает правила структуры проекта в konsistent.json для кодовой базы на TypeScript. Помогает зафиксировать файловые паттерны, форматы импортов и экспортов. CX Codex +1 2 500установок go-naming cxuu Скилл следит за именами в Go: пакеты, типы, функции, константы, получатели. Пригодится, когда агент создаёт новые типы или экспортируемое API. CX Codex +1 1 200установок rust-learner actionbook Скилл находит актуальные версии крейтов, разбирает документацию docs.rs, списки изменений Rust и правила Clippy прямо во время сессии с агентом. CX Codex +1 3 100установок golang-code-style samber Скилл помогает писать понятный код на Go, разбирая правила длины строк, объявления переменных, управления потоком выполнения и комментариев. Пригодится при написании и ревью кода, обсуждении стилистики или установке стандартов проекта. CX Codex +1 44 200установок learn giuseppe-trisciuoglio Анализирует кодовую базу, находит правила разработки и создаёт готовые инструкции в .claude/rules/. Пригодится при входе в незнакомый репозиторий. CX Codex +1 3 300установок

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

instinct-system Фиксирует паттерны, правки пользователя и находки в файлах проекта. Нужен, когда агенту надо учиться на повторяющихся решениях. CX Codex +1 2 800установок container-publish Собирает OCI-образы прямо из dotnet publish /t:PublishContainer, без Dockerfile. Пригодится, когда проект на .NET 10 надо упаковать в контейнер и запушить в реестр. CX Codex +1 2 800установок workflow-mastery Набор практик и готовых конфигураций для ускорения разработки на .NET в Claude Code. Помогает настроить параллельные сессии через git worktree, циклы верификации и лимиты контекста. CX Codex +1 2 800установок aspire Помогает настроить .NET Aspire для локального запуска сервисов, ресурсов и обнаружения сервисов. Нужен при работе с AppHost и общими настройками сервисов. CX Codex +1 2 800установок api-versioning Направляет агента при версионировании ASP.NET Core API через библиотеку Asp.Versioning. Помогает настроить пути, заголовки и мягкую депрекацию устаревших версий. CX Codex +1 2 800установок caching Настраивает кеширование в приложениях .NET 10: HybridCache, кеш ответов и распределённый кеш. Нужен при снижении нагрузки на базу данных и настройке инвалидации. CX Codex +1 2 800установок health-check Прогоняет .NET-проект по восьми осям и ставит буквенные оценки A–F с общим GPA. Пригодится при онбординге, перед релизом и после уборки кода. CX Codex +1 2 800установок openapi Настраивает встроенную генерацию спецификаций OpenAPI в .NET 10 без Swashbuckle. Помогает агенту писать трансформеры, метаданные и схемы безопасности. CX Codex +1 2 800установок

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

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