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

c4-architecture · coco-research — скилл для Claude Code: диаграммы C4 в Mermaid

Скилл c4-architecture генерирует архитектурную документацию по модели C4: контекст системы, контейнеры, компоненты и деплоймент в формате Mermaid.

MIT ★ 328 обновлён 2026-10-29

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

Что делает c4-architecture

Скилл рисует четыре уровня диаграмм C4 — от контекста системы до развёртывания — и динамические диаграммы запросов. Каждый уровень нацелен на свою аудиторию: контекст читают все, контейнеры — технические роли, компоненты — только разработчики. Для большинства команд достаточно первых двух. Скилл анализирует кодовую базу, выбирает нужный уровень абстракции и пишет диаграммы в markdown.

Внутри — workflow из четырёх шагов и таблица с условиями, когда какой уровень создавать. Срабатывает на триггеры вроде «architecture diagram», «C4 diagram», «system context». Диаграммы компонентов рисует только если они реально добавляют ценность, а не по умолчанию.

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

  • нарисовать архитектуру системы по модели C4
  • документировать контейнеры, базы и очереди проекта
  • показать поток запроса через сервисы
  • визуализировать внешние зависимости и актёров
  • сгенерировать deployment-диаграмму для DevOps

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

  • Нарисуй C4 Context для этого репозитория
  • Создай Container Diagram: покажи фронтенд, API, базу PostgreSQL и Kafka
  • Построй динамическую диаграмму для процесса оформления заказа

Как установить c4-architecture

1Через Skills CLI (Vercel)

npx skills add coco-research/coco --skill c4-architecture -a claude-code

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

~/.claude/skills/c4-architecture/SKILL.md

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

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

Вопросы о c4-architecture

Как установить c4-architecture в Claude Code?

Выполни npx skills add coco-research/coco --skill c4-architecture -a claude-code, скилл окажется в ~/.claude/skills/c4-architecture/SKILL.md.

Что делает скилл c4-architecture?

Генерирует архитектурную документацию в виде диаграмм C4 (контекст, контейнеры, компоненты, деплоймент) в формате Mermaid. Анализирует кодовую базу и подбирает нужный уровень абстракции.

Когда рисовать Component Diagram?

Только если она добавляет ценность — для большинства команд хватает контекста и контейнеров. Компоненты рисуй, когда нужно показать внутреннее устройство конкретного модуля разработчикам.

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

SKILL.md · MIT
---
name: c4-architecture
description: "Generate architecture documentation using C4 model Mermaid diagrams. Use when asked to create architecture diagrams, document system architecture, visualize software structure, or generate context/container/component/deployment diagrams."
domain: engineering
supports: [claude-code, cursor, codex, generic]
version: 0.1.0
---

# C4 Architecture Documentation

Generate architecture documentation using C4 model Mermaid diagrams. Use when asked to create architecture diagrams, document system architecture, visualize software structure, create C4 diagrams, or generate context/container/component/deployment diagrams. Triggers include "architecture diagram", "C4 diagram", "system context", "container diagram", "component diagram", "deployment diagram", "document architecture", "visualize architecture".

## Workflow

1. **Understand scope** — Determine which C4 level(s) are needed based on audience
2. **Analyze codebase** — Explore the system to identify components, containers, and relationships
3. **Generate diagrams** — Create Mermaid C4 diagrams at appropriate abstraction levels
4. **Document** — Write diagrams to markdown files with explanatory context

## C4 Diagram Levels

Select the appropriate level based on the documentation need:

| Level | Diagram Type | Audience | Shows | When to Create |
|-------|-------------|----------|-------|----------------|
| 1 | **C4Context** | Everyone | System + external actors | Always (required) |
| 2 | **C4Container** | Technical | Apps, databases, services | Always (required) |
| 3 | **C4Component** | Developers | Internal components | Only if adds value |
| 4 | **C4Deployment** | DevOps | Infrastructure nodes | For production systems |
| - | **C4Dynamic** | Technical | Request flows (numbered) | For complex workflows |

**Key Insight:** "Context + Container diagrams are sufficient for most software development teams." Only create Component/Code diagrams when they genuinely add value.

## Quick Start Examples

