c4-architecture-c4-architecture

rmyndharis/antigravity-skills

Генерация документации C4 по репозиторию методом анализа снизу вверх

Звёзды2 043
Авторrmyndharis

Установка

SKILL.md

C4 Architecture Documentation Workflow

Generate comprehensive C4 architecture documentation for an existing repository/codebase using a bottom-up analysis approach.

[Extended thinking: This workflow implements a complete C4 architecture documentation process following the C4 model (Context, Container, Component, Code). It uses a bottom-up approach, starting from the deepest code directories and working upward, ensuring every code element is documented before synthesizing into higher-level abstractions. The workflow coordinates four specialized C4 agents (Code, Component, Container, Context) to create a complete architectural documentation set that serves both technical and non-technical stakeholders.]

Use this skill when

  • Working on c4 architecture documentation workflow tasks or workflows
  • Needing guidance, best practices, or checklists for c4 architecture documentation workflow

Do not use this skill when

  • The task is unrelated to c4 architecture documentation workflow
  • You need a different domain or tool outside this scope

Instructions

  • Clarify goals, constraints, and required inputs.
  • Apply relevant best practices and validate outcomes.
  • Provide actionable steps and verification.

Overview

This workflow creates comprehensive C4 architecture documentation following the official C4 model by:

  1. Code Level: Analyzing every subdirectory bottom-up to create code-level documentation
  2. Component Level: Synthesizing code documentation into logical components within containers
  3. Container Level: Mapping components to deployment containers with API documentation (shows high-level technology choices)
  4. Context Level: Creating high-level system context with personas and user journeys (focuses on people and software systems, not technologies)

Note: According to the C4 model, you don't need to use all 4 levels of diagram - the system context and container diagrams are sufficient for most software development teams. This workflow generates all levels for completeness, but teams can choose which levels to use.

All documentation is written to a new C4-Documentation/ directory in the repository root.

Phase 1: Code-Level Documentation (Bottom-Up Analysis)

1.1 Discover All Subdirectories

  • Use codebase search to identify all subdirectories in the repository
  • Sort directories by depth (deepest first) for bottom-up processing
  • Filter out common non-code directories (node_modules, .git, build, dist, etc.)
  • Create list of directories to process

1.2 Process Each Directory (Bottom-Up)

For each directory, starting from the deepest:

  • Use Task tool with subagent_type="c4-architecture::c4-code"

  • Prompt: | Analyze the code in directory: [directory_path]

    Create comprehensive C4 Code-level documentation following this structure:

    1. Overview Section:<!-- -->
      • Name: [Descriptive name for this code directory]
      • Description: [Short description of what this code does]
      • Location: [Link to actual directory path relative to repo root]
      • Language: [Primary programming language(s) used]
      • Purpose: [What this code accomplishes]
    2. Code Elements Section:<!-- -->
      • Document all functions/methods with complete signatures:<!-- -->
        • Function name, parameters (with types), return type
        • Description of what each function does
        • Location (file path and line numbers)
        • Dependencies (what this function depends on)
      • Document all classes/modules:<!-- -->
        • Class name, description, location
        • Methods and their signatures
        • Dependencies
    3. Dependencies Section:<!-- -->
      • Internal dependencies (other code in this repo)
      • External dependencies (libraries, frameworks, services)
    4. Relationships Section:<!-- -->
      • Optional Mermaid diagram if relationships are complex

    Save the output as: C4-Documentation/c4-code-[directory-name].md Use a sanitized directory name (replace / with -, remove special chars) for the filename.

    Ensure the documentation includes:

    • Complete function signatures with all parameters and types
    • Links to actual source code locations
    • All dependencies (internal and external)
    • Clear, descriptive names and descriptions
  • Expected output: c4-code-<!-- --><directory-name><!-- -->.md file in C4-Documentation/

  • Context: All files in the directory and its subdirectories

Repeat for every subdirectory until all directories have corresponding c4-code-*.md files.

Phase 2: Component-Level Synthesis

