c4-architecture-c4-architecture
为现有代码库生成全面的C4架构文档,采用自底向上的分析方法,需按以下步骤系统执行: ### 一、准备阶段 1. **工具与环境配置** - 安装代码分析工具(如Doxygen、Sourcetrail、CodeMap) - 配置可视化工具(PlantUML、Structurizr、Draw.io) - 设置文档生成框架(AsciiDoc/Markdown模板) 2. **代码库扫描** - 运行静态分析工具提取: - 模块/包依赖关系 - 类/接口继承结构 - 方法调用链路 - 数据流路径 ### 二、自底向上分析流程 #### 第1层:代码组件分析 1. **识别基础构件** ```yaml 步骤: - 扫描所有源文件,识别: * 实体类(Entity) * 服务类(Service) * 控制器(Controller) * 数据访问对象(DAO) * 工具类(Utility) - 提取每个构件的: * 职责描述 * 接口定义 * 依赖项 * 代码复杂度指标 ``` 2. **生成组件清单** - 创建CSV/JSON格式的组件目录 - 标注技术栈(语言/框架版本) - 记录代码所有权信息 #### 第2层:容器级抽象 1. **逻辑分组** - 将相关组件聚类为: - 业务功能模块 - 技术支撑模块 - 第三方集成模块 2. **交互关系映射** - 绘制组件通信图: ```plantuml [Web前端] -> [API网关] [API网关] -> [用户服务] [用户服务] -> [数据库] ``` #### 第3层:系统级视图 1. **定义系统边界** - 识别外部依赖系统 - 划定系统上下文范围 2. **创建C4模型文档** - **上下文图**(Level 1): - 系统与用户/外部系统关系 - **容器图**(Level 2): - 应用程序/数据存储/消息队列等 - **组件图**(Level 3): - 各容器内部组件结构 - **代码图**(Level 4,可选): - 关键类的详细设计 ### 三、文档生成 #### 结构化文档模板 ```markdown # C4架构文档 ## 1. 系统上下文 ### 1.1 业务目标 ### 1.2 用户角色 ### 1.3 外部系统 ## 2. 容器视图 ### 2.1 技术选型说明 ### 2.2 容器职责表 ### 2.3 通信协议矩阵 ## 3. 组件视图 ### 3.1 模块分解图 ### 3.2 接口契约 ### 3.3 数据模型 ## 4. 部署视图 ### 4.1 基础设施图 ### 4.2 环境配置 ### 4.3 伸缩性设计 ## 5. 演进记录 ### 5.1 架构决策日志(ADR) ### 5.2 技术债务清单 ``` ### 四、自动化增强 1. **持续更新机制** - 集成CI/CD流水线: ```yaml steps: - 代码变更触发分析 - 自动更新依赖图 - 生成差异报告 ``` 2. **质量检查规则** - 架构一致性验证 - 循环依赖检测 - 文档完整性检查 ### 五、交付物清单 1. **核心产出** - 交互式架构图(HTML格式) - 结构化文档(PDF/Markdown) - 架构决策记录库 2. **辅助材料** - 组件字典(含代码示例) - 技术栈依赖矩阵 - 关键路径时序图 ### 最佳实践建议 1. **增量维护** - 每次重大变更后更新Level 3-4 - 每月复审Level 1-2 2. **协作规范** - 架构图版本控制 - 评审流程嵌入开发周期 - 文档与代码同仓库存储 3. **工具链推荐** - 代码分析:SonarQube + jQAssistant - 文档生成:Arc42 + Structurizr DSL - 可视化:Mermaid.js + Diagrams.net 此方法通过从代码细节出发逐步抽象,确保文档与实现严格对应,同时保持架构视图的业务可读性。建议配合架构验证测试(ArchUnit等)实现文档与代码的同步验证。
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
Do not use this skill when
Instructions
resources/implementation-playbook.md.Overview
This workflow creates comprehensive C4 architecture documentation following the official C4 model by:
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
1.2 Process Each Directory (Bottom-Up)
For each directory, starting from the deepest:
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
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
- 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:
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.
2.3 Create Master Component Index
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
Phase 3: Container-Level Synthesis
3.1 Analyze Components and Deployment 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
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
Phase 4: Context-Level Documentation
4.1 Analyze 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
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. [Step 1]: [Description]
2. [Step 2]: [Description]
...
- Include all system touchpoints
- For programmatic users (external systems, APIs):
- Integration journey with step-by-step process
5. External Systems and Dependencies Section:
- For each external system:
- System name
- Type (Database, API, Service, Message Queue, etc.)
- Description (what it provides)
- Integration type (API, Events, File Transfer, etc.)
- Purpose (why the system depends on this)
6. System Context Diagram:
- Mermaid C4Context diagram showing:
- The system (as a box in the center)
- All personas (users) around it
- All external systems around it
- Relationships and data flows
- Use C4Context notation for proper C4 diagram
7. Related Documentation Section:
- Links to container documentation
- Links to component documentation
Save the output as: C4-Documentation/c4-context.md
Ensure the documentation is:
- Understandable by non-technical stakeholders
- Focuses on system purpose, users, and external relationships
- Includes comprehensive user journey maps
- Identifies all external systems and dependencies
Configuration Options
target_directory: Root directory to analyze (default: current repository root)exclude_patterns: Patterns to exclude (default: node_modules, .git, build, dist, etc.)output_directory: Where to write C4 documentation (default: C4-Documentation/)include_tests: Whether to analyze test files for context (default: true)api_format: Format for API specs (default: openapi)Success Criteria
Output Structure
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
└── ...Coordination Notes
Example Usage
/c4-architecture:c4-architectureThis will:
All documentation written to: C4-Documentation/