### System Context (Level 1)
```mermaid
C4Context
  title System Context - Workout Tracker

  Person(user, "User", "Tracks workouts and exercises")
  System(app, "Workout Tracker", "Vue PWA for tracking strength and CrossFit workouts")
  System_Ext(browser, "Web Browser", "Stores data in IndexedDB")

  Rel(user, app, "Uses")
  Rel(app, browser, "Persists data to", "IndexedDB")
```

### Container Diagram (Level 2)

When the request names apps, services, workers, databases, or queues, draw each name as exactly one element: `Container` for an app, service, or worker; `ContainerDb` for a database or store; `ContainerQueue` for a queue or topic. Put that name in the label. Do not make it a `Container_Boundary` and do not invent inner containers or components. Pass only element aliases to `Rel`, never a boundary alias. Keep the request's direction: `A calls B`, `A writes to B`, `A reads B`, `A pulls from B`, `A drains B`, and `from A to B` are all `Rel(a, b, ...)`.

```mermaid
C4Container
  title Container Diagram - Checkout

  Container(shop, "Basket App", "React", "Places orders")
  Container(api, "Catalog API", "Java", "Accepts orders")
  ContainerDb(db, "Catalog DB", "PostgreSQL", "Product rows")
  ContainerQueue(bus, "Price Queue", "Kafka", "Price events")
  Container(worker, "Index Worker", "Java", "Updates search")

  Rel(shop, api, "Sends orders to", "JSON/HTTPS")
  Rel(api, db, "Writes to", "JDBC")
  Rel(api, bus, "Publishes to")
  Rel(bus, worker, "Delivers events to")
```

The workout diagram below breaks one app into internal containers. For a list of named containers, use the flat form above.

```mermaid
C4Container
  title Container Diagram - Workout Tracker

  Person(user, "User", "Tracks workouts")

  Container_Boundary(app, "Workout Tracker PWA") {
    Container(spa, "SPA", "Vue 3, TypeScript", "Single-page application")
    Container(pinia, "State Management", "Pinia", "Manages application state")
    ContainerDb(indexeddb, "IndexedDB", "Dexie", "Local workout storage")
  }

  Rel(user, spa, "Uses")
  Rel(spa, pinia, "Reads/writes state")
  Rel(pinia, indexeddb, "Persists", "Dexie ORM")
```

**Named parts are elements, not boundaries.** On `C4Container`, each app, service, worker, portal, console, screen, database, store, and queue the user names is one element. Put that exact name in the label:

- app, service, worker, portal, console, or screen → `Container(alias, "Name", "tech", "description")`
- database or store → `ContainerDb(alias, "Name", "tech", "description")`
- queue or topic → `ContainerQueue(alias, "Name", "tech", "description")`

Do not declare that name as `Container_Boundary` and do not nest `Component`s under it. A boundary cannot be a `Rel` endpoint. Aim the arrow with the sentence: "A calls B" / "A writes to B" → `Rel(a, b, "...")`; "events flow from the queue to the worker" → `Rel(queue, worker, "...")`; "the worker pulls or drains the queue" → `Rel(worker, queue, "...")`.

```mermaid
C4Container
  title Container Diagram - Parcel Desk
  Container(desk, "Desk App", "React", "Creates bookings")
  Container(api, "Booking API", "Go", "Reads and writes bookings")
  ContainerDb(db, "Booking DB", "PostgreSQL", "Booking records")
  ContainerQueue(q, "Job Queue", "SQS", "Booking events")
  Container(worker, "Ticket Worker", "Go", "Issues tickets")
  Rel(desk, api, "Calls", "JSON/HTTPS")
  Rel(api, db, "Reads and writes", "SQL")
  Rel(api, q, "Publishes events to")
  Rel(q, worker, "Delivers events to")
```

A container diagram declares each named app, service, worker, database, queue, or external system once: `Container`, `ContainerDb`, `ContainerQueue`, or `Container_Ext`, with that name as the label. `Rel` may use only those aliases, or `Person` for a human. Never pass a `Container_Boundary`, `System_Boundary`, or `Deployment_Node` alias — above, arrows go to `spa`, not `app`. Do not replace a named container with a boundary that holds some other element.