2.1 Analyze All Code-Level Documentation

  • Collect all c4-code-*.md files created in Phase 1
  • Analyze code structure, dependencies, and relationships
  • Identify logical component boundaries based on:<!-- -->
    • Domain boundaries (related business functionality)
    • Technical boundaries (shared frameworks, libraries)
    • Organizational boundaries (team ownership, if evident)

2.2 Create Component Documentation

For each identified component:

  • Use Task tool with subagent_type="c4-architecture::c4-component"

  • Prompt: | Synthesize the following C4 Code-level documentation files into a logical component:

    Code files to analyze: [List of c4-code-*.md file paths]

    Create comprehensive C4 Component-level documentation following this structure:

    1. Overview Section:<!-- -->
      • Name: [Component name - descriptive and meaningful]
      • Description: [Short description of component purpose]
      • Type: [Application, Service, Library, etc.]
      • Technology: [Primary technologies used]
    2. Purpose Section:<!-- -->
      • Detailed description of what this component does
      • What problems it solves
      • Its role in the system
    3. Software Features Section:<!-- -->
      • List all software features provided by this component
      • Each feature with a brief description
    4. Code Elements Section:<!-- -->
      • List all c4-code-*.md files contained in this component
      • Link to each file with a brief description
    5. Interfaces Section:<!-- -->
      • Document all component interfaces:<!-- -->
        • Interface name
        • Protocol (REST, GraphQL, gRPC, Events, etc.)
        • Description
        • Operations (function signatures, endpoints, etc.)
    6. Dependencies Section:<!-- -->
      • Components used (other components this depends on)
      • External systems (databases, APIs, services)
    7. Component Diagram:<!-- -->
      • Mermaid diagram showing this component and its relationships

    Save the output as: C4-Documentation/c4-component-[component-name].md Use a sanitized component name for the filename.

  • Expected output: c4-component-<!-- --><name><!-- -->.md file for each component

  • Context: All relevant c4-code-*.md files for this component

2.3 Create Master Component Index

  • Use Task tool with subagent_type="c4-architecture::c4-component"

  • Prompt: | Create a master component index that lists all components in the system.

    Based on all c4-component-*.md files created, generate:

    1. System Components Section:<!-- -->
      • List all components with:<!-- -->
        • Component name
        • Short description
        • Link to component documentation
    2. Component Relationships Diagram:<!-- -->
      • Mermaid diagram showing all components and their relationships
      • Show dependencies between components
      • Show external system dependencies

    Save the output as: C4-Documentation/c4-component.md

  • Expected output: Master c4-component.md file

  • Context: All c4-component-*.md files

Phase 3: Container-Level Synthesis

3.1 Analyze Components and Deployment Definitions

  • Review all c4-component-*.md files
  • Search for deployment/infrastructure definitions:<!-- -->
    • Dockerfiles
    • Kubernetes manifests (deployments, services, etc.)
    • Docker Compose files
    • Terraform/CloudFormation configs
    • Cloud service definitions (AWS Lambda, Azure Functions, etc.)
    • CI/CD pipeline definitions

3.2 Map Components to Containers

  • Use Task tool with subagent_type="c4-architecture::c4-container"

  • Prompt: | Synthesize components into containers based on deployment definitions.

    Component documentation: [List of all c4-component-*.md file paths]

    Deployment definitions found: [List of deployment config files: Dockerfiles, K8s manifests, etc.]

    Create comprehensive C4 Container-level documentation following this structure:

    1. Containers Section (for each container):<!-- -->
      • Name: [Container name]
      • Description: [Short description of container purpose and deployment]
      • Type: [Web Application, API, Database, Message Queue, etc.]
      • Technology: [Primary technologies: Node.js, Python, PostgreSQL, etc.]
      • Deployment: [Docker, Kubernetes, Cloud Service, etc.]
    2. Purpose Section (for each container):<!-- -->
      • Detailed description of what this container does
      • How it's deployed
      • Its role in the system
    3. Components Section (for each container):<!-- -->
      • List all components deployed in this container
      • Link to component documentation
    4. Interfaces Section (for each container):<!-- -->
      • Document all container APIs and interfaces:<!-- -->
        • API/Interface name
        • Protocol (REST, GraphQL, gRPC, Events, etc.)
        • Description
        • Link to OpenAPI/Swagger/API Spec file
        • List of endpoints/operations
    5. API Specifications:<!-- -->
      • For each container API, create an OpenAPI 3.1+ specification
      • Save as: C4-Documentation/apis/[container-name]-api.yaml
      • Include:<!-- -->
        • All endpoints with methods (GET, POST, etc.)
        • Request/response schemas
        • Authentication requirements
        • Error responses
    6. Dependencies Section (for each container):<!-- -->
      • Containers used (other containers this depends on)
      • External systems (databases, third-party APIs, etc.)
      • Communication protocols
    7. Infrastructure Section (for each container):<!-- -->
      • Link to deployment config (Dockerfile, K8s manifest, etc.)
      • Scaling strategy
      • Resource requirements (CPU, memory, storage)
    8. Container Diagram:<!-- -->
      • Mermaid diagram showing all containers and their relationships
      • Show communication protocols
      • Show external system dependencies

    Save the output as: C4-Documentation/c4-container.md

  • Expected output: c4-container.md with all containers and API specifications

  • Context: All component documentation and deployment definitions