Invalid: `Container_Boundary(api, "Checkout API") { Container(handler, "Handler", "Node", "Handles calls") }` then `Rel(shop, api, "Calls")`.
Valid: `Container(shop, "Storefront", "React", "Takes orders")`, `Container(api, "Checkout API", "Node.js", "Validates orders")`, `ContainerDb(db, "Catalog DB", "PostgreSQL", "Product rows")`, `Rel(shop, api, "Submits orders", "JSON/HTTPS")`, `Rel(api, db, "Reads", "SQL")`.

### Component Diagram (Level 3)
```mermaid
C4Component
  title Component Diagram - Workout Feature

  Container(views, "Views", "Vue Router pages")

  Container_Boundary(workout, "Workout Feature") {
    Component(useWorkout, "useWorkout", "Composable", "Workout execution state")
    Component(useTimer, "useTimer", "Composable", "Timer state machine")
    Component(workoutRepo, "WorkoutRepository", "Dexie", "Workout persistence")
  }

  Rel(views, useWorkout, "Uses")
  Rel(useWorkout, useTimer, "Controls")
  Rel(useWorkout, workoutRepo, "Saves to")
```

### Dynamic Diagram (Request Flow)
```mermaid
C4Dynamic
  title Dynamic Diagram - User Sign In Flow

  ContainerDb(db, "Database", "PostgreSQL", "User credentials")
  Container(spa, "Single-Page App", "React", "Banking UI")

  Container_Boundary(api, "API Application") {
    Component(signIn, "Sign In Controller", "Express", "Auth endpoint")
    Component(security, "Security Service", "JWT", "Validates credentials")
  }

  Rel(spa, signIn, "1. Submit credentials", "JSON/HTTPS")
  Rel(signIn, security, "2. Validate")
  Rel(security, db, "3. Query user", "SQL")

  UpdateRelStyle(spa, signIn, $textColor="blue", $offsetY="-30")
```

### Deployment Diagram
```mermaid
C4Deployment
  title Deployment Diagram - Production

  Deployment_Node(browser, "Customer Browser", "Chrome/Firefox") {
    Container(spa, "SPA", "React", "Web application")
  }

  Deployment_Node(aws, "AWS Cloud", "us-east-1") {
    Deployment_Node(ecs, "ECS Cluster", "Fargate") {
      Container(api, "API Service", "Node.js", "REST API")
    }
    Deployment_Node(rds, "RDS", "db.r5.large") {
      ContainerDb(db, "Database", "PostgreSQL", "Application data")
    }
  }

  Rel(spa, api, "API calls", "HTTPS")
  Rel(api, db, "Reads/writes", "JDBC")
```

## Element Syntax

### People and Systems
```
Person(alias, "Label", "Description")
Person_Ext(alias, "Label", "Description")       # External person
System(alias, "Label", "Description")
System_Ext(alias, "Label", "Description")       # External system
SystemDb(alias, "Label", "Description")         # Database system
SystemQueue(alias, "Label", "Description")      # Queue system
```

### Containers
```
Container(alias, "Label", "Technology", "Description")
Container_Ext(alias, "Label", "Technology", "Description")
ContainerDb(alias, "Label", "Technology", "Description")
ContainerQueue(alias, "Label", "Technology", "Description")
```

### Components
```
Component(alias, "Label", "Technology", "Description")
Component_Ext(alias, "Label", "Technology", "Description")
ComponentDb(alias, "Label", "Technology", "Description")
```

### Boundaries
```
Enterprise_Boundary(alias, "Label") { ... }
System_Boundary(alias, "Label") { ... }
Container_Boundary(alias, "Label") { ... }
Boundary(alias, "Label", "type") { ... }
```

### Relationships
```
Rel(from, to, "Label")
Rel(from, to, "Label", "Technology")
BiRel(from, to, "Label")                        # Bidirectional
Rel_U(from, to, "Label")                        # Upward
Rel_D(from, to, "Label")                        # Downward
Rel_L(from, to, "Label")                        # Leftward
Rel_R(from, to, "Label")                        # Rightward
```

### Deployment Nodes
```
Deployment_Node(alias, "Label", "Type", "Description") { ... }
Node(alias, "Label", "Type", "Description") { ... }  # Shorthand
```