Phase 4: Context-Level Documentation

4.1 Analyze System Documentation

  • Review container and component documentation
  • Search for system documentation:<!-- -->
    • README files
    • Architecture documentation
    • Requirements documents
    • Design documents
    • Test files (to understand system behavior)
    • API documentation
    • User documentation

4.2 Create Context Documentation

  • Use Task tool with subagent_type="c4-architecture::c4-context"

  • Prompt: | Create comprehensive C4 Context-level documentation for the system.

    Container documentation: C4-Documentation/c4-container.md Component documentation: C4-Documentation/c4-component.md System documentation: [List of README, architecture docs, requirements, etc.] Test files: [List of test files that show system behavior]

    Create comprehensive C4 Context-level documentation following this structure:

    1. System Overview Section:<!-- -->
      • Short Description: [One-sentence description of what the system does]
      • Long Description: [Detailed description of system purpose, capabilities, problems solved]
    2. Personas Section:<!-- -->
      • For each persona (human users and programmatic "users"):<!-- -->
        • Persona name
        • Type (Human User / Programmatic User / External System)
        • Description (who they are, what they need)
        • Goals (what they want to achieve)
        • Key features used
    3. System Features Section:<!-- -->
      • For each high-level feature:<!-- -->
        • Feature name
        • Description (what this feature does)
        • Users (which personas use this feature)
        • Link to user journey map
    4. User Journeys Section:<!-- -->
      • For each key feature and persona:<!-- -->
        • Journey name: [Feature Name] - [Persona Name] Journey
        • Step-by-step journey:<!-- -->
          1. ...
        • Include all system touchpoints
      • Для программных пользователей (внешние системы, API):
        • Путь интеграции с пошаговым процессом
    5. Раздел внешних систем и зависимостей:<!-- -->
      • Для каждой внешней системы:
        • Имя системы
        • Тип (база данных, API, сервис, очередь сообщений и т. д.)
        • Описание (что она предоставляет)
        • Тип интеграции (API, события, передача файлов и т. д.)
        • Назначение (почему система зависит от этого)
    6. Диаграмма контекста системы:<!-- -->
      • Диаграмма Mermaid C4Context, показывающая:
        • Систему (в виде блока в центре)
        • Все персоны (пользователи) вокруг неё
        • Все внешние системы вокруг неё
        • Связи и потоки данных
        • Используйте нотацию C4Context для корректной C4-диаграммы
    7. Раздел связанной документации:<!-- -->
      • Ссылки на документацию контейнеров
      • Ссылки на документацию компонентов

    Сохраните результат как: C4-Documentation/c4-context.md

    Убедитесь, что документация:

    • Понятна нетехническим заинтересованным сторонам
    • Сфокусирована на назначении системы, пользователях и внешних связях
    • Включает исчерпывающие карты пользовательских путей
    • Определяет все внешние системы и зависимости
  • Ожидаемый результат: c4-context.md с полным контекстом системы

  • Контекст: вся документация контейнеров, компонентов и системы

Параметры конфигурации

  • target_directory: Корневой каталог для анализа (по умолчанию: корень текущего репозитория)
  • exclude_patterns: Шаблоны для исключения (по умолчанию: node_modules, .git, build, dist и т. д.)
  • output_directory: Куда записывать документацию C4 (по умолчанию: C4-Documentation/)
  • include_tests: Анализировать ли тестовые файлы для контекста (по умолчанию: true)
  • api_format: Формат для спецификаций API (по умолчанию: openapi)

Критерии успеха

  • ✅ Каждый подкаталог имеет соответствующий файл c4-code-*.md
  • ✅ Вся документация уровня кода включает полные сигнатуры функций
  • ✅ Компоненты логически сгруппированы с чёткими границами
  • ✅ Все компоненты имеют документацию интерфейсов
  • ✅ Создан главный индекс компонентов с диаграммой связей
  • ✅ Контейнеры соответствуют фактическим единицам развёртывания
  • ✅ Все API контейнеров задокументированы со спецификациями OpenAPI/Swagger
  • ✅ Диаграмма контейнеров показывает архитектуру развёртывания
  • ✅ Контекст системы включает все персоны (человеческие и программные)
  • ✅ Пользовательские пути задокументированы для всех ключевых функций
  • ✅ Определены все внешние системы и зависимости
  • ✅ Диаграмма контекста показывает систему, пользователей и внешние системы
  • ✅ Документация организована в каталоге C4-Documentation/

Структура выходных данных

C4-Documentation/
├── c4-code-*.md              # Code-level docs (one per directory)
├── c4-component-*.md          # Component-level docs (one per component)
├── c4-component.md            # Master component index
├── c4-container.md            # Container-level docs
├── c4-context.md              # Context-level docs
└── apis/                      # API specifications
    ├── [container]-api.yaml   # OpenAPI specs for each container
    └── ...

Заметки о координации

  • Обработка снизу вверх: Обрабатывайте каталоги от самых глубоких к самым верхним
  • Инкрементальный синтез: Каждый уровень строится на документации предыдущего уровня
  • Полный охват: Каждый каталог должен иметь документацию уровня кода перед синтезом
  • Согласованность ссылок: Все файлы документации должны соответствующим образом ссылаться друг на друга
  • Документация API: API контейнеров должны иметь спецификации OpenAPI/Swagger
  • Дружелюбность к заинтересованным сторонам: Документация контекста должна быть понятна нетехническим заинтересованным сторонам
  • Диаграммы Mermaid: Используйте правильную нотацию C4 Mermaid для всех диаграмм

Пример использования

/c4-architecture:c4-architecture

Это позволит:

  1. Пройти по всем подкаталогам снизу вверх
  2. Создать c4-code-*.md для каждого каталога
  3. Синтезировать в компоненты
  4. Сопоставить с контейнерами с документацией API
  5. Создать контекст системы с персонами и путями

Вся документация записана в: C4-Documentation/

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: c4-architecture-c4-architecture](https://darkplay.ru/ai/skills/rmyndharis-antigravity-skills-c4-architecture-c4-architecture)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Architectaffaan-m · Специалист по архитектуре ПО для проектирования систем, масштабируемости и принятия…
225 587 ★
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
225 587 ★
Code Exploreraffaan-m · Глубоко анализирует существующие функции кодовой базы, прослеживая пути выполнения…
225 587 ★
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
225 587 ★
Java Revieweraffaan-m · Ревьюер Java для Spring Boot и Quarkus: архитектура, JPA, безопасность и конкурентность.
225 587 ★
Kotlin Revieweraffaan-m · Ревьюер Kotlin и Android/KMP: корутины, Compose, архитектура и типичные ошибки.
225 587 ★
Network Architectaffaan-m · Проектирует корпоративные и распределённые сети с маршрутизацией и автоматизацией.
225 587 ★
Vue Revieweraffaan-m · Ревьюер Vue.js: Composition API, реактивность, архитектура компонентов, Pinia, Nuxt.
225 587 ★
feature-devanthropics · Полный рабочий процесс разработки функций со специализированными агентами для изучения…
34 комп.
ruflo-adrruvnet · Управление жизненным циклом ADR: создание, индексация, замена и связывание Architecture…
240 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

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

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8