## Styling and Layout

### Layout Configuration
```
UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")
```
- `$c4ShapeInRow` — Number of shapes per row (default: 4)
- `$c4BoundaryInRow` — Number of boundaries per row (default: 2)

### Element Styling
```
UpdateElementStyle(alias, $fontColor="red", $bgColor="grey", $borderColor="red")
```

### Relationship Styling
```
UpdateRelStyle(from, to, $textColor="blue", $lineColor="blue", $offsetX="5", $offsetY="-10")
```
Use `$offsetX` and `$offsetY` to fix overlapping relationship labels.

## Best Practices

### Essential Rules

1. **Every element must have**: Name, Type, Technology (where applicable), and Description
2. **Use unidirectional arrows only** — Bidirectional arrows create ambiguity
3. **Label arrows with action verbs** — "Sends email using", "Reads from", not just "uses"
4. **Include technology labels** — "JSON/HTTPS", "JDBC", "gRPC"
5. **Stay under 20 elements per diagram** — Split complex systems into multiple diagrams

### Clarity Guidelines

1. **Start at Level 1** — Context diagrams help frame the system scope
2. **One diagram per file** — Keep diagrams focused on a single abstraction level
3. **Meaningful aliases** — Use descriptive aliases (e.g., `orderService` not `s1`)
4. **Concise descriptions** — Keep descriptions under 50 characters when possible
5. **Always include a title** — "System Context diagram for [System Name]"

### What to Avoid

See [references/common-mistakes.md](references/common-mistakes.md) for detailed anti-patterns:
- Confusing containers (deployable) vs components (non-deployable)
- Modeling shared libraries as containers
- Showing message brokers as single containers instead of individual topics
- Adding undefined abstraction levels like "subcomponents"
- Removing type labels to "simplify" diagrams

## Microservices Guidelines

### Single Team Ownership
Model each microservice as a **container** (or container group):
```mermaid
C4Container
  title Microservices - Single Team

  System_Boundary(platform, "E-commerce Platform") {
    Container(orderApi, "Order Service", "Spring Boot", "Order processing")
    ContainerDb(orderDb, "Order DB", "PostgreSQL", "Order data")
    Container(inventoryApi, "Inventory Service", "Node.js", "Stock management")
    ContainerDb(inventoryDb, "Inventory DB", "MongoDB", "Stock data")
  }
```

### Multi-Team Ownership
Promote microservices to **software systems** when owned by separate teams:
```mermaid
C4Context
  title Microservices - Multi-Team

  Person(customer, "Customer", "Places orders")
  System(orderSystem, "Order System", "Team Alpha")
  System(inventorySystem, "Inventory System", "Team Beta")
  System(paymentSystem, "Payment System", "Team Gamma")

  Rel(customer, orderSystem, "Places orders")
  Rel(orderSystem, inventorySystem, "Checks stock")
  Rel(orderSystem, paymentSystem, "Processes payment")
```

### Event-Driven Architecture
Show individual topics/queues as containers, NOT a single "Kafka" box:
```mermaid
C4Container
  title Event-Driven Architecture

  Container(orderService, "Order Service", "Java", "Creates orders")
  Container(stockService, "Stock Service", "Java", "Manages inventory")
  ContainerQueue(orderTopic, "order.created", "Kafka", "Order events")
  ContainerQueue(stockTopic, "stock.reserved", "Kafka", "Stock events")

  Rel(orderService, orderTopic, "Publishes to")
  Rel(stockService, orderTopic, "Subscribes to")
  Rel(stockService, stockTopic, "Publishes to")
  Rel(orderService, stockTopic, "Subscribes to")
```

## Output Location

Write architecture documentation to `docs/architecture/` with naming convention:
- `c4-context.md` — System context diagram
- `c4-containers.md` — Container diagram
- `c4-components-{feature}.md` — Component diagrams per feature
- `c4-deployment.md` — Deployment diagram
- `c4-dynamic-{flow}.md` — Dynamic diagrams for specific flows

## Audience-Appropriate Detail

| Audience | Recommended Diagrams |
|----------|---------------------|
| Executives | System Context only |
| Product Managers | Context + Container |
| Architects | Context + Container + key Components |
| Developers | All levels as needed |
| DevOps | Container + Deployment |

## References

- [references/c4-syntax.md](references/c4-syntax.md) — Complete Mermaid C4 syntax
- [references/common-mistakes.md](references/common-mistakes.md) — Anti-patterns to avoid
- [references/advanced-patterns.md](references/advanced-patterns.md) — Microservices, event-driven, deployment

© coco-research · MIT · coco-research/coco

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

Все скиллы по теме «DevOps и инфраструктура» →

Сначала — c4-architecture от других авторов.

c4-architecture microsoft Скилл c4-architecture строит диаграммы C4 по коду существующей системы или требованиям к новой. Помогает описать архитектуру на нужном уровне и подготовить исходник для Mermaid. CX Codex +1 ★ 1 627звёзд репо architecture-blueprint-generator официальный github Скилл architecture-blueprint-generator анализирует кодовую базу и готовит архитектурный blueprint с описанием компонентов, зависимостей и схемами. Нужен перед развитием проекта или вводом новых разработчиков. CX Codex +1 12 196установок architecture-diagrams aj-geddes Скилл architecture-diagrams помогает генерировать схемы архитектуры, потоки данных и C4-диаграммы в текстовом формате Mermaid или PlantUML. Пригодится при оформлении технической документации прямо в чате с агентом. CX Codex +1 2 000установок c4-context Seth Hobson Субагент c4-context для Claude Code описывает систему, пользователей и внешние зависимости в документации верхнего уровня по C4. Готовит контекстную диаграмму и карту пользовательских сценариев. CX Codex ★ 42 780звёзд репо c4-code Seth Hobson c4-code — субагент для Claude Code, который описывает структуру кода на уровне C4. Он включается при запросе документации для отдельных каталогов и модулей. CX Codex ★ 42 780звёзд репо c4-codebase-architecture lmammino Скилл c4-codebase-architecture для Claude Code разбирает репозиторий и собирает документацию по модели C4: контекст системы, контейнеры, компоненты. Помогает разобраться в чужом проекте или ввести в него новых людей. CX Codex +1 ★ 24звёзд репо mermaid-diagram-specialist davila7 Скилл mermaid-diagram-specialist генерирует диаграммы Mermaid прямо в Markdown: от блок-схем и ER-диаграмм до C4 и таймлайнов. Пригодится при составлении технической документации и проектировании архитектуры. CX Codex +1 145установок

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

Весь набор →
redesign-existing-projects Скилл redesign-existing-projects для Claude, который проходит по готовому сайту или приложению, находит типовые следы ИИ-дизайна и правит их в существующем стеке, не трогая логику. CX Codex +1 ★ 328звёзд репо database-architect Субагент database-architect помогает спроектировать схему данных, выбрать архитектуру БД и подготовить план миграции. Вызывайте его при работе с моделями данных, масштабированием или микросервисами. CX Codex ★ 328звёзд репо tailwind-patterns Скилл tailwind-patterns помогает настраивать Tailwind CSS v4 через CSS, собирать адаптивные макеты и проектировать дизайн-токены. Пригодится и при переносе проекта с v3. CX Codex +1 ★ 328звёзд репо create-subagent Скилл create-subagent помогает создавать изолированных субагентов с готовыми системными промптами для ревью кода, отладки и работы с данными. CX Codex +1 ★ 328звёзд репо create-skill Скилл create-skill помогает проектировать скиллы для ИИ-агентов: объясняет структуру каталогов, разметку SKILL.md и правила формулирования триггеров в описании. CX Codex +1 ★ 328звёзд репо ultra-think Скилл ultra-think для Claude Code разбирает архитектурные развилки с четырёх сторон, сравнивает подходы и выдаёт одну рекомендацию. CX Codex +1 ★ 328звёзд репо generate-tests Скилл generate-tests пишет тесты для файла, модуля или компонента, сначала определяя фреймворк и конвенции проекта. CX Codex +1 ★ 328звёзд репо m0-handoff Скилл m0-handoff сохраняет состояние сессии в STATE.md и локальный демон M0, чтобы продолжить работу после сжатия контекста или в другой сессии. CX Codex +1 ★ 328звёзд репо

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

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