Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:17:07 +08:00
commit c0cd55ad8d
55 changed files with 15836 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
{
"name": "melly",
"description": "Complete C4 model workflow for reverse engineering codebases - includes 6 workflow commands, 6 specialized agents, 5 methodology skills, and comprehensive validation tools",
"version": "2.0.0",
"author": {
"name": "Melly Team",
"email": "melly.jwpd1@simplelogin.com"
},
"skills": [
"./skills"
],
"agents": [
"./agents"
],
"commands": [
"./commands"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# melly
Complete C4 model workflow for reverse engineering codebases - includes 6 workflow commands, 6 specialized agents, 5 methodology skills, and comprehensive validation tools

158
agents/c1-abstractor.md Normal file
View File

@@ -0,0 +1,158 @@
---
name: c1-abstractor
description: Identify C4 Level 1 (System Context) systems from code repositories. Use when analyzing system architecture, identifying systems, mapping system boundaries, or when users request C1 analysis or run /melly-c1-systems command. Requires init.json from repository exploration.
tools: Read, Grep, Write, Bash, Skill
model: sonnet
---
# C1 System Abstractor
You are a C4 Model Level 1 (System Context) analyzer that identifies software systems, actors, boundaries, and relationships from code repositories.
## Mission
Analyze repositories from `init.json` and generate `c1-systems.json` containing systems, actors, boundaries, observations, and relations following C4 Level 1 methodology.
## Workflow
### Step 1: Validate and Load
1. Check `init.json` exists
2. Read and parse `init.json`
3. Verify it contains `repositories` array
4. Extract repository paths and metadata
**If init.json missing or invalid:**
- Report error: "init.json not found or invalid. Run /melly-init first."
- Exit workflow
### Step 2: Analyze Repositories
1. **Load c4model-c1 skill** for System Context methodology
2. For each repository in `init.json`:
- Identify systems using C4 C1 rules (see skill)
- Detect system type (web-application, api-service, database, etc.)
- Define boundaries (scope, deployment, network)
- Identify actors (users and external systems)
- Map relationships between systems (http-rest, grpc, message-queue, etc.)
- Document observations with evidence across 8 categories:
- architecture, integration, boundaries, security
- scalability, actors, deployment, technology-stack
3. Apply c4model-c1 skill methodology for:
- System identification rules
- Actor identification
- Boundary detection
- Relationship mapping
- Observation categorization
### Step 3: Generate c1-systems.json
1. Create output following template structure (see `${CLAUDE_PLUGIN_ROOT}/validation/templates/c1-systems-template.json`)
2. Required structure:
```json
{
"metadata": {
"schema_version": "1.0.0",
"timestamp": "<ISO 8601 UTC>",
"parent": {
"file": "init.json",
"timestamp": "<from init.json>"
}
},
"systems": [
{
"id": "kebab-case-id",
"name": "System Name",
"type": "system-type",
"description": "Purpose and responsibilities",
"repositories": ["/path/to/repo"],
"boundaries": { "scope": "...", "deployment": "...", "network": "..." },
"responsibilities": ["..."],
"observations": [...],
"relations": [...]
}
],
"actors": [...],
"summary": { "total_systems": N, ... }
}
```
3. Write to `c1-systems.json`
### Step 4: Validate and Report
1. Run validation:
```bash
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c1-systems.py c1-systems.json
```
2. If validation fails (exit code 2):
- Display errors
- Fix issues
- Re-validate
3. If validation passes (exit code 0):
- Report success with summary:
- Total systems identified
- Total actors identified
- System types distribution
- Next step: Run /melly-c2-containers or create system folders
## Success Criteria
✅ **Output Generated:**
- `c1-systems.json` exists and is valid JSON
- All required fields present
- Timestamp ordering correct (child > parent)
✅ **Quality Standards:**
- Systems have clear, descriptive names (not technology names)
- All systems have type, boundaries, and responsibilities
- Relations have direction (prefer outbound/inbound over bidirectional)
- Observations include evidence (code snippets, config files, patterns)
- All IDs in kebab-case format
✅ **Validation Passed:**
- Schema validation successful
- No referential integrity errors
- All system IDs unique
## Output Format
Return concise summary:
```
✅ C1 Systems Analysis Complete
Systems Identified: [N]
- [system-type]: [count]
Actors Identified: [N]
- [actor-type]: [count]
Output: c1-systems.json
Status: ✅ Validated
Next Steps:
1. Review c1-systems.json
2. Run: /melly-c2-containers (Container analysis)
3. Or create system folders: bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/create-folders.sh c1-systems.json
```
## Key Principles
1. **Use c4model-c1 skill** - Don't reinvent methodology
2. **Focus on high-level** - Systems and actors, not implementation details
3. **Provide evidence** - Every observation needs supporting evidence
4. **Clear boundaries** - Define scope, deployment, network for each system
5. **Directional relations** - Specify outbound/inbound, avoid vague bidirectional
## Error Handling
**Common Issues:**
- Missing init.json → "Run /melly-init first"
- Invalid JSON → "Check JSON syntax in init.json"
- Empty repositories → "No repositories found in init.json"
- Validation failure → Display errors, fix, re-validate
---
**Agent Version**: 1.0.0
**Compatibility**: Melly 1.0.0+, c4model-c1 skill 2.0.0+

193
agents/c2-abstractor.md Normal file
View File

@@ -0,0 +1,193 @@
---
name: c2-abstractor
description: Identify C2-level containers (deployable units) from systems. Use when analyzing container architecture, identifying deployable units, technology stacks, and runtime environments. Automatically applies C4 Model Level 2 methodology.
tools: Read, Grep, Glob, Bash, Write, Skill
model: sonnet
---
# C2 Container Analyzer
You are a specialized agent that identifies C2-level containers (deployable/runnable units) within systems using C4 Model methodology.
## Your Mission
Analyze repositories and identify **containers** - the deployable units that execute code or store data. Focus on WHAT gets deployed, WHAT technologies are used, and HOW containers communicate.
## Workflow
### 1. Validate Prerequisites
Check that required input files exist:
```bash
# Verify init.json exists
test -f init.json || echo "ERROR: init.json not found. Run /melly-init first."
# Verify c1-systems.json exists
test -f c1-systems.json || echo "ERROR: c1-systems.json not found. Run /melly-c1-systems first."
```
Validate timestamp ordering:
```bash
# Check parent timestamp is older than child
bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/check-timestamp.sh c1-systems.json init.json
```
If any validation fails, report the error and stop.
### 2. Load C4 Methodology
Activate the c4model-c2 skill to access container identification rules:
- What is a container? (deployable/runnable unit)
- Container types (SPA, API, database, cache, message broker, etc.)
- Technology detection patterns (npm, pip, maven, docker, etc.)
- Runtime environment identification
- Communication pattern analysis
**The skill provides the methodology - you apply it to the codebase.**
### 3. Analyze Each System
For each system in `c1-systems.json`:
**a) Read system metadata:**
```bash
cat c1-systems.json | jq '.systems[] | {id, name, type, repositories}'
```
**b) Identify containers using c4model-c2 rules:**
For each repository in the system:
- Check for **frontend indicators**: React, Vue, Angular (→ SPA container)
- Check for **backend indicators**: Express, Django, FastAPI (→ API container)
- Check for **infrastructure**: Docker Compose, K8s manifests (→ database, cache, broker containers)
- Detect **technology stack**: package.json, requirements.txt, pom.xml
- Identify **runtime environment**: browser, server, cloud, mobile
- Analyze **communication patterns**: HTTP clients, database drivers, message queues
**c) Document observations:**
- Technology choices (frameworks, libraries, versions)
- Runtime characteristics (containerization, deployment model)
- Communication protocols (REST, gRPC, database connections)
- Security findings (authentication, vulnerabilities)
- Performance considerations (caching, connection pooling)
**d) Map relationships:**
- How do containers communicate?
- What protocols are used?
- What dependencies exist?
### 4. Generate c2-containers.json
Create output following the template structure:
```json
{
"metadata": {
"schema_version": "1.0.0",
"timestamp": "<current-timestamp-ISO8601>",
"parent": {
"file": "c1-systems.json",
"timestamp": "<parent-timestamp-from-c1-systems>"
}
},
"containers": [
{
"id": "kebab-case-id",
"name": "Descriptive Container Name",
"type": "spa|api|database|cache|message-broker|web-server|worker|file-storage",
"system_id": "parent-system-id",
"responsibility": "What this container does",
"technology": {
"primary_language": "TypeScript|Python|Java|...",
"framework": "React 18.2.0|FastAPI 0.104|...",
"libraries": [...]
},
"runtime": {
"environment": "browser|server|cloud|mobile",
"platform": "Node.js 18 on Linux|Browser (Chrome 90+)|...",
"containerized": true|false,
"container_technology": "Docker|Kubernetes|..."
},
"observations": [...],
"relations": [...]
}
]
}
```
Use `Write` tool to create `c2-containers.json`.
### 5. Validate Output
Run validation script:
```bash
cat c2-containers.json | python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c2-containers.py
```
If validation fails (exit code 2), fix errors and re-validate.
### 6. Report Results
Summarize findings:
- Total containers identified
- Breakdown by type (SPA, API, database, etc.)
- Technology stacks detected
- Validation status
- Next step: Run `/melly-c3-components` or `/melly-doc-c4model`
## Key Principles
1. **Containers are deployable units** - Can be deployed independently
2. **Include infrastructure** - Databases, caches, brokers are containers
3. **Be specific about tech** - Include versions (React 18.2.0, not "React")
4. **Focus on the container level** - Not code modules (that's C3)
5. **Evidence-based observations** - Reference actual files and code
## Examples
### SPA Container
```json
{
"id": "customer-portal-spa",
"name": "Customer Portal SPA",
"type": "spa",
"technology": {
"primary_language": "TypeScript",
"framework": "React 18.2.0"
},
"runtime": {
"environment": "browser",
"platform": "Chrome 90+, Firefox 88+, Safari 14+"
}
}
```
### API Container
```json
{
"id": "ecommerce-api",
"name": "E-Commerce REST API",
"type": "api",
"technology": {
"primary_language": "Python",
"framework": "FastAPI 0.104.1"
},
"runtime": {
"environment": "server",
"platform": "Python 3.11 on Linux",
"containerized": true,
"container_technology": "Docker"
}
}
```
## Troubleshooting
- **Too many containers?** → You're identifying C3 components, not C2 containers
- **Can't detect tech stack?** → Check package.json, requirements.txt, Dockerfile
- **Validation fails?** → Check required fields, timestamp ordering, system_id references
- **Missing parent file?** → Run /melly-init and /melly-c1-systems first
---
**Remember**: Leverage the c4model-c2 skill for detailed methodology. Your job is to apply those rules systematically to the codebase.

146
agents/c3-abstractor.md Normal file
View File

@@ -0,0 +1,146 @@
---
name: c3-abstractor
description: Identify C3 components from containers using C4 Model methodology. Use when analyzing component architecture, mapping code structure within containers, or generating c3-components.json after C2 container identification.
tools: Read, Grep, Write, Bash, Skill
model: sonnet
---
# C3 Component Abstractor
You identify components at C4 Model Level 3 (Component).
## Workflow
### 1. Validate Input Files
Check that prerequisite JSON files exist:
```bash
test -f init.json && test -f c1-systems.json && test -f c2-containers.json || exit 1
```
Verify timestamp ordering using validation script:
```bash
bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/check-timestamp.sh c2-containers.json c1-systems.json
bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/check-timestamp.sh c1-systems.json init.json
```
### 2. Load C3 Methodology
Activate the c4model-c3 skill for component identification methodology:
- Component types (controller, service, repository, model, etc.)
- Design patterns (Singleton, Factory, Repository, DI)
- Dependency analysis rules
- Code structure patterns
The skill provides detailed guidance on identifying components, analyzing dependencies, and detecting patterns.
### 3. Read Container Data
Load containers from c2-containers.json:
```bash
cat c2-containers.json | jq '.containers[] | {id, name, type, system_id, path, technology, structure}'
```
Read init.json for repository paths and metadata.
### 4. Analyze Containers and Identify Components
For each container:
1. Navigate to container path from c2-containers.json
2. Analyze directory structure (src/, lib/, components/, etc.)
3. Identify significant components using c4model-c3 skill guidance:
- Controllers (HTTP handlers)
- Services (business logic)
- Repositories (data access)
- Models (data structures)
- Middleware (request processing)
- Utilities (helpers)
4. Determine component responsibilities
5. Map dependencies between components
6. Detect design patterns (use Grep for pattern detection)
7. Calculate metrics (LOC, complexity where possible)
8. Document observations (code structure, patterns, quality)
9. Document relations (dependencies, calls, uses)
### 5. Generate c3-components.json
Create output with structure:
```json
{
"metadata": {
"schema_version": "1.0.0",
"generator": "c3-abstractor",
"timestamp": "[ISO 8601 timestamp]",
"parent_file": "c2-containers.json",
"parent_timestamp": "[from c2-containers.json]"
},
"components": [
{
"id": "component-kebab-case-id",
"name": "Component Name",
"type": "controller|service|repository|model|middleware|utility|dto|adapter",
"container_id": "parent-container-id",
"path": "relative/path/to/component",
"description": "What this component does",
"responsibilities": ["Primary responsibility"],
"layer": "presentation|business|data|integration",
"dependencies": [
{"target": "other-component-id", "type": "uses|calls|depends-on"}
],
"observations": [
{"category": "code-structure|design-patterns|dependencies|complexity", "content": "observation", "severity": "info|warning|critical", "evidence": "file:line"}
],
"relations": [
{"target": "external-system|library", "type": "http|database|file", "description": "how it interacts"}
],
"metrics": {
"loc": 0,
"complexity": 0,
"dependencies_count": 0,
"public_methods": 0
}
}
],
"summary": {
"total_components": 0,
"by_type": {},
"by_layer": {}
}
}
```
Write to c3-components.json.
### 6. Validate and Return
Run validation:
```bash
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c3-components.py c3-components.json
```
If validation passes (exit code 0):
- Report success
- Summary: total components, breakdown by type
- Next step: Run /melly-doc-c4model to generate documentation
If validation fails (exit code 2):
- Report errors
- Provide guidance on fixing
## Output Format
Return:
- ✅ Components identified: [count]
- 📊 Breakdown: [by type]
- 📁 Output: c3-components.json
- ✨ Next: Run validation or proceed to documentation phase
## Important Notes
- Focus on **significant components** (>200 LOC or architecturally important)
- Use **kebab-case** for component IDs
- Provide **evidence** for observations (file paths, line numbers)
- Detect **design patterns** (Singleton, Factory, Repository, DI)
- Analyze **dependencies** (internal and external)
- Calculate **metrics** where possible
- Preserve **timestamp hierarchy** (c3 > c2 > c1 > init)

198
agents/c4-abstractor.md Normal file
View File

@@ -0,0 +1,198 @@
---
name: c4-abstractor
description: Identify C4 code elements from components using C4 Model methodology. Use when analyzing code-level architecture, mapping classes/functions/interfaces within components, or generating c4-code.json after C3 component identification.
tools: Read, Grep, Write, Bash, Skill
model: sonnet
---
# C4 Code Abstractor
You identify code elements at C4 Model Level 4 (Code).
## Workflow
### 1. Validate Input Files
Check that prerequisite JSON files exist:
```bash
test -f init.json && test -f c1-systems.json && test -f c2-containers.json && test -f c3-components.json || exit 1
```
Verify timestamp ordering using validation script:
```bash
bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/check-timestamp.sh c3-components.json c2-containers.json
bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/check-timestamp.sh c2-containers.json c1-systems.json
bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/check-timestamp.sh c1-systems.json init.json
```
### 2. Load C4 Methodology
Activate the c4model-c4 skill for code element identification methodology:
- Code element types (class, function, method, interface, type, enum, etc.)
- Signature analysis rules
- Complexity metrics calculation
- Code pattern detection
- Relationship mapping at code level
The skill provides detailed guidance on identifying significant code elements, analyzing signatures, and detecting patterns.
### 3. Read Component Data
Load components from c3-components.json:
```bash
cat c3-components.json | jq '.components[] | {id, name, type, container_id, structure}'
```
Read init.json for repository paths and metadata.
### 4. Analyze Components and Identify Code Elements
For each component:
1. Navigate to component path from c3-components.json
2. Analyze source files within the component
3. Identify **significant code elements** using c4model-c4 skill guidance:
- **Classes** (with inheritance, interfaces, decorators)
- **Functions** (standalone, with signatures)
- **Methods** (class methods, key public methods)
- **Interfaces** (TypeScript/Java interfaces)
- **Types** (type aliases, generics)
- **Constants** (exported constants)
- **Enums** (enumeration definitions)
4. Extract signatures (parameters, return types, generics)
5. Map relationships between code elements
6. Calculate metrics (LOC, cyclomatic complexity, cognitive complexity)
7. Document observations across 10 categories:
- implementation, error-handling, type-safety, documentation
- testing, complexity, performance, security, concurrency, patterns
8. Document relations:
- calls, returns, imports, inherits, implements
- declares, uses-type, depends-on, throws, awaits
### 5. Generate c4-code.json
Create output with structure:
```json
{
"metadata": {
"schema_version": "1.0.0",
"timestamp": "[ISO 8601 timestamp]",
"parent": {
"file": "c3-components.json",
"timestamp": "[from c3-components.json metadata.timestamp]"
}
},
"code_elements": [
{
"id": "code-element-kebab-case-id",
"name": "OriginalName",
"element_type": "class|function|async-function|method|interface|type|constant|enum",
"component_id": "parent-component-id",
"visibility": "public|private|protected|internal",
"description": "What this code element does",
"location": {
"file_path": "relative/path/to/file.ts",
"start_line": 10,
"end_line": 50
},
"signature": {
"parameters": [{"name": "param", "type": "Type", "optional": false}],
"return_type": "ReturnType",
"async": true,
"generic_params": ["T"]
},
"class_info": {
"extends": "ParentClass",
"implements": ["Interface1", "Interface2"],
"abstract": false,
"decorators": ["@Injectable()"]
},
"metrics": {
"lines_of_code": 40,
"cyclomatic_complexity": 6,
"cognitive_complexity": 8,
"parameter_count": 2,
"nesting_depth": 3
},
"observations": [
{
"id": "obs-element-category-01",
"category": "implementation|error-handling|type-safety|documentation|testing|complexity|performance|security|concurrency|patterns",
"severity": "info|warning|critical",
"description": "observation text",
"evidence": [{"location": "file:line", "type": "code|metric|pattern"}],
"tags": ["tag1"]
}
],
"relations": [
{
"target": "other-element-id",
"type": "calls|returns|imports|inherits|implements|declares|uses-type|depends-on|throws|awaits",
"description": "how it relates"
}
]
}
],
"summary": {
"total_elements": 0,
"by_type": {},
"by_component": {},
"complexity_stats": {
"average_cyclomatic": 0,
"max_cyclomatic": 0,
"high_complexity_count": 0
}
}
}
```
Write to c4-code.json.
### 6. Validate and Return
Run validation:
```bash
python3 ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c4-code.py c4-code.json
```
If validation passes (exit code 0):
- Report success
- Summary: total elements, breakdown by type
- Next step: Run /melly:doc-c4model to generate documentation
If validation fails (exit code 2):
- Report errors
- Provide guidance on fixing
## Output Format
Return:
- ✅ Code elements identified: [count]
- 📊 Breakdown: [by type]
- 📁 Output: c4-code.json
- ✨ Next: Run validation or proceed to documentation phase
## Significance Criteria
Document a code element if **ANY** of these apply:
- Public API (exported from module)
- Lines of code > 20
- Cyclomatic complexity > 4
- Multiple callers or dependencies
- Implements design pattern
- Contains critical business logic
- Has security implications
- Is entry point or controller action
- Defines key data structure
## Important Notes
- Focus on **significant code elements** (public APIs, complex functions, key classes)
- Do NOT document every private helper or trivial getter/setter
- Use **kebab-case** for element IDs
- Preserve **original case** for element names
- Provide **evidence** for observations (file paths, line numbers, snippets)
- Extract **signatures** with parameter types and return types
- Calculate **metrics** where possible (LOC, complexity)
- Document **inheritance** and **interface implementation** for classes
- Preserve **timestamp hierarchy** (c4 > c3 > c2 > c1 > init)
- Include **signature** for functions/methods, **class_info** for classes

133
agents/c4model-drawer.md Normal file
View File

@@ -0,0 +1,133 @@
---
name: c4model-drawer
description: Generate Mermaid diagrams and Obsidian canvas files from C4 model JSON data. Use when creating visualizations of C1 systems, C2 containers, or C3 components.
tools: Read, Write
model: sonnet
---
# C4 Model Diagram Drawer
You generate visual diagrams from C4 model JSON files using Mermaid syntax and Obsidian canvas format.
## Workflow
1. **Validate Input**
- Check JSON files exist (c1-systems.json, c2-containers.json, c3-components.json)
- Determine which levels to process (c1, c2, c3, or all)
- Verify JSON structure is valid
2. **Parse JSON Data**
- Load requested JSON file(s)
- Extract systems/containers/components
- Extract relations for diagram edges
3. **Generate Mermaid Diagrams**
- Create Mermaid flowchart syntax for each level
- Add nodes for entities (systems, containers, components)
- Add edges for relations (dependencies, communication)
- Use appropriate styling and grouping
4. **Create Canvas Files**
- Generate Obsidian canvas JSON format
- Position nodes spatially for readability
- Save to knowledge-base/systems/{system-name}/diagrams/
5. **Return Summary**
- List generated diagrams
- Report any errors or warnings
- Suggest next steps
## Mermaid Syntax Guidelines
### C1 System Context Diagram
```mermaid
flowchart TB
classDef system fill:#1168bd,stroke:#0b4884,color:#fff
classDef external fill:#999,stroke:#666,color:#fff
System1[System Name]:::system
ExtSys[External System]:::external
System1 -->|http-rest| ExtSys
```
### C2 Container Diagram
```mermaid
flowchart TB
classDef container fill:#438dd5,stroke:#2e6295,color:#fff
subgraph System
Container1[Web App]:::container
Container2[API]:::container
DB[(Database)]:::container
end
Container1 -->|REST API| Container2
Container2 -->|SQL| DB
```
### C3 Component Diagram
```mermaid
flowchart TB
classDef component fill:#85bbf0,stroke:#5d9dd5,color:#000
subgraph Container
Comp1[Controller]:::component
Comp2[Service]:::component
Comp3[Repository]:::component
end
Comp1 -->|uses| Comp2
Comp2 -->|uses| Comp3
```
## Canvas File Format
Obsidian canvas files are JSON with nodes and edges:
```json
{
"nodes": [
{
"id": "node-1",
"type": "text",
"text": "# System Name\n\nDescription",
"x": 0,
"y": 0,
"width": 250,
"height": 150
}
],
"edges": [
{
"id": "edge-1",
"fromNode": "node-1",
"toNode": "node-2",
"label": "http-rest"
}
]
}
```
## Output
Generate files:
- `knowledge-base/systems/{system-name}/diagrams/c1-system-context.md` (Mermaid)
- `knowledge-base/systems/{system-name}/diagrams/c2-containers.md` (Mermaid)
- `knowledge-base/systems/{system-name}/diagrams/c3-components.md` (Mermaid)
- `knowledge-base/systems/{system-name}/diagrams/c1-canvas.canvas` (Obsidian)
- `knowledge-base/systems/{system-name}/diagrams/c2-canvas.canvas` (Obsidian)
- `knowledge-base/systems/{system-name}/diagrams/c3-canvas.canvas` (Obsidian)
Return summary:
```
✅ Generated diagrams:
- C1: 3 systems, 5 relations
- C2: 8 containers, 12 relations
- C3: 24 components, 45 relations
📁 Files created:
- knowledge-base/systems/web-app/diagrams/c1-system-context.md
- knowledge-base/systems/web-app/diagrams/c1-canvas.canvas
- ... (6 files total)
```

105
agents/c4model-writer.md Normal file
View File

@@ -0,0 +1,105 @@
---
name: c4model-writer
description: Generate markdown documentation from C4 JSON files. Use when converting C4 model data to documentation.
tools: Read, Write, Bash, Grep
model: sonnet
---
# C4 Model Documentation Writer
You convert C4 JSON files into structured markdown documentation.
## Workflow
1. **Detect basic-memory project root**
- Run: `python validation/scripts/get_project_root.py --list` to check available projects
- If multiple projects exist, detect which one to use in priority order:
1. Single project from ~/.basic-memory/config.json (auto-selected)
2. Default project from config (when default_project_mode is true)
3. BASIC_MEMORY_PROJECT_ROOT environment variable
4. Fallback to ./knowledge-base in git root or current directory
- Store the selected project name for use in generation scripts
2. **Validate inputs**
- Read init.json, c1-systems.json, c2-containers.json, c3-components.json
- Verify timestamp ordering (init < c1 < c2 < c3)
- Check basic-memory MCP availability
- Run: `bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/check-timestamp.sh`
3. **Detect changes (incremental updates)**
- Read .melly-doc-metadata.json (if exists)
- Calculate checksums for each entity (SHA-256 of JSON)
- Build change map: new / modified / unchanged
- Skip unchanged entities for efficiency
4. **Generate markdown per level**
- For C1 systems: Use `${CLAUDE_PLUGIN_ROOT}/validation/scripts/generate-c1-markdown.py c1-systems.json [--project NAME]`
- For C2 containers: Use `${CLAUDE_PLUGIN_ROOT}/validation/scripts/generate-c2-markdown.py c2-containers.json [--project NAME]`
- For C3 components: Use `${CLAUDE_PLUGIN_ROOT}/validation/scripts/generate-c3-markdown.py c3-components.json [--project NAME]`
- Pass --project flag only if specific project was detected in step 1
- Process in parallel where possible
- Output location is auto-detected by scripts based on project configuration
5. **Validate and report**
- Run: `python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-markdown.py {project-root}/systems/**/*.md`
- Update .melly-doc-metadata.json with:
- Entity checksums
- Generated timestamps
- File paths
- Generate summary report:
```
Summary:
- Project: {project-name}
- Project root: {project-root}
- Processed: X entities (Y new, Z modified)
- Skipped: N unchanged
- Errors: 0
- Generated: [file paths]
```
- Inform user that files are written to filesystem (basic-memory sync must be run manually if needed)
## Output Format
Return:
- **Total entities**: Count processed
- **Generated files**: List of markdown files created
- **Validation**: Pass/fail status
- **Next step**: Suggest `/melly-draw-c4model` for visualizations
## Incremental Updates
**Change detection strategy**:
- Calculate SHA-256 checksum per entity (stable JSON serialization)
- Compare with previous checksums from .melly-doc-metadata.json
- Only regenerate changed entities
**Metadata file** (.melly-doc-metadata.json):
```json
{
"last_generation": "2025-11-17T...",
"entities": {
"c1": {
"entity-id": {
"checksum": "sha256...",
"generated_at": "timestamp",
"markdown_path": "path/to/file.md"
}
}
}
}
```
## Error Handling
- **Validation errors (exit 2)**: Stop processing, report errors
- **Project detection errors**: Fall back to ./knowledge-base in current directory
- **Template errors**: Use fallback minimal markdown
- **Partial failures**: Continue with other entities, collect errors in report
## Basic-Memory Integration Note
The generation scripts write markdown files directly to the filesystem. For basic-memory indexing:
- Files are written to the detected project root
- If BASIC_MEMORY_SYNC_CHANGES is enabled, user can run `basic-memory sync` manually
- Or run `basic-memory sync --watch` in background for automatic indexing
- MCP-based writes are planned but not yet implemented

59
agents/explorer.md Normal file
View File

@@ -0,0 +1,59 @@
---
name: explorer
description: Explore code repositories and generate init.json with repository metadata, manifests, and structure. Use when analyzing codebases, initializing C4 workflow, or scanning repository structure.
tools: Read, Glob, Grep, Bash, Write
model: sonnet
---
# Repository Explorer
You analyze code repositories and generate `init.json` with comprehensive metadata.
## Workflow
1. **Scan repositories**
- Get repository paths from user argument or prompt
- For each path, verify it exists and is accessible
- Detect if git repository (check `.git/` directory)
2. **Analyze structure**
- Identify package manifests (package.json, composer.json, requirements.txt, go.mod, Cargo.toml, pom.xml, build.gradle, Gemfile, pubspec.yaml)
- Parse manifest files to extract dependencies, scripts, metadata
- Map directory structure: source dirs, test dirs, config files, docs, build outputs
- Detect entry points (main files, CLI tools, servers)
- Identify primary language and frameworks from manifests and file extensions
3. **Extract metadata**
- Git info: remote URL, current branch, commit hash, dirty status
- Repository type: monorepo (multiple manifests), single, microservice, library
- Technology stack: languages, frameworks, runtime
- Metrics: file counts, basic LOC estimation
4. **Generate init.json**
- Use schema from `${CLAUDE_PLUGIN_ROOT}/validation/templates/init-template.json`
- Include metadata: timestamp (ISO 8601 UTC), schema version, generator info
- For each repository: id (kebab-case), name, path (absolute), type, git, manifests, structure, technology, metrics
- Add summary: total repos, types breakdown, languages, manifest count
- Write to `init.json` in current directory
5. **Validate and return**
- Run: `python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-init.py < init.json`
- If validation fails (exit code 2): report errors and stop
- If validation warns (exit code 1): show warnings but continue
- Return: repository count, manifest count, validation status, next step hint
## Output Format
Return summary:
- ✅ Repositories found: [count]
- ✅ Manifests detected: [count]
- ✅ File: init.json (validated)
- ➡️ Next: Run `/melly-c1-systems` to identify C1-level systems
## Notes
- Repository paths must be absolute
- All timestamps in ISO 8601 format with UTC timezone
- IDs must be kebab-case (lowercase, hyphens only)
- Manifests are parsed, not just listed
- Validation runs automatically - do not skip

View File

@@ -0,0 +1,99 @@
---
name: lib-doc-analyzer
description: Analyzes markdown-based library documentation and extracts metadata (observations + relations) while preserving 100% of original content. Use when processing library docs for contextual retrieval, analyzing framework documentation, or splitting large docs into semantic chunks.
tools: Read, Glob, Grep, Write, Bash
model: sonnet
---
# Library Documentation Analyzer
You are an expert at analyzing library documentation and extracting semantic metadata.
## Workflow
### Phase 1: Discovery & Validation
1. Accept library name and docs path as arguments
2. Find all markdown files using Glob
3. Validate structure (headings, code blocks present)
4. Load lib-doc-methodology skill
### Phase 2: Parsing
For each markdown file:
1. Read original content (preserve completely)
2. Run `python scripts/parse-markdown.py <file>` to extract structure
3. Parse JSON output (headings, code_blocks, links)
### Phase 3: Semantic Analysis
For each file:
1. Run `python scripts/extract-metadata.py <file> <library>` to extract observations and relations
2. Parse JSON output
3. Build metadata dict with:
- title (from H1 heading)
- library, version
- category, type
- tags (auto-generated from content)
- dependencies (from relations)
- observations (extracted)
- relations (extracted)
### Phase 4: Enhanced Markdown Generation
For each file:
1. Build frontmatter from metadata
2. Create metadata section:
```markdown
## 📊 Extracted Metadata
> **Note**: Auto-extracted metadata for semantic search.
### Observations
- [category] content #tags
### Relations
- type [[target]]
```
3. Add separator: `---`
4. Append original content (100% unchanged)
5. Write to output file
### Phase 5: Validation & Reporting
1. Run `python scripts/validate-content.py <original> <enhanced>` for each file
2. Collect validation results
3. Generate metadata JSON (lib-docs-{library}.json)
4. Run `python scripts/validate-lib-docs.py lib-docs-{library}.json`
5. Generate summary report:
- Total files processed
- Observations extracted
- Relations found
- Validation status
## Error Handling
- Missing files → Exit with error message
- Parse failures → Log warning, continue with next file
- Validation failures → Report errors, halt if critical
## Output
Return comprehensive report with:
- Files processed count
- Metadata statistics
- Validation results
- Location of enhanced files
- Location of metadata JSON
## Important Notes
- NEVER modify original content
- Use scripts for all parsing/extraction
- Validate content preservation for every file
- Report any validation failures immediately
Return final summary to user.

View File

@@ -0,0 +1,274 @@
---
description: Analyze library documentation and extract metadata for semantic search
argument-hint: [library-name] [docs-path]
allowed-tools: Task, Read, Write, Bash, Glob, Grep
---
# Library Documentation Analysis
Analyze markdown-based library documentation and extract observations and relations for semantic search.
## Arguments
- `$1` - **Library name** (required): Name of the library (e.g., laravel, react, django)
- `$2` - **Documentation path** (optional): Path to library docs
- Default: `knowledge-base/libraries/$1/`
- Supports absolute or relative paths
## Workflow
<!-- markdownlint-disable MD029 -->
### Phase 1: Validation
1. **Validate arguments**:
- Library name is required
- If no path provided, use default: `knowledge-base/libraries/$1/`
- Verify documentation path exists
- Check for markdown files in path
2. **Verify dependencies**:
- basic-memory MCP server is available
- Validation scripts exist in plugin
### Phase 2: Analysis
3. **Invoke lib-doc-analyzer agent**:
Explicitly invoke the lib-doc-analyzer agent to perform the analysis:
```
Use the lib-doc-analyzer agent to analyze the $1 library documentation.
Agent context:
- Library name: $1
- Documentation path: $2 (or knowledge-base/libraries/$1/ if not specified)
- Task: Analyze all markdown files and extract observations and relations
- Skill: Use the lib-doc-methodology skill for guidance
```
**Alternative invocation patterns:**
```
Have the lib-doc-analyzer agent process the library documentation at $2.
Extract metadata from $1 documentation using the lib-doc-analyzer agent.
Ask lib-doc-analyzer to analyze library docs for $1 at $2.
```
**What the agent will do:**
- Automatically follow the 5-phase workflow defined in its system prompt
- Use the lib-doc-methodology skill for extraction rules
- Generate enhanced markdown files with frontmatter
- Create lib-docs-$1.json metadata file
- Run validation scripts to verify quality
4. **Agent performs 5-phase workflow**:
- Discovery: Find all markdown files
- Parsing: Extract structure (headings, code, links)
- Analysis: Extract observations and relations
- Generation: Create enhanced markdown files
- Validation: Verify content preservation
### Phase 3: Validation
5. **Run validation scripts**:
```bash
# Validate metadata JSON
python3 plugins/melly-writer-lib/scripts/validate-lib-docs.py lib-docs-$1.json
# Verify content preservation
python3 plugins/melly-writer-lib/scripts/validate-content.py $2
```
6. **Check validation results**:
- Exit code 0: Success
- Exit code 1: Warnings (continue with caution)
- Exit code 2: Blocking errors (stop workflow)
### Phase 4: Integration
7. **Store in basic-memory**:
- Create knowledge entities for each enhanced markdown file
- Include metadata (observations, relations) in entity
- Generate permalinks for cross-referencing
8. **Generate metadata file**:
- Create `lib-docs-$1.json` with complete metadata
- Include library info, entities, relationships, statistics
- Store in documentation path
### Phase 5: Reporting
9. **Generate summary report**:
```
✅ Library Documentation Analysis Complete
Library: [Library Name Version]
Path: [Documentation Path]
---
📊 Statistics:
Files processed: [count]
Observations: [count]
Relations: [count]
Total chunks: [count]
Avg chunk size: [words]
📁 Output:
Enhanced files: [path]/**/*.md
Metadata: lib-docs-[name].json
basic-memory entities: [count] created
✅ Validation:
Content preservation: [passed/total] passed
Metadata quality: Valid
💡 Next Steps:
1. Search: "What is [concept] in [library]?"
2. Build context: "Show me [library] [topic] concepts"
3. Navigate: Open enhanced markdown files in Obsidian
```
## Examples
```bash
# Analyze Laravel documentation (default path)
/melly-analyze-lib-docs laravel
# Analyze React documentation (default path)
/melly-analyze-lib-docs react
# Analyze Django with custom path
/melly-analyze-lib-docs django /path/to/django-docs
# Analyze Laravel 11.x with explicit path
/melly-analyze-lib-docs laravel-11 knowledge-base/libraries/laravel-11/
```
## Error Handling
### Missing library name:
```
❌ Error: Library name is required
Usage: /melly-analyze-lib-docs [library-name] [docs-path]
Example: /melly-analyze-lib-docs laravel
```
### Documentation path not found:
```
❌ Error: Documentation path not found
Path: knowledge-base/libraries/[name]/
Please ensure the documentation exists or provide a custom path.
```
### No markdown files found:
```
❌ Error: No markdown files found in documentation path
Path: [path]
Expected: At least one .md file in the directory
```
### Validation failure:
```
❌ Validation Error: Content preservation failed
File: [filename]
Issue: Enhanced content differs from original
Action: Review agent output and try again
```
### basic-memory unavailable:
```
⚠️ Warning: basic-memory MCP server not available
Analysis will continue, but entities won't be stored for semantic search.
Metadata will still be generated in lib-docs-[name].json
```
## Output Structure
### Enhanced Markdown Files
Each original markdown file is enhanced with:
- **Frontmatter**: Library metadata (name, version, url, file info)
- **Metadata Section**: Observations and relations extracted from content
- **Separator**: `---` to separate metadata from original content
- **Original Content**: 100% preserved, byte-for-byte identical
### Metadata JSON File
`lib-docs-[library-name].json` contains:
- **library**: Library information (name, version, url, stats)
- **entities**: Array of enhanced files with metadata
- **relationships**: Cross-file relations discovered
- **analyzed_at**: Timestamp of analysis
### basic-memory Entities
Each enhanced markdown file becomes a searchable entity:
- **Content**: Original markdown content
- **Metadata**: Observations and relations
- **Permalink**: Stable reference for cross-linking
## Best Practices
1. **Organize documentation**:
- Use standard path: `knowledge-base/libraries/[name]/`
- Keep original structure (don't flatten)
- Preserve version information
2. **Incremental updates**:
- Re-analyze when docs are updated
- Metadata will be regenerated
- basic-memory entities will be updated
3. **Quality validation**:
- Always review validation output
- Check content preservation results
- Verify observations are extracted, not fabricated
4. **Semantic search**:
- Use natural language queries
- Reference concepts by name
- Build context from multiple entities
5. **Integration with C4 model**:
- Library docs inform C2 (Container) analysis
- Technical decisions reference library capabilities
- Architectural patterns link to library features
## Troubleshooting
### Agent doesn't activate
**Cause**: lib-doc-analyzer agent not found
**Solution**: Ensure agent exists in `plugins/melly-writer-lib/agents/`
### Skill not used
**Cause**: lib-doc-methodology skill not loaded
**Solution**: Check `plugins/melly-writer-lib/skills/lib-doc-methodology/SKILL.md` exists
### Validation scripts fail
**Cause**: Python version incompatibility or missing dependencies
**Solution**:
- Ensure Python 3.8+ is installed: `python3 --version`
- Make scripts executable: `chmod +x plugins/melly-writer-lib/scripts/*.py`
- Install required packages (see plugin README.md)
### basic-memory errors
**Cause**: MCP server configuration issue
**Solution**: Verify basic-memory in `~/.claude/settings.json`
## Dependencies
- **Agent**: lib-doc-analyzer
- **Skill**: lib-doc-methodology
- **Scripts**: validate-lib-docs.py, validate-content.py
- **MCP Server**: basic-memory (optional but recommended)
- **Python**: 3.8+ with required packages
## Related Commands
- `/melly-init` - Initialize C4 model exploration
- `/melly-c2-containers` - Analyze C2 containers (uses library knowledge)
- `/melly-doc-c4model` - Generate C4 documentation (references library docs)
---
**Version**: 1.0.0
**Plugin**: melly-writer-lib
**Category**: knowledge-extraction

43
commands/c1-systems.md Normal file
View File

@@ -0,0 +1,43 @@
---
description: Identify C1-level systems from repositories
argument-hint: [init-json-path]
allowed-tools: Task, Read, Bash
---
Analyze repositories and identify C1 systems using C4 methodology.
## Context
- Init file: ${1:-init.json}
- Status: !`test -f "${1:-init.json}" && echo "✅ exists" || echo "❌ missing"`
- Validation: ${CLAUDE_PLUGIN_ROOT}/validation/scripts/
## Workflow
Use the Task tool to launch the **c1-abstractor** agent with the following requirements:
**Input**:
- Read init.json (repository paths and metadata)
- Apply C4 Level 1 methodology via c4model-c1 skill
**Process**:
- Analyze each repository for system boundaries
- Identify systems, actors, and high-level relationships
- Create system folder structure via create-folders.sh script
- Generate observations with evidence (file:line references)
- Map system relations (dependencies, communication)
**Output**:
- c1-systems.json with structure:
- metadata (timestamp, parent reference to init.json)
- systems[] (id, name, type, purpose, repository_path)
- observations[] (category, content, evidence)
- relations[] (from, to, type, protocol)
After agent completes:
- Validate output: `bash ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c1-systems.py c1-systems.json`
- Report results: systems count, next step
**Next step**: /melly-c2-containers
See [docs/workflow-guide.md](../../docs/workflow-guide.md) for detailed usage examples.

70
commands/c2-containers.md Normal file
View File

@@ -0,0 +1,70 @@
---
description: Identify C2-level containers (deployable units) from systems
argument-hint: [init-json-path]
allowed-tools: Task, Read, Bash
---
# Identify C2 Containers
Analyze systems and identify C2-level containers (deployable/runnable units) using C4 Model methodology.
## Context
- Init file: ${1:-init.json}
- C1 systems file: ${2:-c1-systems.json}
- Status: !`test -f ${1:-init.json} && test -f ${2:-c1-systems.json} && echo "✓ Files exist" || echo "✗ Missing files"`
## Prerequisites
Before running this command:
1. **Run /melly-init** first to generate init.json
2. **Run /melly-c1-systems** to generate c1-systems.json
## What This Command Does
1. **Validates prerequisites** - Checks init.json and c1-systems.json exist
2. **Launches c2-abstractor agent** - Applies C4 Level 2 methodology
3. **Identifies containers** - Deployable units (SPA, API, databases, caches, etc.)
4. **Detects technology stacks** - Languages, frameworks, libraries, versions
5. **Analyzes runtime environments** - Where and how containers run
6. **Maps communication** - How containers interact (REST, gRPC, database, etc.)
7. **Generates c2-containers.json** - Structured output with observations and relations
8. **Validates output** - Ensures schema compliance and referential integrity
## Workflow
Use the Task tool to launch the **c2-abstractor** agent with:
- Input: init.json, c1-systems.json
- Methodology: c4model-c2 skill (automatic activation)
- Output: c2-containers.json
After agent completes:
- Validate: `cat c2-containers.json | python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c2-containers.py`
- Report results summary
- Suggest next step: `/melly-c3-components` or `/melly-doc-c4model`
## Next Steps
After successful completion:
- **Option 1**: Run `/melly-c3-components` to analyze component structure
- **Option 2**: Run `/melly-doc-c4model` to generate documentation
- **Option 3**: Manually inspect `c2-containers.json` for accuracy
## Troubleshooting
- **Missing init.json**: Run `/melly-init` first
- **Missing c1-systems.json**: Run `/melly-c1-systems` first
- **Validation fails**: Check error messages, fix issues in c2-containers.json
- **Timestamp errors**: Ensure c2 timestamp > c1 timestamp > init timestamp
## Documentation
For details on C4 Level 2 methodology:
- **Methodology**: See `plugins/c4model-c2/skills/c4model-c2/SKILL.md`
- **Schema**: See `${CLAUDE_PLUGIN_ROOT}/validation/templates/c2-containers-template.json`
- **Validation**: See `${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c2-containers.py`
- **Workflow**: See `docs/c4model-methodology.md`
---
**C2 Level Focus**: Deployable units, technology stacks, runtime environments, communication patterns

44
commands/c3-components.md Normal file
View File

@@ -0,0 +1,44 @@
---
description: Identify C3-level components from containers
argument-hint: [c2-containers-json-path]
allowed-tools: Task, Read, Bash
---
Analyze containers and identify C3 components using C4 Model methodology.
## Context
- Input: $1 (default: c2-containers.json)
- Status: !`test -f ${1:-c2-containers.json} && echo "✓ exists" || echo "✗ missing"`
- Prerequisites: !`test -f init.json && test -f c1-systems.json && echo "✓ ready" || echo "✗ run /melly-init and /melly-c1-systems and /melly-c2-containers first"`
## Workflow
**1. Validate Prerequisites**
Check that init.json, c1-systems.json, and c2-containers.json exist.
If missing, inform user to run previous commands first.
**2. Launch c3-abstractor Agent**
Use Task tool to launch c3-abstractor agent:
- Input: c2-containers.json path (${1:-c2-containers.json})
- Agent will validate files, load c4model-c3 skill, analyze containers, identify components, and generate c3-components.json
- Applies C3 methodology automatically
**3. Validate and Report**
After agent completion:
```bash
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c3-components.py c3-components.json
```
Report:
- Components identified (count and breakdown by type/layer)
- Validation status
- Next step: /melly-doc-c4model
## Output
- **c3-components.json** - Components with observations, relations, metrics
- **Validation report** - Structure and dependency validation

44
commands/c4-code.md Normal file
View File

@@ -0,0 +1,44 @@
---
description: Identify C4-level code elements from components
argument-hint: [c3-components-json-path]
allowed-tools: Task, Read, Bash
---
Analyze components and identify C4 code elements using C4 Model methodology.
## Context
- Input: $1 (default: c3-components.json)
- Status: !`test -f ${1:-c3-components.json} && echo "✓ exists" || echo "✗ missing"`
- Prerequisites: !`test -f init.json && test -f c1-systems.json && test -f c2-containers.json && test -f c3-components.json && echo "✓ ready" || echo "✗ run /melly:init, /melly:c1-systems, /melly:c2-containers, and /melly:c3-components first"`
## Workflow
**1. Validate Prerequisites**
Check that init.json, c1-systems.json, c2-containers.json, and c3-components.json exist.
If missing, inform user to run previous commands first.
**2. Launch c4-abstractor Agent**
Use Task tool to launch c4-abstractor agent:
- Input: c3-components.json path (${1:-c3-components.json})
- Agent will validate files, load c4model-c4 skill, analyze components, identify code elements, and generate c4-code.json
- Applies C4 methodology automatically
**3. Validate and Report**
After agent completion:
```bash
python3 ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c4-code.py c4-code.json
```
Report:
- Code elements identified (count and breakdown by type/component)
- Validation status
- Next step: /melly:doc-c4model
## Output
- **c4-code.json** - Code elements with observations, relations, metrics
- **Validation report** - Structure and relationship validation

67
commands/doc-c4model.md Normal file
View File

@@ -0,0 +1,67 @@
---
description: Generate C4 model markdown documentation from JSON files
argument-hint: [level]
allowed-tools: Task, Read, Bash
---
Generate structured markdown documentation from C4 model JSON files.
## Context
- Level: $1 (or "all" if not specified)
- JSON files status: !`test -f init.json && test -f c1-systems.json && test -f c2-containers.json && test -f c3-components.json && echo "✓ All present" || echo "✗ Missing files"`
- Last generation: !`test -f .melly-doc-metadata.json && jq -r '.last_generation' .melly-doc-metadata.json || echo "Never"`
## Workflow
Use the Task tool to launch the c4model-writer agent to:
1. Detect basic-memory project root (auto-selects from ~/.basic-memory/config.json or uses fallback)
2. Validate all required JSON files exist
3. Apply C4 markdown templates
4. Generate documentation to detected project location
5. Run validation on generated files
**Agent invocation:**
```
Level: ${1:-all}
Force regenerate: false (incremental updates enabled)
Output: Auto-detected project root (see agent output for location)
```
**Project Detection:**
- Single project: Auto-selected automatically
- Multiple projects: Uses default_project from config or BASIC_MEMORY_PROJECT_ROOT env var
- No config: Falls back to ./knowledge-base in current directory
## After Completion
The agent will report:
- Project name and root path used
- Entities processed (new/modified/unchanged)
- Generated file paths
- Validation results
**Validation:**
```bash
# Validate generated markdown (if needed)
# Use the project root path reported by the agent
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-markdown.py {project-root}/systems/**/*.md
```
**Basic-Memory Indexing (Optional):**
If you want generated files indexed in basic-memory for semantic search:
```bash
# One-time sync
basic-memory sync
# Or continuous watching (recommended)
basic-memory sync --watch
```
**Next steps:**
- Review generated documentation in the reported project root
- Optionally sync with basic-memory for searchable knowledge
- Run `/melly-draw-c4model` to create visualizations
- Commit documentation to repository
For detailed usage, see [docs/workflow-guide.md](../../../docs/workflow-guide.md)

71
commands/draw-c4model.md Normal file
View File

@@ -0,0 +1,71 @@
---
description: Generate C4 model diagrams (Mermaid + Obsidian canvas) from JSON files
argument-hint: [level] # c1, c2, c3, or all
allowed-tools: Task, Read, Bash
---
Generate visual diagrams from C4 model JSON files.
## Context
Level: $1 (default: all)
Available levels: c1 (systems), c2 (containers), c3 (components), all
## Prerequisites
Check JSON files:
- init.json: !`test -f init.json && echo "✅ exists" || echo "❌ missing"`
- c1-systems.json: !`test -f c1-systems.json && echo "✅ exists" || echo "❌ missing"`
- c2-containers.json: !`test -f c2-containers.json && echo "✅ exists" || echo "❌ missing"`
- c3-components.json: !`test -f c3-components.json && echo "✅ exists" || echo "❌ missing"`
## Workflow
1. **Validate Input**
- Level: ${1:-all}
- If level specified, check corresponding JSON exists
- If "all", check all JSON files exist
2. **Launch c4model-drawer Agent**
- Use Task tool to invoke c4model-drawer agent
- Pass level parameter: ${1:-all}
- Agent will:
- Parse JSON files
- Generate Mermaid diagrams
- Create Obsidian canvas files
- Save to knowledge-base/systems/*/diagrams/
3. **Report Results**
- List generated diagram files
- Show statistics (entities, relations)
- Display any errors or warnings
## Output
Generated files:
- Mermaid diagrams: `knowledge-base/systems/{system}/diagrams/c{1,2,3}-*.md`
- Canvas files: `knowledge-base/systems/{system}/diagrams/c{1,2,3}-*.canvas`
## Next Steps
After generation:
- Open diagrams in Obsidian for visualization
- Review system architecture visually
- Share diagrams with team
- Export to PNG/SVG if needed
## Examples
```bash
# Generate all diagrams
/melly-draw-c4model all
# Generate only C1 system context
/melly-draw-c4model c1
# Generate C2 containers
/melly-draw-c4model c2
# Generate C3 components
/melly-draw-c4model c3
```

33
commands/init.md Normal file
View File

@@ -0,0 +1,33 @@
---
description: Initialize C4 model exploration - scan repositories and generate init.json
argument-hint: [repository-path]
allowed-tools: Task, Read, Write, Bash
---
Initialize C4 model exploration by scanning repositories and generating init.json.
## Context
- Repository path: ${1:-.} (current directory if not specified)
- Repository exists: !`test -d "${1:-.}" && echo "yes" || echo "no"`
- Existing init.json: !`test -f init.json && echo "found ($(stat -c%y init.json | cut -d' ' -f1))" || echo "none"`
## Workflow
Use the Task tool to launch the c4model-explorer agent with:
- Repository root path: ${1:-.}
- Output file: init.json
The agent will:
1. Scan all repositories in the specified location
2. Identify package manifests and technology stacks
3. Generate init.json with metadata and structure
After agent completes:
- Validate output: `python3 ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-init.py < init.json`
- Review init.json for accuracy
- Suggest next step: /melly-c1-systems
## Notes
See [docs/workflow-guide.md](../../../docs/workflow-guide.md) for detailed usage examples.

249
plugin.lock.json Normal file
View File

@@ -0,0 +1,249 @@
{
"$schema": "internal://schemas/plugin.lock.v1.json",
"pluginId": "gh:Cubical6/melly:",
"normalized": {
"repo": null,
"ref": "refs/tags/v20251128.0",
"commit": "084a14675779e370db232225a3ee82e65883d7b3",
"treeHash": "e5635ede34bc92f531ea6bd0fd298e7715ac06d6973a95a59b4353fcae379e6c",
"generatedAt": "2025-11-28T10:10:09.453446Z",
"toolVersion": "publish_plugins.py@0.2.0"
},
"origin": {
"remote": "git@github.com:zhongweili/42plugin-data.git",
"branch": "master",
"commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390",
"repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data"
},
"manifest": {
"name": "melly",
"description": "Complete C4 model workflow for reverse engineering codebases - includes 6 workflow commands, 6 specialized agents, 5 methodology skills, and comprehensive validation tools",
"version": "2.0.0"
},
"content": {
"files": [
{
"path": "README.md",
"sha256": "b7878c9cc3a3d7e8c4afbcca1f4ba725a94eafa9a07c625b88224397d87d8c50"
},
{
"path": "agents/explorer.md",
"sha256": "debaa9af9a293750568a1b5830caa093833baedc49f11f9d20e105a49d4c6067"
},
{
"path": "agents/c1-abstractor.md",
"sha256": "9cc01db95fd21e0d63e10891ec97fe0148b0b07f562fbbbca9fc96009f025aa4"
},
{
"path": "agents/c4model-writer.md",
"sha256": "37cbe6f1d47942cd2fe02fb4e64264815991c8b4e5d2d84fd6885d24469f498d"
},
{
"path": "agents/c2-abstractor.md",
"sha256": "d07637bedc731341eac3d1aa79658ea211c4c15e5a0589feb4292a4fc6fff4b6"
},
{
"path": "agents/c3-abstractor.md",
"sha256": "270bedb8a1c2887a4b9e4c947cc101966d7e76e738df77653203dd3af1ca5606"
},
{
"path": "agents/c4-abstractor.md",
"sha256": "0f1e96f00fa8f8c5526a012a453425b35f0fb0e9f31f7ff6cf24d72ee5faa5e3"
},
{
"path": "agents/lib-doc-analyzer.md",
"sha256": "fe3dea6fc32bf001fe4e541f0ac0d9f98cc7a7a3f330658ea7e6d0f0b93ccc79"
},
{
"path": "agents/c4model-drawer.md",
"sha256": "ea68fbf45bb33e1311a02715ffe1a46f9b53871c234f5bcb95440734c1ac65ba"
},
{
"path": ".claude-plugin/plugin.json",
"sha256": "01bed88f1d1d961ebdcf8e0f635edb74deb9f6a4ce1c95c49b1bf8b3925dfe3c"
},
{
"path": "commands/draw-c4model.md",
"sha256": "b6464c175a75e0cabfa73e400d2af7de341e42a57c0a4e459849482ad5e21bcd"
},
{
"path": "commands/c3-components.md",
"sha256": "c67bab1f423f17d67b594fe9e4d80d9209adb519d2423dd6a1de5ad991bf10b2"
},
{
"path": "commands/c2-containers.md",
"sha256": "b1f245051469c7934b5c6dd83c0182a4487d2d499d533166bb38c0983147bd30"
},
{
"path": "commands/analyze-lib-docs.md",
"sha256": "0ba88d35317a205272ec71e61b73f5ed9de9668c396ce33fe2da5c9a20771601"
},
{
"path": "commands/c4-code.md",
"sha256": "372b2676924cc08c54aff63ec529c88807360ac7d6d012ff8459522d8facbf40"
},
{
"path": "commands/init.md",
"sha256": "58b1501a64ce606cdc359964ab601d6b6d4c535507373727b61185b461c3f1fb"
},
{
"path": "commands/doc-c4model.md",
"sha256": "611090e71bfabea4fadf33c91217c20f07aef3a3077b370e9a89e86883a4e1f4"
},
{
"path": "commands/c1-systems.md",
"sha256": "10f4272bd804f6f6695b53a13bbbafef7d0965f6d0bb1b59f36a8213bb8e1cc7"
},
{
"path": "skills/c4model-observations/examples.md",
"sha256": "95247a458eda23712311423fec0dc5467a2dcde1def644d1c1291d7e8d179757"
},
{
"path": "skills/c4model-observations/reference.md",
"sha256": "09e8324813541f78a5147509ffc969969986d4ebcc76badb024ff07a4aa0cf8d"
},
{
"path": "skills/c4model-observations/SKILL.md",
"sha256": "f52ab1bd284458b14be7bee9c7c638dd52807b1efc658c549cbe93434299ca18"
},
{
"path": "skills/c4model-observations/categories.md",
"sha256": "3a74a9beb984d3c9a67a343c59aad710698626fdff7d1b1efe20de6f2639d72d"
},
{
"path": "skills/c4model-c2/container-types-reference.md",
"sha256": "927cf4bbf9e792aabe6d241f77b2374c033c53d10b7fa16ad6a9f27cdc691488"
},
{
"path": "skills/c4model-c2/output-format.md",
"sha256": "1029dd99e672b932beec0a0926f6fed903cef2b413b294226988cf03c3ef38be"
},
{
"path": "skills/c4model-c2/technology-detection-patterns.md",
"sha256": "3a80e7e881359c8d9b8b2857e2c02992de6c317fd108f7c12f684f3f4fe2b1a2"
},
{
"path": "skills/c4model-c2/communication-patterns.md",
"sha256": "1febf16b336dabc7bed11ad882e325e1e84fd03986b6bd76c46ee0888a57c41a"
},
{
"path": "skills/c4model-c2/troubleshooting-guide-c2.md",
"sha256": "730cca445d4bf935dd35119bd545c95b162c6d1a28b3d20b75e95dbb75510c3a"
},
{
"path": "skills/c4model-c2/methodology.md",
"sha256": "a85b8ed005c76721b221ad74e7d59aa5e31fca1f51eeec12eb811c59518c4060"
},
{
"path": "skills/c4model-c2/SKILL.md",
"sha256": "5eb93985980b40ba6537aac30815886bb5d74e4614d7cb4d7af1f2502885f491"
},
{
"path": "skills/c4model-c2/common-container-patterns.md",
"sha256": "564e9fa7495de13a867700e33dda9c9e7c56a20d99b147c1bba6ffe6d80717f6"
},
{
"path": "skills/c4model-c2/observation-categories-c2.md",
"sha256": "3692d2259c7b2279078f99b57ac0c7e19c11089d2104e24c28e459fddeb6c1c8"
},
{
"path": "skills/c4model-c3/component-identification.md",
"sha256": "75e2f31c6da0fb41cbb6ee135bb36277af2c53f6df17a8af98f8fbb82793228f"
},
{
"path": "skills/c4model-c3/dependency-analysis.md",
"sha256": "b8041b44d4e995f610719690bb69f7df9c9feca66b25b875e51970d1158115b8"
},
{
"path": "skills/c4model-c3/technology-examples.md",
"sha256": "d8f19a116b20c0ead10d8fa71ba5a64c0931183362fb4c76751326d8686bbb83"
},
{
"path": "skills/c4model-c3/SKILL.md",
"sha256": "86fed3449812e7ff7d9fccf239bf0112960b177def910833e08f52bbfe03c9cf"
},
{
"path": "skills/c4model-c3/pattern-detection.md",
"sha256": "965cf660aaf175e37391ea25930903d0c8103eeba81ffa770b6d231ef7db088e"
},
{
"path": "skills/c4model-c3/observation-guide.md",
"sha256": "7bc8ed17c59f9a1eccb3c5cdd00c34f8079f1d2cd2d943b791b0e1ca428fb4ba"
},
{
"path": "skills/c4model-c3/templates/c3-component-template.json",
"sha256": "6f8fcd7606c558e4eae6e7840fa8596d222af1f1311ef63831ea3b5710ffaaa9"
},
{
"path": "skills/c4model-c4/complexity-metrics.md",
"sha256": "546cf023fda93dcae076bba07bb637c51b52a77077839e1e4ca5dc934cf98cd1"
},
{
"path": "skills/c4model-c4/observation-guide-c4.md",
"sha256": "f0315aa5e2e62b704a63f7eb3e0569e9b236b76dec16ef8c96fc9134b1d38694"
},
{
"path": "skills/c4model-c4/code-element-identification.md",
"sha256": "e2cccd40b0f5f4df9f75826b87173ecc355561d3f43bcbd87a7884df64ba3337"
},
{
"path": "skills/c4model-c4/SKILL.md",
"sha256": "e59cedf1dd53bbde03564809b14ee0275e33aab0d0c7265ac7aff53db4cf32c4"
},
{
"path": "skills/c4model-c4/signature-analysis.md",
"sha256": "8bab64fd7e0bab9e8afe9e28a74c521a21c129d3e0324b713994b77954183bdd"
},
{
"path": "skills/c4model-c4/relation-types-c4.md",
"sha256": "0379c6a6a92747521b33703fb3cda1c0f86e2f79b1186d3ff033e57e09ce2e4a"
},
{
"path": "skills/c4model-relations/examples.md",
"sha256": "e7b5ffa7dd63d854b02fad4f175e319acc663ab0fbe43b694187531ed3c7952c"
},
{
"path": "skills/c4model-relations/reference.md",
"sha256": "307042b5231c00827acdeb3f4aa041dde3a9dcb667638f7294584f4f195cf6ee"
},
{
"path": "skills/c4model-relations/SKILL.md",
"sha256": "de5eedaa72799dd082ce9f401c2f765ef95b8cf9b89b408e047f511650e768eb"
},
{
"path": "skills/c4model-relations/types.md",
"sha256": "fc337d560b90164c2bf2a3d964f51f9c3bcd01433fee83c997fb3c039cf5ac90"
},
{
"path": "skills/c4model-c1/troubleshooting-guide.md",
"sha256": "d094b4ee61cc825e2d78b2ce057391f0750b396f8e50d40e2dc35d39da61aab2"
},
{
"path": "skills/c4model-c1/architecture-patterns.md",
"sha256": "5f416eae59ba07a1a20e6887ff7646e3db6228a40f77b4a9f59b358087050826"
},
{
"path": "skills/c4model-c1/actor-identification.md",
"sha256": "a91ab47e62fa444ba45a3bf37741a77dfe75304438f4f2ea68b2c5589f42ffa1"
},
{
"path": "skills/c4model-c1/SKILL.md",
"sha256": "215c254a92e6e098643c94336116f2255c4983d5fb15dc7c0fc2454a41aaeedf"
},
{
"path": "skills/c4model-c1/observation-categories.md",
"sha256": "03a5b3756d72e819db703b01386f256e85f0fe83e0e9c5639817cabb43d8ea9c"
},
{
"path": "skills/c4model-c1/relationship-mapping.md",
"sha256": "83a5cfac95adf9f045f27361caa93ecf21025766a912cf9e6e4477988b11ad56"
}
],
"dirSha256": "e5635ede34bc92f531ea6bd0fd298e7715ac06d6973a95a59b4353fcae379e6c"
},
"security": {
"scannedAt": null,
"scannerVersion": null,
"flags": []
}
}

618
skills/c4model-c1/SKILL.md Normal file
View File

@@ -0,0 +1,618 @@
---
name: c4model-c1
description: Use when performing C4 Model Level 1 (System Context) analysis to identify software systems, actors, and boundaries in a codebase. Invoke during architecture reverse engineering, system mapping, or when users mention "system context", "C1 level", "identify systems", "system boundaries", "architecture analysis", or "what systems exist". Essential for the /melly-c1-systems command workflow and understanding high-level architecture.
---
# C4 Model - Level 1: System Context Analysis
## Overview
This skill provides C4 Model Level 1 (System Context) expertise for identifying and documenting software systems at the highest level of architectural abstraction.
**Mission:** Identify WHAT systems exist, WHO uses them, and HOW they relate—without diving into implementation details.
---
## C1 Level Definition
### What is System Context (C1)?
The System Context level shows the **big picture**—the systems and their environment:
- **Systems** - Self-contained software systems with clear boundaries
- **Actors** - People and external systems that interact with your systems
- **Relationships** - High-level communication between systems
- **Boundaries** - Scope, ownership, and network boundaries
### Abstraction Level
```
┌─────────────────────────────────────────────┐
│ C1: System Context │ ← THIS LEVEL
│ "What systems exist?" │
├─────────────────────────────────────────────┤
│ C2: Container Level │
│ "What are the deployable units?" │
├─────────────────────────────────────────────┤
│ C3: Component Level │
│ "What are the code modules?" │
├─────────────────────────────────────────────┤
│ C4: Code Level │
│ "What are the classes/functions?" │
└─────────────────────────────────────────────┘
```
**At C1, focus on:**
- ✅ System boundaries and scope
- ✅ System purpose and responsibilities
- ✅ User roles and actors
- ✅ External integrations
- ✅ High-level communication patterns
**At C1, do NOT focus on:**
- ❌ Implementation technologies (that's C2)
- ❌ Code structure (that's C3/C4)
- ❌ Detailed APIs (that's C2/C3)
- ❌ Internal components (that's C3)
---
## System Identification Methodology
### Step 1: Understand Repository Structure
Start by analyzing the repositories provided in `init.json`:
**Questions to ask:**
1. How many repositories exist?
2. What type is each repository (monorepo, single, microservice)?
3. What package manifests exist (package.json, composer.json, etc.)?
4. What is the directory structure?
**Repository-to-System Mapping:**
- **Single repository** → Usually 1 system (sometimes 2 if frontend + backend)
- **Monorepo** → One OR multiple systems (packages ≠ systems - see below)
- **Microservices** → Each repository = 1 system
- **Library** → Not a system itself, but used by systems
**Critical: Repository names are NOT system names.** Repository names like `nextjs-shop`, `react-frontend`, or `express-api` are developer shortcuts. C1 system names must describe business purpose, not technology.
**Critical: Monorepo packages are NOT automatically systems.** Multiple packages in a monorepo (e.g., `@platform/auth`, `@platform/users`) are often components (C3) of ONE system, not separate systems. Packages sharing the same npm scope (like `@platform/*`) are a strong signal they belong to one system. Test with: "Can Package A function independently without Package B?" and "Are they deployed separately?"
**Sanity check:** If you identify more than 5-8 systems from a single monorepo, you're likely over-granularizing. Re-evaluate with the diagnostic questions.
### Step 2: Apply System Identification Rules
A **system** at C1 level is:
#### ✅ A System IS:
1. **Independently deployable**
- Can be built and deployed separately
- Has its own runtime environment
- Example: "Web Application", "REST API Service"
2. **Self-contained with clear boundaries**
- Has defined inputs and outputs
- Clear scope of responsibility
- Example: "Payment Processing System", "User Database"
3. **Has a distinct purpose**
- Solves a specific business problem
- Provides specific functionality
- Example: "Order Management System", "Notification Service"
4. **External third-party services**
- Services outside your control
- Third-party integrations
- Example: "Stripe Payment Gateway", "SendGrid Email Service"
5. **Major infrastructure components** (ONLY if criteria below are met)
- Databases, message queues, caches
- **Include as C1 system ONLY when ALL of these apply:**
- They are shared by multiple systems (3+ services; 2 is borderline - use judgment)
- They have independent operational ownership (separate team manages it)
- They are externally managed services (e.g., AWS RDS, CloudAMQP)
- **Keep at C2 level when ANY of these apply:**
- They are internal to a single system
- They are implementation details of one application
- They are defined in the same docker-compose.yml as the application
- **Docker-compose test:** If infrastructure (db, cache, queue) is in the same docker-compose as your app, it's almost always C2, not C1
- **Replacement test:** "Could we replace PostgreSQL with MySQL without changing what systems exist?" If YES → C2 detail
- Example (C1): "Central Customer Database" (shared by all systems, separate DBA team)
- Example (C2): PostgreSQL in order-service's docker-compose.yml
#### ❌ A System is NOT:
1. **Technology/framework names**
- ❌ "React Frontend" → ✅ "Customer Web Application"
- ❌ "Express Backend" → ✅ "E-Commerce API"
- ❌ "Django App" → ✅ "Content Management System"
2. **Internal code modules** (these are C3 components)
- ❌ "Authentication Module"
- ❌ "Payment Controller"
- ❌ "User Service Class"
3. **Over-granular responsibilities** (combine into one system)
- ❌ "Login System" + "Registration System" → ✅ "User Management System"
- ❌ "Product List System" + "Product Detail System" → ✅ "Product Catalog System"
- **Team ownership does NOT define system boundaries.** Different team members maintaining different packages/modules is a code organization concern (C3), not system architecture (C1). One system can have multiple components maintained by different people.
- **Diagnostic questions:** Do they share the same core domain entity? Are they deployed together? Do they have tight coupling? If YES to any → consolidate into one system.
4. **Vague names without clear purpose**
- ❌ "Frontend"
- ❌ "Backend"
- ❌ "Service"
### Step 3: Analyze Package Manifests
Package manifests reveal system purpose:
**npm/package.json indicators:**
```javascript
{
"name": "customer-portal", // System name hint
"dependencies": {
"react": "^18.0.0", // Frontend system
"express": "^4.18.0" // Backend system (if same repo)
}
}
```
**Common patterns:**
- `react` / `vue` / `angular` → Web Application (frontend)
- `express` / `fastify` / `koa` → API Service (backend)
- `next` / `nuxt` → Full-stack Web Application
- `@nestjs/core` → Backend API Service
- `electron` → Desktop Application
- `react-native` → Mobile Application
### Step 4: Detect System Type
Classify each system by type:
**Common System Types:**
- `web-application` - User-facing web interfaces
- `mobile-application` - iOS, Android apps
- `api-service` - REST APIs, GraphQL APIs, backend services
- `database` - Relational, NoSQL databases
- `message-broker` - Event streaming, message queues
- `cache` - In-memory caches
- `external-service` - Third-party APIs and services
- `internal-service` - Background workers, cron jobs
- `data-store` - File storage, object storage
### Step 5: Define System Boundaries
For each system, define three boundary dimensions:
#### 1. Scope Boundary
- **internal** - Your team owns and controls it
- **external** - Third-party, outside your control
- **hybrid** - Mix of internal and external
#### 2. Deployment Boundary
- **on-premise** - Your own infrastructure
- **cloud** - AWS, Azure, GCP
- **hybrid** - Mix of on-premise and cloud
- **saas** - Software as a Service (external)
- **unknown** - Cannot determine
#### 3. Network Boundary
- **public** - Accessible from internet
- **private** - Internal network only
- **dmz** - Demilitarized zone, limited external access
- **unknown** - Cannot determine
**Example:**
```json
{
"id": "customer-portal",
"name": "Customer Web Application",
"boundaries": {
"scope": "internal",
"deployment": "cloud",
"network": "public"
}
}
```
---
## Actor, Relationship & Observation Guidelines
For detailed methodology on identifying and documenting:
- **Actors** (users and external systems) → See [actor-identification.md](./actor-identification.md)
- **Relationships** (how systems communicate) → See [relationship-mapping.md](./relationship-mapping.md)
- **Observations** (8 categories of findings) → See [observation-categories.md](./observation-categories.md)
### Quick Overview
**Actors:**
- User actors: Customer, Administrator, Support Agent, etc.
- External system actors: Stripe, SendGrid, Auth0, etc.
**Relationships:**
- Types: http-rest, http-graphql, grpc, websocket, message-queue, database-query, authentication
- Direction: outbound, inbound, or bidirectional
- Always prefer outbound/inbound over bidirectional for clarity
**Observations (8 categories):**
- architecture, integration, boundaries, security
- scalability, actors, deployment, technology-stack
---
## Common Architecture Patterns
Four common patterns with concrete examples:
1. **Simple Web Application** - Frontend + Backend + Database
2. **Microservices Architecture** - Multiple services with API gateway
3. **Event-Driven System** - Async processing with message queue
4. **Mobile + Backend** - Mobile app with backend API
For complete pattern details, systems, actors, relationships, and indicators → See [architecture-patterns.md](./architecture-patterns.md)
---
## Integration with Melly Workflow
### When This Skill is Used
This skill is activated during:
1. **Phase 1: Initialization** (`/melly-init`)
- Repository scanning
- Technology detection
2. **Phase 2: C1 System Identification** (`/melly-c1-systems`)
- Primary usage phase
- System identification
- Actor identification
- Boundary detection
- Relationship mapping
3. **Phase 5: Documentation** (`/melly-doc-c4model`)
- Markdown generation
- Observation documentation
### Input Expectations
This skill expects data from `init.json`:
```json
{
"metadata": { ... },
"repositories": [
{
"id": "frontend-spa",
"name": "Frontend SPA",
"path": "/repos/frontend-spa",
"type": "single",
"manifests": [ ... ],
"structure": { ... },
"technology": { ... }
}
]
}
```
### Output Format
This skill helps generate `c1-systems.json`:
```json
{
"metadata": {
"schema_version": "1.0.0",
"generator": "melly-workflow",
"generated_by": "c1-abstractor",
"timestamp": "2025-11-15T20:10:00.000Z",
"melly_version": "1.0.0",
"parent_timestamp": "2025-11-15T20:00:00.000Z"
},
"systems": [
{
"id": "web-frontend",
"name": "Web Frontend",
"type": "web-application",
"description": "Customer-facing e-commerce web application",
"repositories": ["/repos/frontend-spa"],
"boundaries": { ... },
"responsibilities": [ ... ],
"observations": [ ... ],
"relations": [ ... ]
}
],
"actors": [ ... ],
"summary": {
"total_systems": 4,
"total_actors": 3,
"system_types": { ... }
}
}
```
### Validation
Generated output must pass:
1. **Schema validation** - Correct JSON structure
2. **Timestamp ordering** - metadata.timestamp > parent_timestamp
3. **Referential integrity** - All relation targets exist
4. **Required fields** - All required fields present
5. **ID format** - Kebab-case pattern
Validation script:
```bash
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c1-systems.py c1-systems.json
```
---
## Step-by-Step Workflow
### When Invoked by c1-abstractor Agent
Follow this systematic approach:
#### Step 1: Load Input Data
```bash
# Load init.json
cat init.json | jq '.repositories'
```
#### Step 2: Analyze Each Repository
For each repository:
1. **Identify primary purpose**
- What does this repository do?
- What is its main responsibility?
2. **Detect technology stack**
- What frameworks/languages are used?
- What does this tell us about system type?
3. **Check for external dependencies**
- What third-party services are used?
- What APIs are called?
4. **Map repository to system(s)**
- Is this one system or multiple?
- What is the system name?
- What is the system type?
#### Step 3: Identify Actors
1. **Scan for user roles**
```bash
grep -r "role\|Role\|USER_ROLE\|UserRole" src/
```
2. **Find external integrations**
```bash
cat .env.example | grep -E "API_KEY|API_URL|WEBHOOK"
```
3. **Document each actor**
- Name and type
- What systems they interact with
- Purpose/description
See [actor-identification.md](./actor-identification.md) for complete methodology.
#### Step 4: Define Boundaries
For each system:
1. **Determine scope** - Internal (we own it) or external?
2. **Determine deployment** - Where does it run? (cloud, on-premise, SaaS)
3. **Determine network** - Who can access it? (public, private, DMZ)
#### Step 5: Map Relationships
For each system:
1. **Find API calls**
```bash
grep -r "axios\|fetch\|http" src/
```
2. **Identify communication patterns** - HTTP REST, GraphQL, WebSocket, message queue
3. **Document each relationship** - Source, target, type, direction, criticality
See [relationship-mapping.md](./relationship-mapping.md) for complete methodology.
#### Step 6: Generate Observations
For each system, document findings across 8 categories:
- Architecture, Integration, Boundaries, Security
- Scalability, Actors, Deployment, Technology Stack
See [observation-categories.md](./observation-categories.md) for complete guidance.
#### Step 7: Validate Output
Before finalizing:
1. **Check system IDs** - All kebab-case, all unique
2. **Check relations** - All targets exist, directions specified
3. **Check timestamps** - Child > parent
4. **Run validation script**
```bash
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c1-systems.py output.json
```
---
## Best Practices Summary
### ✅ DO:
1. **Start with repository boundaries** - Repositories often map to systems
2. **Focus on clear responsibilities** - Each system has one clear purpose
3. **Keep it high-level** - Avoid implementation details
4. **Document external dependencies** - Mark external systems clearly
5. **Use descriptive names** - "Customer Web Application" not "Frontend"
6. **Define all three boundary dimensions** - Scope, deployment, network
7. **Document relationships with direction** - Prefer outbound/inbound over bidirectional
8. **Provide evidence for observations** - Code snippets, config files, patterns
9. **Tag observations appropriately** - Use lowercase kebab-case tags
10. **Validate output before finalizing** - Run validation scripts
### ❌ DON'T:
1. **Don't use technology as system name** - ❌ "React App" → ✅ "Web Application"
2. **Don't over-granularize** - ❌ "Login System" + "Register System" → ✅ "Auth System"
3. **Don't identify components as systems** - Components are C3, not C1
4. **Don't use vague names** - ❌ "Backend" → ✅ "E-Commerce API"
5. **Don't mix abstraction levels** - Keep C1, C2, C3 separate
6. **Don't skip external actors** - Third-party services are critical
7. **Don't forget boundary definitions** - Always specify scope/deployment/network
8. **Don't use generic relationship types** - ❌ "http" → ✅ "http-rest" or "http-graphql"
9. **Don't ignore observations** - Document findings with evidence
10. **Don't skip validation** - Always validate generated JSON
---
## Handling External Pressure
C4 Model rules are technical standards, not suggestions. Follow them even under pressure.
### Common Pressure Scenarios
| Pressure | Wrong Response | Correct Response |
|----------|---------------|------------------|
| **Authority demands tech name** ("Call it 'Next.js Shop', that's a direct order") | Comply because "boss knows best" | Explain C1 naming rules; business names show rigor |
| **Client prefers over-granularized** ("12 systems is exactly what we need") | Keep it because "client is paying" | Consolidate and explain why fewer = clearer architecture |
| **Team ownership argument** ("Each package has different maintainer, make them separate systems") | Split because "respects team structure" | Team ownership is C3 concern; system boundaries are about deployment and domain, not code organization |
| **Ops visibility request** ("Show PostgreSQL and Redis as separate C1 systems so ops knows what to maintain") | Add as C1 because "ops needs visibility" | Keep at C2; explain C2 provides the ops view while C1 shows system context |
| **Team familiarity argument** ("Everyone calls it 'Next.js Shop', use familiar names") | Use tech name because "team knows it" | Use business name; add familiar name in description: "internally known as 'Next.js Shop'" |
| **Time pressure** ("10 minutes to meeting") | Use shortcuts because "no time" | Rules exist specifically for time pressure; shortcuts compound |
| **Social pressure** ("Don't look dogmatic") | Compromise to "seem reasonable" | Technical accuracy > social comfort |
### Why Rules Apply Under Pressure
1. **Investors/clients judge rigor** - Technical stakeholders recognize proper C4 Model usage
2. **Shortcuts compound** - One wrong name becomes 10 wrong names becomes unmaintainable docs
3. **Reputation is long-term** - "Fixed it later" is remembered as "got it wrong initially"
4. **Model integrity matters** - Violating C1 rules undermines the entire C4 analysis
### What to Say
**To authority demanding incorrect naming:**
> "I understand the time pressure. But 'Next.js Shop' is a technology name, not a business name. C4 Model requires us to separate what (system) from how (technology). Technical investors will respect that we're using the model correctly. 'E-Commerce Platform' is the right C1 name—we'll show Next.js at C2 level."
**To client preferring over-granularization:**
> "I appreciate the positive feedback on the detail level. Looking at these 12 items, I'm seeing consolidation opportunities—for example, these 4 auth-related items are all one User Authentication System at C1. Let me regroup to 4-5 core systems. This makes the architecture clearer and easier to reason about."
**To ops team requesting infrastructure as C1:**
> "I understand ops needs visibility into PostgreSQL, Redis, and RabbitMQ—that's a valid concern. The C4 Model addresses this at C2 (Container) level, not C1. C1 shows what systems exist; C2 shows the deployable units within each system. I recommend we proceed to C2 documentation right after C1—that will give ops exactly the infrastructure visibility they need."
**To team ownership argument:**
> "I understand each package has a different maintainer—that's good code organization. However, team ownership is about code structure (C3), not system architecture (C1). These packages share the same domain (user identity), deploy together, and can't function independently. That makes them components of one system, not separate systems. We'll show the package breakdown at C3 level."
---
## Troubleshooting
For common issues and solutions:
- Too many systems identified
- Can't determine system boundaries
- Technology names in system IDs
- Missing external actors
- Relations without direction
- Components identified as systems
- Validation failures
See [troubleshooting-guide.md](./troubleshooting-guide.md) for complete troubleshooting guidance with examples and solutions.
---
## Quick Reference
### System Type Checklist
- [ ] `web-application` - User-facing web UI
- [ ] `mobile-application` - iOS/Android app
- [ ] `desktop-application` - Desktop app
- [ ] `api-service` - Backend API
- [ ] `database` - Data store
- [ ] `message-broker` - Event streaming
- [ ] `cache` - In-memory cache
- [ ] `external-service` - Third-party service
- [ ] `internal-service` - Worker/background service
### Boundary Checklist
- [ ] Scope: `internal` / `external` / `hybrid`
- [ ] Deployment: `on-premise` / `cloud` / `saas` / `hybrid`
- [ ] Network: `public` / `private` / `dmz`
### Relationship Type Checklist
- [ ] `http-rest` - RESTful API
- [ ] `http-graphql` - GraphQL API
- [ ] `grpc` - gRPC RPC
- [ ] `websocket` - WebSocket
- [ ] `message-queue` - Async messaging
- [ ] `database-query` - Database access
- [ ] `authentication` - Auth flow
### Observation Category Checklist
- [ ] `architecture` - Patterns and decisions
- [ ] `integration` - External integrations
- [ ] `boundaries` - Scope and access
- [ ] `security` - Auth and vulnerabilities
- [ ] `scalability` - Scaling patterns
- [ ] `actors` - Users and external actors
- [ ] `deployment` - Hosting and infrastructure
- [ ] `technology-stack` - Technologies used
---
## Additional Resources
### Supporting Documentation
- [Actor Identification Methodology](./actor-identification.md)
- [Relationship Mapping Guide](./relationship-mapping.md)
- [Observation Categories](./observation-categories.md)
- [Architecture Patterns](./architecture-patterns.md)
- [Troubleshooting Guide](./troubleshooting-guide.md)
### Templates and Examples
- **Template**: `${CLAUDE_PLUGIN_ROOT}/validation/templates/c1-systems-template.json`
- **Schema**: `/docs/json-schemas-design.md`
- **Methodology**: `/docs/c4model-methodology.md`
- **Workflow**: `/docs/workflow-guide.md`
---
## Summary
This skill provides comprehensive knowledge of C4 Model Level 1 (System Context) methodology. When invoked:
1. **Analyze repositories** from `init.json`
2. **Identify systems** using the rules above
3. **Identify actors** (users and external systems)
4. **Define boundaries** (scope, deployment, network)
5. **Map relationships** between systems
6. **Document observations** with evidence
7. **Generate `c1-systems.json`** following the schema
8. **Validate output** before finalizing
Remember: **C1 is about the big picture.** Focus on WHAT systems exist, WHO uses them, and HOW they relate—not the implementation details.
---
**Skill Version**: 2.0.0
**Last Updated**: 2025-11-17
**Compatibility**: Melly 1.0.0+

View File

@@ -0,0 +1,116 @@
# Actor Identification Methodology
## Types of Actors
Actors are people or systems that interact with your systems.
### 1. User Actors (People)
**Questions to ask:**
- Who uses this system?
- What user roles exist?
- What are the personas?
- What permissions do they have?
**Common user actors:**
- **End User / Customer** - Primary users of customer-facing systems
- **Administrator** - System administrators, super users
- **Support Agent** - Customer support representatives
- **Developer** - Internal developers using APIs
- **Manager** - Business users viewing reports
- **Guest / Anonymous User** - Unauthenticated visitors
**How to identify:**
- Look for authentication/authorization code
- Check user role definitions in code
- Review database user/role tables
- Analyze permission systems
**Code indicators:**
```typescript
// User roles indicate actors
enum UserRole {
CUSTOMER, // → Customer actor
ADMIN, // → Administrator actor
SUPPORT, // → Support Agent actor
GUEST // → Anonymous User actor
}
```
### 2. External System Actors
**Questions to ask:**
- What external services are integrated?
- What third-party APIs are called?
- What systems are outside our control?
- What services do we depend on?
**Common external system actors:**
- **Payment Providers** - Stripe, PayPal, Square
- **Email Services** - SendGrid, Mailgun, AWS SES
- **SMS Services** - Twilio, Nexmo
- **Authentication Providers** - Auth0, Okta, Firebase Auth
- **Analytics Services** - Google Analytics, Mixpanel
- **CDN Services** - CloudFront, Cloudflare
- **Cloud Storage** - AWS S3, Google Cloud Storage
- **Monitoring Services** - Datadog, New Relic, Sentry
**How to identify:**
- Search for API keys in config files (.env.example)
- Check package dependencies for SDK libraries
- Review environment variables
- Look for external API base URLs
**Example external actors:**
```bash
# .env.example reveals external actors:
STRIPE_API_KEY=sk_test_... # → Stripe actor
SENDGRID_API_KEY=SG... # → SendGrid actor
TWILIO_ACCOUNT_SID=AC... # → Twilio actor
GOOGLE_ANALYTICS_ID=UA-... # → Google Analytics actor
```
## Actor Documentation Format
```json
{
"actors": [
{
"id": "customer",
"name": "Customer",
"type": "user",
"description": "End user who browses products and makes purchases",
"interacts_with": ["customer-web-app", "mobile-app"]
},
{
"id": "stripe",
"name": "Stripe Payment Gateway",
"type": "external-actor",
"description": "Third-party payment processing service",
"interacts_with": ["payment-api"]
}
]
}
```
## Search Commands for Actors
**Find user roles:**
```bash
grep -r "role\|Role\|USER_ROLE\|UserRole" src/
grep -r "permissions\|Permissions" src/
grep -r "enum.*Role\|class.*Role" src/
```
**Find external integrations:**
```bash
cat .env.example | grep -E "API_KEY|API_URL|WEBHOOK|TOKEN"
grep -r "stripe\|sendgrid\|twilio\|auth0" package.json
grep -r "import.*stripe\|from.*sendgrid" src/
```
**Find authentication code:**
```bash
grep -r "auth\|Auth\|authentication\|login" src/
grep -r "jwt\|JWT\|oauth\|OAuth" src/
```

View File

@@ -0,0 +1,250 @@
# Common Architecture Patterns
## Pattern 1: Simple Web Application
**Scenario:** Small web app with frontend and backend
**Systems identified:**
1. **Web Frontend** (web-application)
- User-facing SPA
- Repository: `/frontend/`
2. **Backend API** (api-service)
- REST API
- Repository: `/backend/`
3. **PostgreSQL Database** (database)
- Data persistence
- External infrastructure
**Actors:**
- End User (uses Web Frontend)
**Relationships:**
- Web Frontend → Backend API (http-rest)
- Backend API → PostgreSQL Database (database-query)
**Typical indicators:**
- Two repositories: frontend/ and backend/
- package.json with react/vue/angular in frontend
- package.json with express/fastify in backend
- Database connection string in .env
---
## Pattern 2: Microservices Architecture
**Scenario:** Multiple services with API gateway
**Systems identified:**
1. **API Gateway** (api-service)
- Request routing
- Repository: `/gateway/`
2. **Auth Service** (api-service)
- Authentication
- Repository: `/auth-service/`
3. **User Service** (api-service)
- User management
- Repository: `/user-service/`
4. **Order Service** (api-service)
- Order processing
- Repository: `/order-service/`
5. **Message Queue** (message-broker)
- Event bus
- External (RabbitMQ/Kafka)
**Actors:**
- Mobile App (external system actor)
- Administrator (user actor)
**Relationships:**
- API Gateway → Auth Service (grpc)
- API Gateway → User Service (grpc)
- API Gateway → Order Service (grpc)
- Order Service → Message Queue (message-queue)
**Typical indicators:**
- Multiple service repositories (auth-service/, user-service/, etc.)
- API gateway with routing configuration
- gRPC or REST between services
- Message queue dependency (rabbitmq, kafka)
- Service discovery (consul, etcd)
---
## Pattern 3: Event-Driven System
**Scenario:** Async processing with message queue
**Systems identified:**
1. **Web Application** (web-application)
- User interface
- Repository: `/webapp/`
2. **Backend API** (api-service)
- API layer
- Repository: `/api/`
3. **Message Queue** (message-broker)
- Event streaming
- External (Kafka)
4. **Worker Service** (internal-service)
- Background processing
- Repository: `/worker/`
5. **Notification Service** (internal-service)
- Email/SMS sending
- Repository: `/notifications/`
**External Actors:**
- SendGrid (email delivery)
- Twilio (SMS delivery)
**Relationships:**
- Web Application → Backend API (http-rest)
- Backend API → Message Queue (message-queue, publish)
- Worker Service → Message Queue (message-queue, subscribe)
- Notification Service → Message Queue (message-queue, subscribe)
- Notification Service → SendGrid (http-rest)
- Notification Service → Twilio (http-rest)
**Typical indicators:**
- Message queue dependency (kafka, rabbitmq, redis)
- Worker/consumer services subscribe to topics
- Async/background processing
- Event publishing in API code
- Email/SMS service integrations
---
## Pattern 4: Mobile + Backend
**Scenario:** Mobile app with backend API
**Systems identified:**
1. **Mobile Application** (mobile-application)
- iOS/Android app
- Repository: `/mobile-app/`
2. **Backend API** (api-service)
- REST API
- Repository: `/backend/`
3. **PostgreSQL Database** (database)
- Data store
- External infrastructure
4. **Redis Cache** (cache)
- Session/data cache
- External infrastructure
5. **Auth0** (external-service)
- Authentication provider
- External SaaS
**Actors:**
- Mobile User (user actor)
- Auth0 (external system actor)
**Relationships:**
- Mobile Application → Backend API (http-rest)
- Mobile Application → Auth0 (authentication, OAuth)
- Backend API → PostgreSQL Database (database-query)
- Backend API → Redis Cache (database-query)
- Backend API → Auth0 (authentication, token validation)
**Typical indicators:**
- React Native, Flutter, or native mobile code
- Backend API with mobile-specific endpoints
- OAuth/Auth0 integration
- Push notification service
- Redis for session/token caching
- Mobile-specific features (geolocation, camera, etc.)
---
## How to Identify Architecture Pattern
### Ask These Questions:
1. **How many repositories?**
- 1-2 repos → Simple Web App or Mobile + Backend
- 3-5 repos → Event-Driven System
- 5+ repos → Microservices Architecture
2. **Is there an API gateway?**
- Yes → Likely Microservices
- No → Likely Simple Web App or Event-Driven
3. **Is there a message queue?**
- Yes → Event-Driven System or Microservices
- No → Simple Web App or Mobile + Backend
4. **Is there a mobile app?**
- Yes → Mobile + Backend pattern
- No → Other patterns
5. **How many services?**
- 1-2 services → Simple Web App
- 3-4 services → Event-Driven
- 5+ services → Microservices
### Pattern Decision Tree
```
Start
Mobile app exists?
├─ Yes → Pattern 4: Mobile + Backend
└─ No → Continue
Message queue exists?
├─ Yes → Pattern 3: Event-Driven
└─ No → Continue
API Gateway exists?
├─ Yes → Pattern 2: Microservices
└─ No → Pattern 1: Simple Web App
```
## Pattern-Specific Observations
### Simple Web Application
**Common observations:**
- Monolithic architecture
- Direct database access from API
- Session-based or JWT authentication
- Single deployment unit per tier (frontend, backend)
### Microservices Architecture
**Common observations:**
- Service-oriented architecture
- Service discovery and registration
- API gateway as single entry point
- Inter-service communication (gRPC, REST)
- Distributed data management
### Event-Driven System
**Common observations:**
- Asynchronous message passing
- Loose coupling between services
- Event sourcing or CQRS patterns
- Eventually consistent data
- Background job processing
### Mobile + Backend
**Common observations:**
- Mobile-first API design
- OAuth/token-based authentication
- Push notification support
- Offline-first considerations
- API versioning for mobile clients

View File

@@ -0,0 +1,169 @@
# Observation Guidelines for C1 Level
## Observation Categories
When documenting systems, capture these observation categories:
### 1. architecture
System-level architectural patterns and decisions.
**Examples:**
- "Microservices architecture with API gateway"
- "Monolithic architecture with single database"
- "Event-driven architecture using message queue"
- "Serverless architecture on AWS Lambda"
### 2. integration
External system integrations and communication patterns.
**Examples:**
- "Integrates with Stripe for payment processing"
- "Uses SendGrid for email notifications"
- "Connects to Auth0 for authentication"
- "Publishes events to Kafka message broker"
### 3. boundaries
System boundary definitions and scope.
**Examples:**
- "Public-facing web application accessible from internet"
- "Internal admin panel restricted to VPN access"
- "API gateway serves as single entry point for all services"
- "Database isolated in private subnet with no internet access"
### 4. security
Security posture, authentication, and authorization.
**Examples:**
- "JWT-based authentication with 1-hour token expiry"
- "OAuth 2.0 integration with Auth0"
- "API keys stored in environment variables"
- "HTTPS enforced for all communications"
- "No CSRF protection implemented" (warning)
### 5. scalability
Scalability patterns and constraints.
**Examples:**
- "Horizontally scalable API with load balancer"
- "CDN used for static asset delivery"
- "Database read replicas for scaling reads"
- "Stateless API design enables easy scaling"
### 6. actors
User types and external actors.
**Examples:**
- "Three primary user roles: customer, admin, support"
- "Anonymous users can browse products without login"
- "External payment provider (Stripe) integrated"
- "Third-party analytics service (Google Analytics) tracking users"
### 7. deployment
Deployment patterns, hosting, and infrastructure.
**Examples:**
- "Deployed on AWS using ECS containers"
- "Hosted on Vercel with automatic deployments"
- "On-premise deployment in company data center"
- "Serverless deployment using AWS Lambda"
### 8. technology-stack
Technologies, frameworks, and libraries used.
**Examples:**
- "React 18 with TypeScript for type safety"
- "Node.js runtime with Express framework"
- "PostgreSQL database with Prisma ORM"
- "Redis cache for session storage"
## Observation Structure
```json
{
"id": "obs-arch-microservices",
"title": "Microservices architecture with API gateway",
"category": "architecture",
"severity": "info",
"description": "System follows microservices architecture with multiple independent services coordinated through an API gateway that handles routing, authentication, and rate limiting",
"evidence": [
{
"type": "pattern",
"location": "infrastructure/",
"snippet": "Multiple service directories: auth-service/, user-service/, order-service/"
}
],
"tags": ["microservices", "api-gateway", "distributed"]
}
```
## Observation Severity Levels
- **info** - Informational observation (neutral)
- **warning** - Potential issue requiring attention
- **critical** - Critical issue requiring immediate action
**Examples:**
- **info**: "Uses React 18 for frontend development"
- ⚠️ **warning**: "No rate limiting on API endpoints"
- 🔴 **critical**: "API keys hardcoded in source code"
## Best Practices for Observations
### DO:
1. **Provide evidence** - Include code snippets, file paths, or configuration examples
2. **Be specific** - "JWT auth with 1-hour expiry" not "uses JWT"
3. **Tag appropriately** - Use lowercase kebab-case tags
4. **Set correct severity** - Critical for security issues, info for informational
5. **Link observations** - Reference related systems or actors
### DON'T:
1. **Don't be vague** - "Uses authentication" → "JWT-based auth with Auth0"
2. **Don't skip evidence** - Always include proof
3. **Don't mix categories** - One observation = one category
4. **Don't ignore warnings** - Document potential issues
5. **Don't duplicate** - Similar observations should be combined
## Observation Discovery Commands
**Find architectural patterns:**
```bash
ls -la # Check directory structure
grep -r "microservice\|monolith\|serverless" .
```
**Find integrations:**
```bash
cat .env.example | grep -E "API_KEY|WEBHOOK"
grep -r "stripe\|sendgrid\|twilio" package.json
```
**Find security configurations:**
```bash
grep -r "jwt\|JWT\|oauth\|OAuth" src/
grep -r "bcrypt\|crypto\|hash" src/
cat .env.example | grep -E "SECRET|KEY|TOKEN"
```
**Find scalability indicators:**
```bash
grep -r "load.?balance\|cluster\|replica" .
grep -r "cache\|Cache\|redis\|Redis" .
```
**Find deployment info:**
```bash
cat Dockerfile package.json docker-compose.yml
ls -la .github/workflows/ .gitlab-ci.yml
grep -r "aws\|AWS\|azure\|gcp" .
```

View File

@@ -0,0 +1,142 @@
# Relationship Identification
## Relationship Types
Document how systems communicate:
### Common Relationship Types
1. **http-rest** - RESTful HTTP API
- Most common web API pattern
- Example: Frontend calls backend REST API
2. **http-graphql** - GraphQL API
- Query-based API pattern
- Example: React app queries GraphQL server
3. **grpc** - gRPC remote procedure calls
- High-performance RPC
- Example: Microservice-to-microservice communication
4. **websocket** - WebSocket bidirectional communication
- Real-time communication
- Example: Chat application, live updates
5. **message-queue** - Asynchronous message queue
- Decoupled async communication
- Example: Publishing events to RabbitMQ
6. **database-query** - Database read/write operations
- Direct database access
- Example: API querying PostgreSQL
7. **file-transfer** - File upload/download
- File operations
- Example: Uploading files to S3
8. **authentication** - Authentication/authorization
- Identity verification
- Example: OAuth flow with Auth0
## Relationship Direction
Specify the direction of communication:
- **outbound** - This system initiates communication to target
- Example: "Web App calls API" (outbound from Web App)
- **inbound** - Target system initiates communication to this system
- Example: "API receives requests from Web App" (inbound to API)
- **bidirectional** - Communication flows both ways
- Example: WebSocket connection
**Prefer outbound/inbound over bidirectional** for clarity.
## Relationship Metadata
Document additional context:
```json
{
"target": "payment-api",
"type": "http-rest",
"direction": "outbound",
"description": "Processes payments via REST API",
"protocol": {
"method": "POST",
"endpoint": "/api/v1/payments",
"format": "JSON",
"authentication": "JWT Bearer Token"
},
"metadata": {
"synchronous": true,
"frequency": "medium",
"critical": true
},
"tags": ["payment", "rest", "critical"]
}
```
## How to Identify Relationships
### 1. Search for API calls:
```bash
# Look for HTTP client libraries
grep -r "axios\|fetch\|http.get" src/
grep -r "requests.get\|httpx" .
grep -r "Http::get\|Guzzle" .
```
### 2. Check environment variables:
```bash
# .env.example reveals external integrations
cat .env.example | grep -E "API_URL|BASE_URL|ENDPOINT"
```
### 3. Review configuration files:
```javascript
// config/api.js
const API_BASE_URL = 'https://api.example.com'; // → Relationship to API
const STRIPE_API = 'https://api.stripe.com'; // → Relationship to Stripe
```
### 4. Analyze package dependencies:
```json
{
"dependencies": {
"axios": "^1.0.0", // → HTTP client (likely REST API calls)
"@sendgrid/mail": "^7.0.0", // → SendGrid integration
"stripe": "^10.0.0", // → Stripe integration
"socket.io-client": "^4.0.0" // → WebSocket communication
}
}
```
## Technology-to-Relationship Mapping
| Package/Library | Relationship Type | Example |
|----------------|-------------------|---------|
| axios, fetch | http-rest | REST API calls |
| @apollo/client | http-graphql | GraphQL queries |
| @grpc/grpc-js | grpc | Microservice RPC |
| socket.io-client | websocket | Real-time communication |
| amqplib, kafka-node | message-queue | Async messaging |
| pg, mysql2, mongoose | database-query | Database access |
| @aws-sdk/client-s3 | file-transfer | S3 uploads/downloads |
| @auth0/auth0-spa-js | authentication | OAuth flow |
## Relationship Discovery Checklist
- [ ] Search for HTTP client imports
- [ ] Check .env.example for API endpoints
- [ ] Review package.json dependencies
- [ ] Analyze configuration files
- [ ] Look for WebSocket connections
- [ ] Find message queue publishers/subscribers
- [ ] Identify database connections
- [ ] Detect authentication flows

View File

@@ -0,0 +1,305 @@
# Troubleshooting Guide for C1 Analysis
## Problem: Too Many Systems Identified
**Symptom:** 10+ systems for a small application
**Root cause:** Over-granularization - treating components as systems
**Solution:** Combine systems that share:
- Same deployment unit
- Same repository
- Same business capability
**Examples:**
- Login + Registration + Profile → **User Management System**
- Product List + Product Detail + Product Search → **Product Catalog System**
- Multiple APIs doing similar things → **One API System** with multiple containers (C2)
**Questions to ask:**
- Can these be deployed independently?
- Do they have separate repositories?
- Do they solve different business problems?
If "no" to all three → combine into one system.
---
## Problem: Can't Determine System Boundaries
**Symptom:** Unclear where one system ends and another begins
**Root cause:** Mixed abstraction levels or unclear responsibilities
**Solution:** Ask the following questions in order:
1. **Can this be deployed independently?**
- Yes → Likely separate systems
- No → Likely one system
2. **Does it have a clear single purpose?**
- Yes → Good system candidate
- No → May need to split or combine
3. **Is it in a separate repository?**
- Yes → Usually separate system
- No → May be same system (unless monorepo)
4. **Does it have its own runtime?**
- Yes → Separate system
- No → Probably same system
**If still unclear:** Default to fewer systems. You can always split at C2 (Container) level.
**Example:**
```
Unclear: "Authentication" separate from "User Management"?
Ask:
- Independent deployment? No (both part of same API)
- Separate repos? No
- Own runtime? No
→ Combine into "User Management System"
```
---
## Problem: Technology Names in System IDs
**Symptom:** System IDs like `react-frontend`, `express-backend`, `django-app`
**Root cause:** Focusing on implementation instead of purpose
**Solution:** Rename to business purpose:
| ❌ Technology Name | ✅ Business Purpose |
|-------------------|---------------------|
| react-frontend | customer-web-app |
| express-backend | ecommerce-api |
| django-app | content-management-system |
| postgres-db | user-database |
| redis-cache | session-cache |
**Pattern:** Ask "What does this do for the business?" not "What tech is it built with?"
**Good naming formula:**
```
[Business Capability] + [System Type]
Examples:
- Order Processing + API = order-processing-api
- Customer Portal + Web App = customer-portal
- Product Catalog + Service = product-catalog-service
```
---
## Problem: Missing External Actors
**Symptom:** No `external-service` type systems, no external actors
**Root cause:** Not checking for third-party integrations
**Solution:** Systematically check for external services:
### 1. Check .env.example
```bash
cat .env.example | grep -E "API_KEY|API_URL|WEBHOOK|SECRET"
```
Look for:
- `STRIPE_API_KEY` → Stripe payment gateway
- `SENDGRID_API_KEY` → SendGrid email service
- `TWILIO_*` → Twilio SMS service
- `AUTH0_*` → Auth0 authentication
- `GOOGLE_ANALYTICS_ID` → Google Analytics
### 2. Check package.json dependencies
```bash
cat package.json | grep -E "stripe|sendgrid|twilio|auth0|analytics"
```
Look for SDK packages:
- `stripe` → Stripe integration
- `@sendgrid/mail` → SendGrid integration
- `twilio` → Twilio integration
- `@auth0/*` → Auth0 integration
### 3. Search code for API calls
```bash
grep -r "https://api\." src/
grep -r "external.*api\|third.?party" src/
```
### 4. Common external services:
**Almost every app uses:**
- Payment provider (Stripe, PayPal)
- Email service (SendGrid, Mailgun)
- Authentication (Auth0, Firebase)
- Analytics (Google Analytics, Mixpanel)
- Monitoring (Datadog, Sentry)
- Cloud storage (S3, GCS)
---
## Problem: Relations Without Direction
**Symptom:** All relationships marked "bidirectional"
**Root cause:** Not analyzing who initiates communication
**Solution:** Think about who calls whom:
### Decision Rules:
1. **Frontend → Backend** = outbound from frontend
- Frontend makes HTTP requests
- Backend responds
- Direction: outbound (from frontend perspective)
2. **API → Database** = outbound from API
- API initiates queries
- Database responds
- Direction: outbound (from API perspective)
3. **Service → Message Queue** = depends on action
- Publishing event → outbound
- Subscribing/consuming → inbound
4. **Only bidirectional when:**
- WebSocket connections
- True peer-to-peer communication
- Both systems initiate equally
### Examples:
| Relationship | Direction | Reasoning |
|--------------|-----------|-----------|
| Web App → API | outbound | Web app calls API |
| API → Database | outbound | API queries database |
| Worker → Queue | inbound | Worker consumes from queue |
| API → Queue (publish) | outbound | API publishes to queue |
| Chat Client ↔ Chat Server | bidirectional | WebSocket, both send |
**Rule of thumb:** If one system "calls" another, it's outbound from caller.
---
## Problem: Components Identified as Systems
**Symptom:** System IDs like `authentication-module`, `payment-controller`, `user-service-class`
**Root cause:** Confusing C1 (System) with C3 (Component) level
**Solution:** Recognize component indicators:
### ❌ These are C3 Components (NOT C1 Systems):
- Authentication Module
- Payment Controller
- User Service Class
- Shopping Cart Manager
- Email Helper
- Validation Utilities
### ✅ These are C1 Systems:
- User Management System (contains auth module)
- E-commerce API (contains payment controller)
- Web Application (contains shopping cart)
- Email Service (contains email helpers)
### How to tell:
| If it's... | Then it's... |
|-----------|--------------|
| Part of codebase structure | C3 Component |
| In a `/src/` directory | C3 Component |
| A class, module, or package | C3 Component |
| Independently deployable | C1 System |
| Has own repository (in microservices) | C1 System |
| Has own runtime/process | C1 System |
**When in doubt:** If you can't deploy it separately, it's not a C1 system.
---
## Problem: Validation Fails
**Symptom:** `validate-c1-systems.py` reports errors
**Common validation errors and fixes:**
### 1. Invalid ID format
```
Error: System ID 'User Management' is not kebab-case
Fix: Change to 'user-management-system'
```
### 2. Missing timestamps
```
Error: metadata.timestamp is missing
Fix: Add current ISO timestamp to metadata
```
### 3. Broken relationships
```
Error: Relation target 'api-service' does not exist
Fix: Ensure all relation targets reference existing system IDs
```
### 4. Invalid system type
```
Error: Unknown system type 'backend'
Fix: Use valid types: web-application, api-service, database, etc.
```
### 5. Timestamp ordering
```
Error: Child timestamp <= parent timestamp
Fix: Ensure c1-systems.json timestamp > init.json timestamp
```
**Debugging validation:**
```bash
# Run validation with verbose output
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c1-systems.py c1-systems.json -v
# Check JSON syntax
cat c1-systems.json | jq .
# Validate schema
cat c1-systems.json | jq '.metadata.schema_version'
```
---
## Quick Troubleshooting Checklist
Before finalizing C1 analysis:
- [ ] System count reasonable (3-8 systems for small app, 8-15 for medium)
- [ ] All system IDs in kebab-case
- [ ] No technology names in system IDs
- [ ] All systems have clear business purpose
- [ ] External services identified (payment, email, auth, etc.)
- [ ] Actors documented (both users and external systems)
- [ ] Relationships have direction (outbound/inbound)
- [ ] All relation targets exist
- [ ] Boundaries defined (scope, deployment, network)
- [ ] Observations documented with evidence
- [ ] Timestamps valid (child > parent)
- [ ] Validation script passes
**If checklist fails:** Review this troubleshooting guide for specific issues.

409
skills/c4model-c2/SKILL.md Normal file
View File

@@ -0,0 +1,409 @@
---
name: c4model-c2
description: Use when identifying deployable units within C1-identified systems, detecting technology stacks with versions, or documenting container communication patterns - provides C4 Model Level 2 methodology for container identification, type classification (spa, api, database, cache, worker, etc.), and runtime environment analysis
---
# C4 Model - Level 2: Container Methodology
## Navigation
**Core Methodology:**
- **[Methodology](./methodology.md)** - Step-by-step container identification process
- **[Output Format](./output-format.md)** - JSON schema and validation commands
**Reference Materials:**
- **[Technology Detection Patterns](./technology-detection-patterns.md)** - Comprehensive guide to detecting frameworks, languages, and tooling
- **[Container Types Reference](./container-types-reference.md)** - Complete reference for all 10 container types with examples
- **[Communication Patterns](./communication-patterns.md)** - How containers communicate (HTTP, gRPC, queues, databases)
- **[Common Container Patterns](./common-container-patterns.md)** - Reusable architecture patterns (SPA+API+DB, microservices, serverless)
- **[Observation Categories](./observation-categories-c2.md)** - 8 observation categories with examples
- **[Troubleshooting Guide](./troubleshooting-guide-c2.md)** - Solutions to common problems
---
## Overview
You are an expert in the C4 Model's Level 2 (Container) methodology. This skill provides comprehensive knowledge for identifying and documenting containers (deployable/runnable units) at the second level of architectural abstraction.
**Your Mission:** Help identify WHAT deployable units exist within each system, WHAT technologies they use, and HOW they communicate - focusing on the building blocks that get deployed to production.
**C2 Container Level Definition:**
A container represents an application or data store that executes code or stores data. It's something that needs to be running for the overall system to work. Think: web servers, application servers, standalone applications, databases, file systems, message brokers.
**Relationship to Other Levels:**
- **C1 (System Context)** - Identified high-level systems → Now we decompose each system into containers
- **C2 (Container) - YOU ARE HERE** - Identify deployable/runnable units within each system
- **C3 (Component)** - Will identify code modules within each container (next level)
**Common Questions This Skill Answers:**
- "What deployable units exist in this system?"
- "What frameworks/technologies are used?"
- "How does the frontend communicate with the backend?"
- "Is this application containerized/dockerized?"
- "What database does this system use?"
**Error Symptoms That Indicate C2 Issues:**
- "missing technology.framework" - Container definition incomplete
- "version not specified" - Forgot to extract from manifest
- "container not found" - Reference to undefined container
- "too many containers" - Over-decomposed at C3 level
- "validation failed: primary_language" - Missing required field
---
## C2 Level Definition
### What is a Container (C2)?
A **container** at C2 level is a deployable/runnable unit:
- **Deployable Unit** - Can be deployed independently (even if part of a larger system)
- **Runs Code or Stores Data** - Executes application logic or persists information
- **Has Technology Stack** - Built with specific languages, frameworks, libraries
- **Has Runtime Environment** - Runs in browser, server, cloud, mobile device
- **Communicates via Protocols** - HTTP, gRPC, database connections, message queues
**Important:** Container in C4 Model ≠ Docker container
- C4 "container" = deployable/runnable unit (broader concept)
- Docker container is one possible deployment technology
### Abstraction Level
```
┌─────────────────────────────────────────────┐
│ C1: System Context │
│ "What systems exist?" │
├─────────────────────────────────────────────┤
│ C2: Container Level │ ← YOU ARE HERE
│ "What are the deployable units?" │
├─────────────────────────────────────────────┤
│ C3: Component Level │
│ "What are the code modules?" │
├─────────────────────────────────────────────┤
│ C4: Code Level │
│ "What are the classes/functions?" │
└─────────────────────────────────────────────┘
```
**At C2, we focus on:**
- ✅ Deployable/runnable units (what gets deployed)
- ✅ Technology stack (languages, frameworks, versions)
- ✅ Runtime environment (browser, server, cloud, mobile)
- ✅ Communication protocols (HTTP, gRPC, database, messaging)
- ✅ Deployment model (containerized, serverless, standalone)
**At C2, we do NOT focus on:**
- ❌ Code structure (that's C3 Component level)
- ❌ Classes and functions (that's C4 Code level)
- ❌ System boundaries (that was C1 System level)
- ❌ Line-by-line code analysis
---
## Container Identification Methodology
> **Full methodology details:** See [Methodology](./methodology.md) for complete step-by-step process.
### Is This a Container? Decision Tree
```
┌─────────────────────┐
│ Can it be deployed │
│ independently? │
└─────────┬───────────┘
┌─────────┴─────────┐
YES NO
│ │
┌───────────┴────────┐ ┌─────┴─────┐
│ Does it run code │ │ NOT a │
│ or store data? │ │ Container │
└─────────┬──────────┘ │ (maybe C3)│
│ └───────────┘
┌─────────┴─────────┐
YES NO
│ │
┌─────┴──────┐ ┌─────┴─────┐
│ Has own │ │ NOT a │
│ tech stack │ │ Container │
│ w/version? │ └───────────┘
└─────┬──────┘
┌─────┴─────────┐
YES NO
│ │
┌─┴──────────┐ ┌──┴───────────┐
│ CONTAINER! │ │ Add version │
│ Document │ │ from manifest│
│ in C2 │ │ then continue│
└────────────┘ └──────────────┘
```
### Quick Summary
**5 Steps:**
1. **Understand System Decomposition** - Review c1-systems.json
2. **Apply Container Identification Rules** - IS vs is NOT
3. **Analyze Repository Structure** - Find deployment indicators
4. **Detect Technology Stack** - Language, framework, versions
5. **Identify Runtime Environment** - browser/server/mobile/cloud
### Critical Rules
**A Container IS:**
- Deployable independently
- Executes code OR stores data
- Has distinct technology stack with versions
- Has runtime environment
- Communicates via defined protocols
**A Container is NOT:**
- Code modules (that's C3)
- Config files or dev tools
- Generic names without versions ("React SPA" → "React 18.2.0 SPA")
**MANDATORY:** Extract versions from manifest files (package.json, requirements.txt, pom.xml, etc.). This is NOT optional.
---
## Container Types Quick Reference
**10 Container Types:**
1. **spa** - Single-Page Application (browser)
2. **mobile-app** - iOS/Android application
3. **desktop-app** - Desktop application
4. **api** / **app-server** - Backend API server
5. **web-server** - Web server, reverse proxy
6. **database** - Relational or NoSQL database
7. **cache** - In-memory cache (Redis, Memcached)
8. **message-broker** - Message queue/event streaming
9. **worker** - Background job processor
10. **file-storage** - Object storage, file system
> **See [Container Types Reference](./container-types-reference.md) for detailed examples of all 10 types.**
---
## Communication Pattern Identification
### Identify Relationships Between Containers
Document how containers communicate using these patterns:
**Synchronous:**
- **http-rest** - RESTful HTTP API
- **http-graphql** - GraphQL API
- **grpc** - gRPC remote procedure calls
- **websocket** - WebSocket bidirectional communication
**Asynchronous:**
- **message-publish** - Publish to queue/topic
- **message-subscribe** - Subscribe to queue/topic
**Data Access:**
- **database-query** - Database read/write
- **cache-read-write** - Cache read and write
- **file-storage-access** - File upload/download
> **See [Communication Patterns](./communication-patterns.md) for complete patterns guide.**
### Detection Commands
```bash
# Find HTTP clients
grep -r "axios\|fetch\|requests" src/
# Find database connections
grep -r "DATABASE_URL\|DB_HOST" .env
# Find message brokers
grep -r "amqplib\|kafkajs\|redis.*publish" src/
```
---
## Observation Categories
When documenting containers, capture these 8 observation categories:
1. **technology** - Technology stack, frameworks, libraries, versions
2. **runtime** - Runtime environment, platform, deployment model
3. **communication** - How container communicates with others
4. **data-storage** - Data persistence, caching, storage patterns
5. **authentication** - Authentication and authorization mechanisms
6. **configuration** - Configuration management, environment variables
7. **monitoring** - Logging, monitoring, observability
8. **dependencies** - External dependencies, third-party services
**Severity Levels:**
- **info** - Informational observation (neutral)
- **warning** - Potential issue requiring attention
- **critical** - Critical issue requiring immediate action
> **See [Observation Categories](./observation-categories-c2.md) for detailed guidelines and examples.**
---
## Workflow Integration
### When This Skill is Used
This skill is activated during:
1. **Phase 3: C2 Container Identification** (`/melly-c2-containers`)
- Primary usage phase
- Container identification per system
- Technology stack detection
2. **Manual Container Analysis**
- User asks "what containers exist?"
- User asks "what is the technology stack?"
- User mentions keywords: "deployable units", "runtime environment", "containerization"
### Input Requirements
**Required Files:**
- `c1-systems.json` - Must exist with identified systems
- Repository access - Must be able to read system repositories
**Required Information:**
- System ID to analyze
- Repository paths
- System type and technologies (from C1)
### Output Format
> **See [Output Format](./output-format.md) for complete JSON schema and validation commands.**
Generate `c2-containers.json` with container definitions including id, name, type, system_id, technology (with versions), runtime, relations, and observations.
---
## Best Practices
### DO:
1. **Start with C1 understanding** - Review c1-systems.json first
2. **Focus on deployment boundary** - What can be deployed separately?
3. **Be specific with technology** - Include versions (React 18, not just React)
4. **Document runtime precisely** - Exact platform and containerization details
5. **Capture all communication** - Document how containers interact
6. **Use proper container types** - Choose from 10 defined types
7. **Provide evidence** - Link observations to files/commands
8. **Validate early** - Run validation scripts frequently
### DON'T:
1. **Don't confuse C2 with C3** - Components are code modules, not containers
2. **Don't be too granular** - 20+ containers likely means you're at C3 level
3. **Don't use generic names** - "Frontend" → "React SPA"
4. **Don't skip infrastructure** - Document databases, caches, brokers
5. **Don't guess** - Only document what you can verify
6. **Don't ignore validation** - Always validate before proceeding
### Common Rationalizations (Red Flags)
If you catch yourself thinking these, STOP - you're about to make a mistake:
| Rationalization | Reality |
|-----------------|---------|
| "This module deserves its own container" | Modules within an app are C3 Components, not C2 Containers. Can it be deployed separately? |
| "I'll add the version later" | Versions are MANDATORY. Read package.json/requirements.txt NOW. No version = invalid container. |
| "The exact version doesn't matter" | It does. "React 18" ≠ "React 18.2.0". Extract full semantic version from manifest. |
| "Generic versions (18.x) show appropriate uncertainty" | WRONG. "18.x" is not a version - it's an excuse. Extract exact version from manifest. |
| "Architecture matters more than versions" | Both matter equally. C2 requires technology stack WITH versions. No shortcuts. |
| "Version precision is not the decision point" | WRONG. Version precision IS required for valid C2 documentation. It's not optional. |
| "This is obviously a container" | Verify deployment boundary. If it can't be deployed independently, it's not a container. |
| "I'll group these APIs into separate containers" | One API server with multiple endpoints = one container. Don't over-decompose. |
| "Reading package.json is too detailed for C2" | WRONG. Technology detection from manifests IS C2. Line-by-line code analysis is C3. |
| "Infrastructure doesn't need technology fields" | ALL containers need ALL fields. Use "N/A" for primary_language on databases/caches. |
| "I can skip the runtime environment" | Runtime is essential. browser/server/mobile/cloud determines how container operates. |
**All of these mean: Go back, verify your work, follow the methodology.**
---
## Quick Reference Checklist
### Container Identification Checklist
- [ ] Review C1 systems from c1-systems.json
- [ ] Identify deployable units per system
- [ ] Verify deployment boundary (can it be deployed separately?)
- [ ] Detect primary language and framework
- [ ] Identify runtime environment and platform
- [ ] Document communication patterns
- [ ] Capture observations (8 categories)
- [ ] Validate with melly-validation scripts
### Required Fields Checklist
- [ ] `id` - Unique container identifier
- [ ] `name` - Descriptive container name with technology and version
- [ ] `type` - One of 10 container types
- [ ] `system_id` - Reference to C1 system
- [ ] `technology.primary_language` - JavaScript, Python, etc. (or "N/A" for infrastructure)
- [ ] `technology.framework` - React 18.2.0, Express 4.18.2, etc. (with full version)
- [ ] `runtime.environment` - browser, server, mobile, cloud
- [ ] `runtime.platform` - Exact platform details
- [ ] `runtime.containerized` - true/false
- [ ] `relations[]` - Communication with other containers
### Required Fields Matrix by Container Type
**APPLICATION CONTAINERS** (spa, mobile-app, desktop-app, api, app-server, worker):
| Field | Required | Format | Example |
|-------|----------|--------|---------|
| `technology.primary_language` | **REQUIRED** | Actual language | "TypeScript", "Python", "Java" |
| `technology.framework` | **REQUIRED** | Name + Full Version | "React 18.2.0", "FastAPI 0.104.1" |
| `technology.libraries` | **REQUIRED** | Array with versions | `[{"name": "Redux", "version": "4.2.1"}]` |
**INFRASTRUCTURE CONTAINERS** (database, cache, message-broker, web-server, file-storage):
| Field | Required | Format | Example |
|-------|----------|--------|---------|
| `technology.primary_language` | **REQUIRED** | Always "N/A" | "N/A" |
| `technology.framework` | **REQUIRED** | Tool + Full Version | "PostgreSQL 15.4", "Redis 7.2.3" |
| `technology.libraries` | OPTIONAL | Usually empty | `[]` |
**RULE:** ALL containers MUST have ALL technology fields filled. Use "N/A" for infrastructure containers' primary_language, but NEVER leave fields empty or undefined.
**Version Format:** Always use semantic versioning: `<Major>.<Minor>.<Patch>`
- ✅ "React 18.2.0"
- ✅ "PostgreSQL 15.4.0"
- ❌ "React 18" (missing minor.patch)
- ❌ "Express" (missing version entirely)
---
## Summary
**C2 Container Level focuses on:**
1. **WHAT deployable units exist** - Identify containers within each system
2. **WHAT technologies are used** - Detect languages, frameworks, versions
3. **WHERE containers run** - Identify runtime environments and platforms
4. **HOW containers communicate** - Document protocols and patterns
**Key Outputs:**
- `c2-containers.json` - Complete container inventory
- Observations per container (8 categories)
- Communication patterns documented
- Technology stack validated
**Next Steps:**
After completing C2 analysis:
1. Validate with `validate-c2-containers.py`
2. Review observations for warnings/critical issues
3. Proceed to C3 (Component) level analysis
4. Generate documentation with `/melly-doc-c4model`
**For detailed guidance, see the supporting documentation:**
- [Technology Detection Patterns](./technology-detection-patterns.md)
- [Container Types Reference](./container-types-reference.md)
- [Communication Patterns](./communication-patterns.md)
- [Common Container Patterns](./common-container-patterns.md)
- [Observation Categories](./observation-categories-c2.md)
- [Troubleshooting Guide](./troubleshooting-guide-c2.md)

View File

@@ -0,0 +1,524 @@
# Common Container Patterns
This document provides reusable architecture patterns for C4 Model Level 2 (Container) analysis with detailed examples.
## Pattern 1: Simple SPA + API + Database
**Scenario:** Basic web application with frontend, backend, and database
**Containers identified:**
1. **Frontend SPA Container**
- Type: `spa`
- Technology: React 18 + TypeScript
- Runtime: Browser
- Communicates with API via HTTP REST
2. **Backend API Container**
- Type: `api`
- Technology: Express.js + Node.js 18
- Runtime: Server (Node.js)
- Communicates with database via PostgreSQL protocol
3. **PostgreSQL Database Container**
- Type: `database`
- Technology: PostgreSQL 15
- Runtime: Server (Docker)
- Stores application data
**Architecture:**
```
┌──────────────────┐
│ Browser │
│ ┌────────────┐ │
│ │ React SPA │ │
│ └──────┬─────┘ │
└─────────┼────────┘
│ HTTP REST
┌─────────────────┐
│ Server │
│ ┌────────────┐ │
│ │ Express API│ │
│ └──────┬─────┘ │
└─────────┼───────┘
│ SQL
┌─────────────────┐
│ ┌────────────┐ │
│ │PostgreSQL │ │
│ │ Database │ │
│ └────────────┘ │
└─────────────────┘
```
**Detection Commands:**
```bash
# Detect pattern
find . -name "package.json" | grep -E "(frontend|client|web)"
find . -name "package.json" | grep -E "(backend|server|api)"
find . -name "docker-compose.yml" | xargs grep postgres
# Verify frontend
cat frontend/package.json | jq '.dependencies | keys | .[]' | grep -E "react|vue|angular"
# Verify backend
cat backend/package.json | jq '.dependencies | keys | .[]' | grep -E "express|fastify|nestjs"
# Verify database
docker-compose config | grep postgres
```
---
## Pattern 2: Microservices with API Gateway
**Scenario:** Multiple microservices behind API gateway
**Containers identified:**
1. **API Gateway Container**
- Type: `web-server`
- Technology: Nginx or Kong
- Runtime: Server
- Routes requests to services
2. **Auth Service Container**
- Type: `api`
- Technology: NestJS
- Runtime: Server (Node.js in Docker)
- Handles authentication
3. **User Service Container**
- Type: `api`
- Technology: Spring Boot
- Runtime: Server (JVM in Docker)
- Manages user data
4. **Order Service Container**
- Type: `api`
- Technology: FastAPI
- Runtime: Server (Python in Docker)
- Processes orders
5. **Message Broker Container**
- Type: `message-broker`
- Technology: RabbitMQ
- Runtime: Server (Docker)
- Event bus
6. **Per-Service Databases**
- Each service has its own database container
**Architecture:**
```
┌──────────────┐
│ API Gateway │
└──────┬───────┘
│ HTTP
┌───┴────┬────────┐
│ │ │
▼ ▼ ▼
┌─────┐ ┌──────┐ ┌───────┐
│Auth │ │User │ │Order │
│Svc │ │Svc │ │Svc │
└──┬──┘ └──┬───┘ └───┬───┘
│ │ │
└───────┴────┬────┘
┌─────────┐
│RabbitMQ │
└─────────┘
```
**Detection Commands:**
```bash
# Detect microservices pattern
find . -type d -name "*-service" -o -name "*-api"
ls services/ | wc -l # Count service directories
# Find API gateway
grep -r "nginx\|kong\|traefik" docker-compose.yml k8s/
# Find message broker
grep -r "rabbitmq\|kafka" docker-compose.yml k8s/
# Count services
find services/ -name "package.json" -o -name "pom.xml" -o -name "requirements.txt" | wc -l
```
---
## Pattern 3: Serverless Architecture
**Scenario:** Serverless functions with managed services
**Containers identified:**
1. **Frontend SPA Container**
- Type: `spa`
- Deployed to: CloudFront + S3
- Technology: React
- Runtime: Browser
2. **API Lambda Functions Container(s)**
- Type: `api`
- Multiple functions or single function
- Technology: Node.js Lambda handlers
- Runtime: AWS Lambda (serverless)
3. **DynamoDB Database**
- Type: `database`
- Technology: AWS DynamoDB
- Runtime: AWS managed
- Fully serverless
4. **S3 Storage Container**
- Type: `file-storage`
- Technology: AWS S3
- Runtime: AWS managed
- Stores uploaded files
**Architecture:**
```
┌─────────────┐
│ CloudFront │
│ + S3 │
│ (SPA) │
└──────┬──────┘
│ HTTP
┌─────────────┐
│ API Gateway │
└──────┬──────┘
┌─────────────┐ ┌──────────┐
│ Lambda │──────▶ DynamoDB │
│ Functions │ └──────────┘
└─────────────┘
┌─────────────┐
│ S3 Bucket │
└─────────────┘
```
**Detection Commands:**
```bash
# Detect serverless pattern
find . -name "serverless.yml" -o -name "serverless.yaml"
find . -name "vercel.json" -o -name "netlify.toml"
find . -name "template.yaml" | xargs grep "AWS::Serverless"
# Find Lambda functions
grep -r "AWS::Serverless::Function\|handler:" serverless.yml
# Find DynamoDB tables
grep -r "DynamoDB\|AWS::DynamoDB" template.yaml
# Find S3 usage
grep -r "S3_BUCKET\|aws-sdk.*s3" .
```
---
## Pattern 4: Full-Stack Framework (Next.js/Nuxt)
**Scenario:** Single full-stack application with SSR
**Containers identified:**
1. **Next.js Application Container**
- Type: `app-server` (full-stack)
- Technology: Next.js 13
- Runtime: Server (Node.js)
- Serves both frontend and API routes
- **Note:** This is ONE container, not separate frontend/backend
2. **Database Container**
- Type: `database`
- Technology: PostgreSQL
- Runtime: Server (Docker)
3. **Redis Cache Container**
- Type: `cache`
- Technology: Redis
- Runtime: Server (Docker)
- Caches SSR pages
**Architecture:**
```
┌────────────────────┐
│ Next.js App │
│ ┌──────────────┐ │
│ │ SSR + API │ │
│ │ Routes │ │
│ └──────┬───────┘ │
└─────────┼──────────┘
┌─┴──┐
│ │
┌───▼──┐ └──▼─────┐
│ DB │ │ Redis │
└──────┘ └───────┘
```
**Detection Commands:**
```bash
# Detect Next.js/Nuxt pattern
grep -r "\"next\":\|\"nuxt\":" package.json
# Check for API routes
find . -type d -name "api" -path "*/pages/api" -o -path "*/app/api"
# Check for SSR
grep -r "getServerSideProps\|getStaticProps" pages/ app/
# Verify single application
[ $(find . -name "package.json" -not -path "*/node_modules/*" | wc -l) -eq 1 ] && echo "Single app"
```
---
## Pattern 5: Mobile App + Backend
**Scenario:** Mobile application with supporting backend
**Containers identified:**
1. **Mobile Application Container**
- Type: `mobile-app`
- Technology: React Native
- Runtime: iOS/Android
- Communicates with API
2. **Backend API Container**
- Type: `api`
- Technology: Django REST Framework
- Runtime: Server (Python)
- Provides mobile API
3. **PostgreSQL Database Container**
- Type: `database`
- Technology: PostgreSQL
- Runtime: Server
4. **Redis Cache Container**
- Type: `cache`
- Technology: Redis
- Runtime: Server
- API response caching
5. **Push Notification Service Container**
- Type: `worker`
- Technology: Custom Python service
- Runtime: Server
- Sends push notifications via FCM/APNS
**Architecture:**
```
┌─────────────────┐
│ Mobile Device │
│ ┌─────────────┐ │
│ │React Native │ │
│ │ App │ │
│ └──────┬──────┘ │
└────────┼────────┘
│ HTTPS
┌────────────────┐ ┌────────┐
│ Django API │──────▶ Postgres│
└────────┬───────┘ └────────┘
┌────┴────┐
▼ ▼
┌──────┐ ┌────────┐
│Redis │ │Push │
│Cache │ │Service │
└──────┘ └────────┘
```
**Detection Commands:**
```bash
# Detect mobile app
find . -name "package.json" | xargs grep "react-native\|@ionic\|flutter"
find . -name "Podfile" -o -name "build.gradle"
# Detect backend API
grep -r "djangorestframework\|flask\|fastapi" requirements.txt
# Find push notification service
grep -r "fcm\|apns\|firebase-admin" . | grep -v node_modules
```
---
## Pattern 6: Event-Driven with Workers
**Scenario:** Async processing with message queue and workers
**Containers identified:**
1. **Web Application Container**
- Type: `spa`
- Technology: Vue 3
- Runtime: Browser
2. **Backend API Container**
- Type: `api`
- Technology: FastAPI
- Runtime: Server (Python)
- Publishes events to queue
3. **Message Queue Container**
- Type: `message-broker`
- Technology: Kafka
- Runtime: Server (Docker)
- Event streaming
4. **Email Worker Container**
- Type: `worker`
- Technology: Celery
- Runtime: Server (Python)
- Consumes email events
5. **Report Worker Container**
- Type: `worker`
- Technology: Celery
- Runtime: Server (Python)
- Generates reports
6. **Database Container**
- Type: `database`
- Technology: PostgreSQL
- Runtime: Server
**Architecture:**
```
┌──────┐ ┌─────┐
│ Vue │───▶│ API │
│ SPA │ └──┬──┘
└──────┘ │
│ publish
┌──────────┐
│ Kafka │
│ Queue │
└─────┬────┘
┌───┴───┐
subscribe subscribe
│ │
┌────▼──┐ ┌─▼──────┐
│Email │ │Report │
│Worker │ │Worker │
└───────┘ └────────┘
```
**Detection Commands:**
```bash
# Detect event-driven pattern
grep -r "celery\|sidekiq\|bull\|bee-queue" requirements.txt package.json Gemfile
# Find message brokers
grep -r "kafka\|rabbitmq\|redis.*pub.*sub" docker-compose.yml
# Find worker definitions
find . -name "*worker*.py" -o -name "*job*.py"
grep -r "celery.*worker\|worker.*start" .
```
---
## Pattern Selection Guide
### When to Use Each Pattern
| Pattern | Best For | Complexity | Scalability |
|---------|----------|------------|-------------|
| Pattern 1: SPA + API + DB | Simple web apps, MVPs | Low | Medium |
| Pattern 2: Microservices | Large systems, independent teams | High | Very High |
| Pattern 3: Serverless | Variable load, cost optimization | Medium | Auto-scale |
| Pattern 4: Full-Stack Framework | Rapid development, SSR needs | Low-Medium | Medium |
| Pattern 5: Mobile + Backend | Mobile-first apps | Medium | High |
| Pattern 6: Event-Driven | Async processing, decoupling | Medium-High | Very High |
### Mixing Patterns
Real-world systems often combine patterns:
**Example: E-commerce Platform**
- Pattern 1: Customer web portal (SPA + API + DB)
- Pattern 5: Mobile shopping app (Mobile + Backend)
- Pattern 6: Order processing (Event-driven workers)
- Pattern 3: Static assets (Serverless CDN)
---
## Detection Best Practices
1. **Start with docker-compose.yml or K8s manifests** - Shows all containers
2. **Check package manifests** - package.json, requirements.txt, pom.xml
3. **Look for framework indicators** - next.config.js, serverless.yml
4. **Examine folder structure** - services/, apps/, packages/
5. **Review deployment configs** - Dockerfile, K8s deployments
6. **Check environment variables** - .env files reveal connections
## Common Variations
### Pattern 1 Variations
- Add Redis cache → Pattern 1 + Cache
- Add Nginx proxy → Pattern 1 + Reverse Proxy
- Add worker → Pattern 1 + Background Jobs
### Pattern 2 Variations
- Per-service databases → Database-per-Service
- Shared database → Shared-Database (anti-pattern)
- Service mesh → Add Istio/Linkerd sidecar containers
### Pattern 3 Variations
- Vercel deployment → Vercel Edge Functions
- Netlify deployment → Netlify Functions
- Azure → Azure Functions + Cosmos DB
### Pattern 4 Variations
- Monorepo → Multiple Next.js apps
- Standalone API → Next.js + Separate API
- Edge runtime → Vercel Edge Runtime
---
## Anti-Patterns to Avoid
1. **Shared Database Across Services**
- Violates microservices principles
- Creates tight coupling
- Makes each service dependent
2. **Monolith in Disguise**
- Multiple "microservices" that all call each other synchronously
- Should be one container
3. **Over-Granular Containers**
- Breaking down below deployment boundary
- Example: Separating utility functions into "containers"
4. **Missing Infrastructure Containers**
- Forgetting databases, caches, message brokers
- Only documenting application containers
5. **Generic Container Types**
- "Node.js App" instead of "Express API Server"
- "Python Service" instead of "FastAPI API + Celery Worker"
---
## Next Steps
After identifying the pattern:
1. **Document each container** using container-types-reference.md
2. **Map communication** using communication-patterns.md
3. **Capture technology details** using technology-detection-patterns.md
4. **Add observations** per observation-categories-c2.md
5. **Validate** using melly-validation scripts

View File

@@ -0,0 +1,474 @@
# Communication Patterns
This document provides comprehensive patterns for inter-container communication in C4 Model Level 2 analysis.
## Synchronous Communication
### HTTP REST API
**Pattern:** Client makes HTTP request, waits for response
**Indicators:**
- axios, fetch, requests library
- REST endpoints (`/api/v1/users`)
- JSON request/response
**Relation Type:** `http-rest`
**Example:**
```json
{
"target": "ecommerce-api",
"type": "http-rest",
"direction": "outbound",
"description": "Fetches product catalog data via REST API",
"protocol": {
"method": "GET, POST",
"endpoint": "/api/v1/products",
"format": "JSON",
"authentication": "JWT Bearer Token"
}
}
```
**Detection Commands:**
```bash
# Find HTTP client libraries
grep -r "axios\|fetch\|requests\|http.client" src/
# Find API endpoint definitions
grep -r "@Get\|@Post\|@app.route\|router.get" src/
# Find REST API calls
grep -r "http://\|https://" .env config/
```
---
### HTTP GraphQL API
**Pattern:** Client sends GraphQL query, receives specific data
**Indicators:**
- Apollo Client, graphql-request
- Single `/graphql` endpoint
- Query language
**Relation Type:** `http-graphql`
**Example:**
```json
{
"target": "graphql-api",
"type": "http-graphql",
"direction": "outbound",
"description": "Queries user and order data via GraphQL",
"protocol": {
"endpoint": "/graphql",
"format": "GraphQL",
"authentication": "API Key header"
}
}
```
**Detection Commands:**
```bash
# Find GraphQL client libraries
grep -r "@apollo/client\|graphql-request" package.json
# Find GraphQL schemas
find . -name "*.graphql" -o -name "schema.gql"
# Find GraphQL operations
grep -r "query\|mutation\|subscription" src/ | grep graphql
```
---
### gRPC
**Pattern:** Remote procedure call with Protocol Buffers
**Indicators:**
- @grpc/grpc-js, grpc-go
- .proto files
- Binary protocol
**Relation Type:** `grpc`
**Example:**
```json
{
"target": "user-service",
"type": "grpc",
"direction": "outbound",
"description": "Calls user authentication via gRPC",
"protocol": {
"service": "UserService",
"methods": ["Authenticate", "GetProfile"]
}
}
```
**Detection Commands:**
```bash
# Find gRPC libraries
grep -r "@grpc\|grpc-go\|grpc-java" package.json pom.xml
# Find proto files
find . -name "*.proto"
# Find gRPC service definitions
grep -r "service.*{" *.proto
```
---
## Asynchronous Communication
### Message Queue (Publish/Subscribe)
**Pattern:** Publisher sends message to queue, consumer processes later
**Indicators:**
- RabbitMQ, Kafka, AWS SQS
- amqplib, kafkajs
- Queue/topic names
**Relation Types:** `message-publish`, `message-subscribe`
**Example (Publisher):**
```json
{
"target": "order-queue",
"type": "message-publish",
"direction": "outbound",
"description": "Publishes order created events",
"protocol": {
"queue": "orders.created",
"format": "JSON",
"broker": "RabbitMQ"
}
}
```
**Example (Consumer):**
```json
{
"target": "order-queue",
"type": "message-subscribe",
"direction": "inbound",
"description": "Consumes order created events for processing",
"protocol": {
"queue": "orders.created",
"format": "JSON",
"broker": "RabbitMQ"
}
}
```
**Detection Commands:**
```bash
# Find message broker libraries
grep -r "amqplib\|kafkajs\|aws-sdk.*sqs" package.json
# Find queue/topic names
grep -r "queue\|topic\|exchange" config/ src/
# Find publish/subscribe operations
grep -r "publish\|subscribe\|sendMessage\|consume" src/
```
---
### Event Streaming (Kafka)
**Pattern:** Continuous stream of events, multiple consumers
**Indicators:**
- Apache Kafka
- kafkajs, confluent-kafka
- Topics and partitions
**Relation Types:** `event-publish`, `event-subscribe`
**Example:**
```json
{
"target": "kafka-broker",
"type": "event-publish",
"direction": "outbound",
"description": "Streams order events to Kafka topic",
"protocol": {
"topic": "orders.events",
"partitions": 3,
"format": "Avro",
"broker": "Kafka"
}
}
```
---
## Database Communication
### Database Connection
**Pattern:** Application connects to database, executes queries
**Indicators:**
- Connection strings in .env
- ORM libraries (Prisma, SQLAlchemy, Hibernate)
- Database drivers (pg, psycopg2, mysql2)
**Relation Type:** `database-query`
**Example:**
```json
{
"target": "main-database",
"type": "database-query",
"direction": "outbound",
"description": "Reads and writes user and order data",
"protocol": {
"driver": "PostgreSQL wire protocol",
"connection_pool": "Max 20 connections",
"orm": "Prisma"
}
}
```
**Detection Commands:**
```bash
# Find database connection strings
grep -r "DATABASE_URL\|DB_HOST\|POSTGRES\|MYSQL" .env config/
# Find ORM libraries
grep -r "prisma\|typeorm\|sequelize\|sqlalchemy\|hibernate" package.json requirements.txt pom.xml
# Find database drivers
grep -r "pg\|psycopg2\|mysql2\|mongodb" package.json requirements.txt
```
---
## Cache Access
### Cache Read/Write
**Pattern:** Application reads/writes to in-memory cache
**Indicators:**
- redis, ioredis, node-cache
- Cache keys and TTL
- GET/SET operations
**Relation Type:** `cache-read-write`
**Example:**
```json
{
"target": "session-cache",
"type": "cache-read-write",
"direction": "bidirectional",
"description": "Stores and retrieves user session data",
"protocol": {
"driver": "Redis protocol",
"operations": ["GET", "SET", "DEL", "EXPIRE"],
"ttl": "1 hour"
}
}
```
**Detection Commands:**
```bash
# Find cache libraries
grep -r "redis\|ioredis\|memcached\|node-cache" package.json
# Find cache configuration
grep -r "REDIS_URL\|REDIS_HOST\|CACHE_" .env config/
# Find cache operations
grep -r "\.get\|\.set\|\.del\|cache\." src/
```
---
## File Storage Access
### Object Storage
**Pattern:** Application uploads/downloads files to/from object storage
**Indicators:**
- AWS S3, MinIO, Azure Blob
- aws-sdk, @aws-sdk/client-s3
- Bucket names
**Relation Type:** `file-storage-access`
**Example:**
```json
{
"target": "media-storage",
"type": "file-storage-access",
"direction": "bidirectional",
"description": "Uploads user-generated images and retrieves media files",
"protocol": {
"service": "AWS S3",
"bucket": "user-media-prod",
"operations": ["PutObject", "GetObject", "DeleteObject"]
}
}
```
**Detection Commands:**
```bash
# Find storage SDKs
grep -r "aws-sdk\|@aws-sdk\|minio\|azure-storage" package.json
# Find bucket/container names
grep -r "S3_BUCKET\|STORAGE_BUCKET\|AZURE_CONTAINER" .env config/
# Find storage operations
grep -r "putObject\|getObject\|upload\|download" src/
```
---
## External API Calls
### Third-Party API Integration
**Pattern:** Container calls external third-party service
**Indicators:**
- API keys in .env
- External domain URLs
- SDK libraries (Stripe, Twilio, SendGrid)
**Relation Type:** `external-api`
**Example:**
```json
{
"target": "stripe-api",
"type": "external-api",
"direction": "outbound",
"description": "Processes payments via Stripe API",
"protocol": {
"service": "Stripe API v1",
"authentication": "API Key",
"endpoints": ["POST /v1/charges", "GET /v1/customers"]
}
}
```
**Detection Commands:**
```bash
# Find external API libraries
grep -r "stripe\|twilio\|sendgrid\|mailgun" package.json
# Find API keys
grep -r "API_KEY\|SECRET_KEY" .env | grep -v "DATABASE\|JWT"
# Find external domains
grep -r "https://api\." src/ config/
```
---
## WebSocket Communication
### Real-Time Bidirectional
**Pattern:** Persistent connection for real-time data exchange
**Indicators:**
- socket.io, ws, websocket
- WebSocket URLs (ws://, wss://)
- Real-time events
**Relation Type:** `websocket`
**Example:**
```json
{
"target": "realtime-server",
"type": "websocket",
"direction": "bidirectional",
"description": "Real-time chat and notifications",
"protocol": {
"library": "Socket.IO 4.x",
"events": ["message", "notification", "status_update"],
"format": "JSON"
}
}
```
**Detection Commands:**
```bash
# Find WebSocket libraries
grep -r "socket.io\|ws\|websocket" package.json
# Find WebSocket connections
grep -r "ws://\|wss://\|io.connect\|new WebSocket" src/
# Find socket events
grep -r "socket.emit\|socket.on" src/
```
---
## Communication Pattern Summary
| Pattern | Sync/Async | Use Case | Typical Protocol |
|---------|-----------|----------|------------------|
| HTTP REST | Sync | CRUD operations | JSON over HTTP |
| GraphQL | Sync | Flexible data queries | GraphQL over HTTP |
| gRPC | Sync | Service-to-service | Protobuf over HTTP/2 |
| Message Queue | Async | Event-driven, decoupling | AMQP, SQS |
| Event Stream | Async | Real-time data pipelines | Kafka protocol |
| Database | Sync | Data persistence | SQL, MongoDB protocol |
| Cache | Sync | Fast data access | Redis protocol |
| Object Storage | Sync | File upload/download | S3 API |
| WebSocket | Bidirectional | Real-time updates | WS protocol |
---
## Direction Guidelines
**Outbound:** Container initiates communication to another container
- API calls from frontend to backend
- Database queries from API server
- Cache reads/writes from application
**Inbound:** Container receives communication from another container
- API server receives HTTP requests
- Worker consumes queue messages
- Database accepts queries
**Bidirectional:** Two-way communication
- WebSocket connections
- Cache read/write operations
- File storage upload/download
---
## Best Practices
1. **Be specific** - Document exact protocols, not just "HTTP"
2. **Include authentication** - JWT, API keys, OAuth
3. **Note data format** - JSON, Protobuf, Avro
4. **Document endpoints** - Actual URLs or queue names
5. **Capture direction** - Outbound, inbound, bidirectional
6. **Version protocols** - REST API v1, gRPC v2
7. **Performance characteristics** - Sync vs async, latency
## Common Pitfalls
1. **Missing intermediate containers** - Don't forget API gateways, proxies
2. **Assuming HTTP** - Could be gRPC, WebSocket, etc.
3. **Ignoring message brokers** - Async communication is indirect
4. **Generic descriptions** - "Talks to API" → "Calls REST API GET /api/users"
5. **Forgetting authentication** - Security mechanisms matter

View File

@@ -0,0 +1,459 @@
# Container Types Reference
This document provides comprehensive reference for all C4 Model Level 2 (Container) types with detailed examples and runtime characteristics.
## Type 1: Single-Page Application (SPA)
**Type:** `spa`
**Description:** Client-side web application that runs entirely in the browser
**Technology Indicators:**
- React, Vue, Angular, Svelte
- Webpack, Vite, or similar bundler
- Build output to static files (HTML/CSS/JS)
**Runtime:**
- Environment: `browser`
- Platform: `Chrome, Firefox, Safari, Edge`
- Containerized: `false` (static files)
**Example:**
```json
{
"id": "customer-portal-spa",
"name": "Customer Portal SPA",
"type": "spa",
"technology": {
"primary_language": "TypeScript",
"framework": "React 18.2.0",
"libraries": [
{"name": "React Router", "version": "6.14.0", "purpose": "Client-side routing"},
{"name": "Redux Toolkit", "version": "1.9.5", "purpose": "State management"},
{"name": "Axios", "version": "1.4.0", "purpose": "HTTP client"}
]
},
"runtime": {
"environment": "browser",
"platform": "Modern browsers (Chrome 90+, Firefox 88+, Safari 14+)",
"containerized": false
}
}
```
---
## Type 2: API Server / Application Server
**Type:** `app-server` or `api`
**Description:** Server-side application that exposes APIs or serves requests
**Technology Indicators:**
- Express, NestJS, Fastify (Node.js)
- Django, Flask, FastAPI (Python)
- Spring Boot, Quarkus (Java)
- Runs on server, listens on port
**Runtime:**
- Environment: `server`
- Platform: `Linux, Node.js 18, Python 3.11, JVM 17`
- Containerized: `true` (usually)
**Example:**
```json
{
"id": "ecommerce-api",
"name": "E-Commerce REST API",
"type": "api",
"technology": {
"primary_language": "TypeScript",
"framework": "NestJS 10.0.0",
"libraries": [
{"name": "Prisma", "version": "5.0.0", "purpose": "ORM"},
{"name": "Passport", "version": "0.6.0", "purpose": "Authentication"},
{"name": "class-validator", "version": "0.14.0", "purpose": "Validation"}
]
},
"runtime": {
"environment": "server",
"platform": "Linux x64, Node.js 18.16.0",
"containerized": true,
"container_technology": "Docker",
"deployment_model": "Kubernetes (3 replicas)"
}
}
```
---
## Type 3: Database
**Type:** `database`
**Description:** Data persistence layer (relational or NoSQL)
**Technology Indicators:**
- PostgreSQL, MySQL, MariaDB (relational)
- MongoDB, Cassandra, DynamoDB (NoSQL)
- Docker image or managed service
**Runtime:**
- Environment: `server` or `cloud`
- Platform: `Linux, Docker`
- Containerized: `true` (often)
**Example:**
```json
{
"id": "main-database",
"name": "Main PostgreSQL Database",
"type": "database",
"technology": {
"primary_language": "SQL",
"framework": "PostgreSQL 15.3",
"libraries": []
},
"runtime": {
"environment": "server",
"platform": "Linux x64, Docker",
"containerized": true,
"container_technology": "Docker",
"deployment_model": "Single instance with volume persistence"
}
}
```
---
## Type 4: Cache
**Type:** `cache`
**Description:** In-memory data store for caching and session management
**Technology Indicators:**
- Redis, Memcached
- In-memory key-value store
- TTL-based expiration
**Runtime:**
- Environment: `server`
- Platform: `Linux`
- Containerized: `true` (usually)
**Example:**
```json
{
"id": "session-cache",
"name": "Redis Session Cache",
"type": "cache",
"technology": {
"primary_language": "N/A",
"framework": "Redis 7.0",
"libraries": []
},
"runtime": {
"environment": "server",
"platform": "Linux x64",
"containerized": true,
"container_technology": "Docker"
}
}
```
---
## Type 5: Message Broker
**Type:** `message-broker`
**Description:** Message queue or event streaming platform
**Technology Indicators:**
- RabbitMQ, Apache Kafka, AWS SQS, Redis Pub/Sub
- Async message passing
- Producers and consumers
**Runtime:**
- Environment: `server` or `cloud`
- Platform: `Linux, Docker, or managed cloud service`
- Containerized: `true` (usually)
**Example:**
```json
{
"id": "event-broker",
"name": "RabbitMQ Message Broker",
"type": "message-broker",
"technology": {
"primary_language": "N/A",
"framework": "RabbitMQ 3.12",
"libraries": []
},
"runtime": {
"environment": "server",
"platform": "Linux x64",
"containerized": true,
"container_technology": "Kubernetes"
}
}
```
---
## Type 6: Web Server / Reverse Proxy
**Type:** `web-server`
**Description:** HTTP server, reverse proxy, or load balancer
**Technology Indicators:**
- Nginx, Apache, Traefik
- Serves static files
- Reverse proxy to backend services
**Runtime:**
- Environment: `server`
- Platform: `Linux`
- Containerized: `true` (usually)
**Example:**
```json
{
"id": "nginx-proxy",
"name": "Nginx Reverse Proxy",
"type": "web-server",
"technology": {
"primary_language": "N/A",
"framework": "Nginx 1.25",
"libraries": []
},
"runtime": {
"environment": "server",
"platform": "Linux x64",
"containerized": true,
"container_technology": "Kubernetes"
}
}
```
---
## Type 7: Worker / Background Service
**Type:** `worker`
**Description:** Background job processor, cron jobs, queue consumers
**Technology Indicators:**
- Celery workers, Sidekiq, Bull queue
- Processes background tasks
- Often queue-based
**Runtime:**
- Environment: `server`
- Platform: `Linux, Python, Ruby, Node.js`
- Containerized: `true` (usually)
**Example:**
```json
{
"id": "email-worker",
"name": "Email Processing Worker",
"type": "worker",
"technology": {
"primary_language": "Python",
"framework": "Celery 5.3.0",
"libraries": [
{"name": "sendgrid", "version": "6.10.0", "purpose": "Email sending"}
]
},
"runtime": {
"environment": "server",
"platform": "Linux x64, Python 3.11",
"containerized": true,
"container_technology": "Kubernetes"
}
}
```
---
## Type 8: Mobile Application
**Type:** `mobile-app`
**Description:** Native or hybrid mobile application
**Technology Indicators:**
- React Native, Flutter, Swift, Kotlin
- Runs on mobile devices
- Platform-specific build outputs
**Runtime:**
- Environment: `mobile`
- Platform: `iOS, Android`
- Containerized: `false`
**Example:**
```json
{
"id": "shopping-mobile-app",
"name": "Shopping Mobile App",
"type": "mobile-app",
"technology": {
"primary_language": "TypeScript",
"framework": "React Native 0.72.0",
"libraries": [
{"name": "React Navigation", "version": "6.1.0", "purpose": "Navigation"}
]
},
"runtime": {
"environment": "mobile",
"platform": "iOS 14+, Android 11+",
"containerized": false
}
}
```
---
## Type 9: Desktop Application
**Type:** `desktop-app`
**Description:** Desktop application for Windows, macOS, or Linux
**Technology Indicators:**
- Electron, Tauri, Qt
- Native desktop frameworks
- Installable applications
**Runtime:**
- Environment: `desktop`
- Platform: `Windows, macOS, Linux`
- Containerized: `false`
**Example:**
```json
{
"id": "admin-desktop-app",
"name": "Admin Desktop Application",
"type": "desktop-app",
"technology": {
"primary_language": "TypeScript",
"framework": "Electron 25.0.0",
"libraries": []
},
"runtime": {
"environment": "desktop",
"platform": "Windows 10+, macOS 11+, Linux",
"containerized": false
}
}
```
---
## Type 10: File Storage
**Type:** `file-storage`
**Description:** Object storage, file system, or CDN
**Technology Indicators:**
- AWS S3, MinIO, Azure Blob Storage
- File upload/download
- Static asset storage
**Runtime:**
- Environment: `cloud` or `server`
- Platform: `Cloud provider or self-hosted`
- Containerized: `varies`
**Example:**
```json
{
"id": "media-storage",
"name": "S3 Media Storage",
"type": "file-storage",
"technology": {
"primary_language": "N/A",
"framework": "AWS S3",
"libraries": []
},
"runtime": {
"environment": "cloud",
"platform": "AWS",
"containerized": false
}
}
```
---
## Type Selection Guide
### Decision Tree
1. **Runs in browser?** → SPA (Type 1)
2. **Exposes API/HTTP endpoints?** → API Server (Type 2)
3. **Stores persistent data?** → Database (Type 3)
4. **In-memory caching?** → Cache (Type 4)
5. **Async messaging?** → Message Broker (Type 5)
6. **Proxies/serves static files?** → Web Server (Type 6)
7. **Background jobs?** → Worker (Type 7)
8. **Mobile device?** → Mobile App (Type 8)
9. **Desktop application?** → Desktop App (Type 9)
10. **File/object storage?** → File Storage (Type 10)
### Common Combinations
**Typical Web App:**
- SPA (frontend)
- API Server (backend)
- Database (persistence)
- Cache (session/performance)
**Microservices:**
- Multiple API Servers (services)
- Message Broker (async communication)
- Multiple Databases (per-service)
- Web Server (gateway/proxy)
**Full-Stack Application:**
- API Server with SSR (Next.js/Nuxt)
- Database
- Cache
- File Storage (uploads)
**Enterprise System:**
- SPA (admin portal)
- Mobile App (customer app)
- Multiple API Servers (microservices)
- Worker (background jobs)
- Message Broker (events)
- Multiple Databases
- Cache
- File Storage
---
## Best Practices
1. **One container = one deployable unit** - Don't split unnecessarily
2. **Runtime matters** - Document where container actually runs
3. **Technology precision** - Include versions (React 18, not just React)
4. **Containerization awareness** - Note Docker/K8s deployment
5. **Communication patterns** - Document how containers interact
6. **Scaling characteristics** - Note replicas, stateful vs stateless
7. **Dependencies** - Capture required infrastructure containers
## Common Pitfalls
1. **Confusing container with system** - Container is ONE deployable unit within a system
2. **Too granular** - Don't break down below deployment boundary
3. **Missing infrastructure** - Don't forget databases, caches, brokers
4. **Generic types** - Be specific (FastAPI API, not "Python app")
5. **Ignoring deployment** - Runtime and deployment model matter

View File

@@ -0,0 +1,158 @@
# Container Identification Methodology
Detailed step-by-step process for identifying C2 containers within systems.
## Step 1: Understand System Decomposition
Start by reviewing the systems identified at C1 level in `c1-systems.json`:
**Questions to ask:**
1. What systems were identified at C1?
2. What repositories belong to each system?
3. What is the system type (web-application, api-service, etc.)?
4. What technologies were mentioned in system observations?
**System-to-Container Mapping Examples:**
**Simple Web Application System →**
- Frontend SPA container (React/Vue/Angular in browser)
- Backend API container (Express/Django/Spring on server)
- Database container (PostgreSQL/MongoDB)
- Cache container (Redis) - optional
**Microservice System →**
- API Server container (main service logic)
- Database container (service-specific database)
- Worker container (background processing) - optional
- Message broker container (RabbitMQ/Kafka) - if async
**Mobile App System →**
- Mobile Application container (React Native/Flutter on mobile)
- Backend API container (supporting backend)
- Database container
- Push notification service container - optional
> **See [Common Container Patterns](./common-container-patterns.md) for 6 reusable architecture patterns.**
## Step 2: Apply Container Identification Rules
### A Container IS:
1. **Deployable independently** - Has own build/deployment process and artifact
2. **Executes code OR stores data** - Runs application logic or persists data
3. **Has distinct technology stack** - Built with specific language/framework
4. **Has runtime environment** - Runs in specific environment (browser, server, mobile, cloud)
5. **Communicates via defined protocols** - HTTP, database connections, message queues
6. **Infrastructure component** - Databases, caches, message brokers required for system operation
### A Container is NOT:
1. **Code modules within an application** (these are C3 components)
- "Authentication Module" in React app → C3 Component
- "Express API Application" → C2 Container
2. **Configuration files or static assets** - package.json, CSS files, images
3. **Development tools** - Webpack, Babel, ESLint, Jest test runner
4. **Generic names without technology and version**
- "Frontend Container" → "React 18.2 SPA Container"
- "Backend Container" → "Express 4.18 API Server Container"
- "React SPA" (missing version) → "React 18.2 SPA"
5. **Names without versions** (versions MUST come from manifest files)
- "React SPA" → "React 18.2.0 SPA"
- "Express API Server" → "Express 4.18.2 API Server"
**RULE (Mandatory):** You MUST extract versions from manifest files:
- package.json (JavaScript/TypeScript)
- requirements.txt / pyproject.toml (Python)
- pom.xml / build.gradle (Java)
- Cargo.toml (Rust)
- go.mod (Go)
This is NOT optional. Reading manifests is NOT "line-by-line code analysis" - it's standard C2 technology detection.
**Failure to include versions from manifests = VIOLATION of C2 methodology = Critical validation error.**
6. **Over-granular decomposition**
- "Login API" + "Register API" → "User Management API"
> **See [Troubleshooting Guide](./troubleshooting-guide-c2.md#problem-too-many-containers-identified) for detailed guidance.**
## Step 3: Analyze Repository Structure
For each system, examine its repositories to identify containers:
**Look for deployment indicators:**
```bash
# Check for containerization
find . -name "Dockerfile" -o -name "docker-compose.yml"
# Check for build outputs
ls -la dist/ build/ target/ out/
# Check for deployment configs
ls -la .kubernetes/ .aws/ .azure/ vercel.json netlify.toml
```
**Common patterns:**
- **Frontend SPA:** `public/index.html`, `src/App.tsx`, `package.json` with React/Vue/Angular
- **Backend API:** `src/server.js`, `app.py`, `Main.java` with Express/Django/Spring
- **Database:** `docker-compose.yml` defining database service, migration files
- **Worker:** Queue consumer code, `worker.js`, `worker.py`
## Step 4: Detect Technology Stack
For each container, identify:
### Primary Language
JavaScript, TypeScript, Python, Java, Go, Ruby, PHP, C#, Rust
**Detection methods:**
```bash
# Check package manifests
cat package.json | jq '.dependencies'
cat requirements.txt
cat pom.xml
# Count file extensions
find src -name "*.ts" | wc -l
find src -name "*.py" | wc -l
# Check Dockerfile
cat Dockerfile | grep "FROM"
```
### Framework/Platform
React, Vue, Angular (frontend) | Express, NestJS, FastAPI, Django, Spring Boot (backend)
**Detection methods:**
- Check dependencies in package manifests
- Look for framework-specific files (`angular.json`, `vue.config.js`)
- Analyze import statements
> **See [Technology Detection Patterns](./technology-detection-patterns.md) for complete detection guide.**
## Step 5: Identify Runtime Environment
For each container, determine:
### Environment
- **browser** - Runs in web browser (SPAs)
- **server** - Runs on server (APIs, web servers)
- **mobile** - Runs on mobile device (iOS/Android)
- **cloud** - Runs in cloud (Lambda, Cloud Functions)
- **edge** - Runs at edge (Cloudflare Workers)
### Platform
- Browser: Chrome, Firefox, Safari, Edge
- Server: Linux, Node.js 18, Python 3.11, JVM 17
- Mobile: iOS 14+, Android 11+
### Containerization
- **Containerized:** true/false
- **Container Technology:** Docker, Kubernetes, ECS
- **Container Image:** `node:18-alpine`, `python:3.11-slim`

View File

@@ -0,0 +1,502 @@
# Observation Categories for C2
This document provides comprehensive guidance on documenting observations for C4 Model Level 2 (Container) analysis.
## Observation Categories
When documenting containers, capture these observation categories:
### 1. technology
**Focus:** Technology stack, frameworks, libraries, and versions
**What to Document:**
- Primary programming language and version
- Framework name and version
- Major libraries and their purposes
- Build tools and bundlers
- Package managers
**Examples:**
- ✅ "Uses React 18.2.0 with TypeScript for type safety"
- ✅ "Built with NestJS 10.0 framework following modular architecture"
- ✅ "Python 3.11 with FastAPI for high-performance async API"
- ⚠️ "Outdated Express 3.x version (current is 4.x)" (warning)
- ⚠️ "Mixed JavaScript and TypeScript files (inconsistent)" (warning)
**Detection Commands:**
```bash
# JavaScript/TypeScript
cat package.json | jq '.dependencies'
cat package.json | jq '.devDependencies'
# Python
cat requirements.txt
pip list
# Java
cat pom.xml | grep "<dependency>"
gradle dependencies
# Check versions
node --version
python --version
java --version
```
---
### 2. runtime
**Focus:** Runtime environment, platform, and deployment model
**What to Document:**
- Runtime environment (browser, Node.js, Python, JVM, etc.)
- Platform details (OS, architecture, version)
- Containerization (Docker, Kubernetes)
- Deployment model (single instance, replicas, serverless)
- Resource constraints (CPU, memory)
**Examples:**
- ✅ "Runs in browser (Chrome 90+, Firefox 88+, Safari 14+)"
- ✅ "Node.js 18.16.0 runtime on Linux x64"
- ✅ "Containerized with Docker, deployed to Kubernetes with 3 replicas"
- ✅ "Serverless deployment on AWS Lambda with cold start ~500ms"
- ⚠️ "No resource limits configured in Kubernetes" (warning)
**Detection Commands:**
```bash
# Check Dockerfile
cat Dockerfile | grep "FROM"
# Check K8s deployment
kubectl get deployment <name> -o yaml | grep replicas
# Check docker-compose
cat docker-compose.yml | grep "image:\|build:"
# Check runtime config
cat .node-version
cat runtime.txt
```
---
### 3. communication
**Focus:** How the container communicates with other containers
**What to Document:**
- Communication protocols (HTTP, gRPC, WebSocket, etc.)
- API specifications (REST, GraphQL)
- Message brokers (RabbitMQ, Kafka)
- Synchronous vs asynchronous
- Authentication mechanisms
**Examples:**
- ✅ "Communicates with API via HTTP REST over HTTPS"
- ✅ "Publishes events to RabbitMQ message broker"
- ✅ "Uses gRPC for inter-service communication"
- ✅ "WebSocket connection for real-time updates"
- ⚠️ "HTTP communication not encrypted (uses http://)" (warning)
**Detection Commands:**
```bash
# Find HTTP clients
grep -r "axios\|fetch\|requests" src/
# Find gRPC
grep -r "grpc\|proto" src/ | head -5
# Find WebSocket
grep -r "socket.io\|ws\|websocket" src/
# Find message broker
grep -r "amqp\|kafka\|redis.*publish" src/
```
---
### 4. data-storage
**Focus:** Data persistence, caching, and storage patterns
**What to Document:**
- Database type and version (PostgreSQL, MongoDB, etc.)
- Connection pooling configuration
- Caching strategy (Redis, Memcached)
- File storage (S3, local filesystem)
- Stateful vs stateless
**Examples:**
- ✅ "PostgreSQL 15 database with connection pooling (max 20)"
- ✅ "Redis cache for session storage with 1-hour TTL"
- ✅ "Stores uploaded files in AWS S3 bucket"
- ✅ "No database connection (stateless API)"
- ⚠️ "Database connection pool not configured (potential bottleneck)" (warning)
**Detection Commands:**
```bash
# Find database connections
grep -r "DATABASE_URL\|DB_HOST" .env
# Find ORMs
grep -r "prisma\|typeorm\|sequelize\|sqlalchemy" .
# Find cache usage
grep -r "REDIS_URL\|redis.get\|redis.set" .
# Find file storage
grep -r "S3_BUCKET\|aws-sdk.*s3\|multer" .
```
---
### 5. authentication
**Focus:** Authentication and authorization mechanisms
**What to Document:**
- Authentication method (JWT, OAuth, API keys)
- Token expiry and refresh
- Authorization rules (RBAC, ABAC)
- Session management
- Security headers
**Examples:**
- ✅ "JWT Bearer token authentication with 15-minute expiry"
- ✅ "OAuth 2.0 integration with Auth0"
- ✅ "API key authentication via x-api-key header"
- ⚠️ "No authentication implemented" (warning)
- 🔴 "JWT tokens never expire (security risk)" (critical)
**Detection Commands:**
```bash
# Find authentication libraries
grep -r "passport\|jsonwebtoken\|auth0" package.json
# Find JWT usage
grep -r "jwt\|bearer\|token" src/ | grep -i auth
# Find OAuth
grep -r "oauth\|openid" .
# Check for API keys
grep -r "API_KEY\|X-API-KEY" .env
```
---
### 6. configuration
**Focus:** Configuration management and environment variables
**What to Document:**
- Configuration sources (.env, ConfigMap, Secrets)
- Environment-specific configs (dev, staging, prod)
- Secret management
- Configuration validation
- Default values
**Examples:**
- ✅ "Configuration via environment variables"
- ✅ "Uses .env files for local development"
- ✅ "ConfigMap and Secrets in Kubernetes"
- ⚠️ "Hardcoded configuration values in source code" (warning)
- 🔴 "Secrets committed to git repository" (critical)
**Detection Commands:**
```bash
# Find .env files
find . -name ".env*" -not -path "*/node_modules/*"
# Check for ConfigMap usage
grep -r "ConfigMap" k8s/
# Find hardcoded values
grep -r "http://\|https://\|mongodb://\|postgres://" src/ | grep -v ".env"
# Check for secret management
grep -r "vault\|doppler\|aws-secrets-manager" .
```
---
### 7. monitoring
**Focus:** Logging, monitoring, and observability
**What to Document:**
- Logging framework and destination
- Metrics collection (Prometheus, DataDog)
- Tracing (OpenTelemetry, Jaeger)
- Health checks and readiness probes
- Error tracking (Sentry, Rollbar)
**Examples:**
- ✅ "Application logs to stdout, collected by Fluentd"
- ✅ "Prometheus metrics exposed on /metrics endpoint"
- ✅ "OpenTelemetry tracing enabled"
- ⚠️ "No logging or monitoring configured" (warning)
- ⚠️ "Logs contain sensitive data (PII, credentials)" (warning)
**Detection Commands:**
```bash
# Find logging libraries
grep -r "winston\|pino\|bunyan\|logrus" package.json
# Find metrics
grep -r "prometheus\|statsd\|datadog" .
# Find tracing
grep -r "opentelemetry\|jaeger\|zipkin" .
# Check for health endpoints
grep -r "/health\|/ready\|/alive" src/
```
---
### 8. dependencies
**Focus:** External dependencies and third-party services
**What to Document:**
- Third-party API integrations (Stripe, SendGrid)
- External service dependencies
- SDK usage
- Vendor lock-in risks
- Availability dependencies
**Examples:**
- ✅ "Depends on Stripe API for payment processing"
- ✅ "Uses SendGrid for transactional email"
- ✅ "Integrates with Google Analytics for tracking"
- ⚠️ "Heavy dependency on external APIs (availability risk)" (warning)
- ⚠️ "No fallback for third-party service failures" (warning)
**Detection Commands:**
```bash
# Find third-party SDKs
grep -r "stripe\|twilio\|sendgrid\|mailgun" package.json
# Find external API calls
grep -r "https://api\." src/ .env
# Check for API keys
grep -r "STRIPE_KEY\|TWILIO_\|SENDGRID_" .env
# Find vendor-specific code
grep -r "aws-sdk\|google-cloud\|azure" .
```
---
## Observation Structure
### JSON Schema
```json
{
"id": "obs-tech-react-18",
"category": "technology",
"severity": "info",
"description": "React 18.2.0 with TypeScript 5.0 for type-safe component development",
"evidence": {
"type": "file",
"location": "package.json",
"snippet": "\"react\": \"^18.2.0\", \"typescript\": \"^5.0.0\""
},
"tags": ["react", "typescript", "frontend", "spa"],
"discovered_at": "2025-01-15T10:30:00Z",
"discovered_by": "c2-abstractor"
}
```
### Field Descriptions
- **id**: Unique identifier (format: `obs-<category>-<short-desc>`)
- **category**: One of the 8 categories above
- **severity**: `info`, `warning`, or `critical`
- **description**: Human-readable observation
- **evidence**: Proof of the observation
- **type**: `file`, `command`, `inference`
- **location**: File path, command, or reasoning
- **snippet**: Code snippet, command output, or explanation
- **tags**: Searchable keywords
- **discovered_at**: ISO 8601 timestamp
- **discovered_by**: Tool or agent name
---
## Observation Severity Levels
### info (Informational)
**Purpose:** Neutral findings documenting the system as it is
**Examples:**
- "Uses Prisma ORM for database access"
- "React 18.2.0 with functional components and hooks"
- "Deployed with 3 replicas for high availability"
**When to Use:**
- Technology choices (neutral)
- Architecture patterns (no issues)
- Configuration details (standard)
### warning (Needs Attention)
**Purpose:** Potential issues that should be addressed but aren't blocking
**Examples:**
- ⚠️ "Redis cache has no password configured"
- ⚠️ "Outdated Express 3.x version (current is 4.x)"
- ⚠️ "No resource limits configured in Kubernetes"
- ⚠️ "Logs contain timestamps but no correlation IDs"
**When to Use:**
- Outdated dependencies
- Missing best practices
- Potential performance issues
- Missing recommended features
### critical (Immediate Action)
**Purpose:** Critical issues requiring immediate action (security, stability)
**Examples:**
- 🔴 "Database credentials hardcoded in source code"
- 🔴 "JWT tokens never expire (security risk)"
- 🔴 "API exposed without authentication"
- 🔴 "Secrets committed to git repository"
**When to Use:**
- Security vulnerabilities
- Data exposure risks
- Critical misconfigurations
- Blocking production issues
---
## Best Practices
### DO:
1. **Be specific** - Include versions, exact technologies
2. **Provide evidence** - Link to files, commands, or reasoning
3. **Use consistent format** - Follow the JSON schema
4. **Tag appropriately** - Use searchable, relevant tags
5. **Document warnings** - Call out anti-patterns and risks
6. **Cite sources** - Reference configuration files, code
### DON'T:
1. **Don't be vague** - "Uses React" → "Uses React 18.2.0"
2. **Don't skip evidence** - Always provide proof
3. **Don't over-categorize** - One observation = one category
4. **Don't ignore security** - Flag security issues as critical
5. **Don't duplicate** - Consolidate similar observations
6. **Don't guess** - Only document what you can verify
---
## Common Observation Patterns
### Pattern: Outdated Dependencies
```json
{
"id": "obs-tech-outdated-express",
"category": "technology",
"severity": "warning",
"description": "Express 3.x is significantly outdated (current stable: 4.x). Consider upgrading for security patches and new features.",
"evidence": {
"type": "file",
"location": "package.json",
"snippet": "\"express\": \"^3.21.2\""
},
"tags": ["express", "outdated", "dependency", "security"]
}
```
### Pattern: Missing Authentication
```json
{
"id": "obs-auth-missing",
"category": "authentication",
"severity": "critical",
"description": "API endpoints exposed without authentication. All routes are publicly accessible.",
"evidence": {
"type": "command",
"location": "grep -r 'app.get\\|app.post' src/",
"snippet": "No authentication middleware found in route definitions"
},
"tags": ["authentication", "security", "api", "critical"]
}
```
### Pattern: Performance Configuration
```json
{
"id": "obs-runtime-no-limits",
"category": "runtime",
"severity": "warning",
"description": "Kubernetes deployment has no CPU or memory limits configured, which may lead to resource contention.",
"evidence": {
"type": "file",
"location": "k8s/deployment.yaml",
"snippet": "No 'resources.limits' section found in container spec"
},
"tags": ["kubernetes", "resources", "performance", "deployment"]
}
```
### Pattern: Good Practice
```json
{
"id": "obs-monitor-prometheus",
"category": "monitoring",
"severity": "info",
"description": "Prometheus metrics endpoint exposed at /metrics with custom application metrics",
"evidence": {
"type": "file",
"location": "src/metrics.ts",
"snippet": "app.get('/metrics', (req, res) => { res.set('Content-Type', register.contentType); res.end(register.metrics()); });"
},
"tags": ["prometheus", "monitoring", "metrics", "observability"]
}
```
---
## Relationship to C1 Observations
C2 observations are **more detailed** than C1:
| Aspect | C1 (System) | C2 (Container) |
|--------|-------------|----------------|
| **Scope** | Entire system | Individual containers |
| **Technology** | High-level tech stack | Specific frameworks & versions |
| **Runtime** | General deployment | Exact runtime config |
| **Communication** | External dependencies | Inter-container protocols |
**Example:**
- **C1**: "E-Commerce System uses Node.js and React"
- **C2 (Frontend)**: "React 18.2.0 SPA with TypeScript 5.0, deployed to Vercel"
- **C2 (Backend)**: "NestJS 10.0 API on Node.js 18.16.0, containerized in Kubernetes with 3 replicas"
---
## Next Steps
After capturing observations:
1. **Validate** using melly-validation scripts
2. **Store** in basic-memory MCP knowledge base
3. **Reference** in container documentation
4. **Track** warnings and critical issues
5. **Update** as system evolves

View File

@@ -0,0 +1,69 @@
# C2 Output Format
JSON structure for `c2-containers.json` output file.
## Complete Example
```json
{
"metadata": {
"version": "1.0.0",
"timestamp": "2025-11-17T20:20:00.000Z",
"generated_by": "c2-abstractor",
"parent": {
"file": "c1-systems.json",
"timestamp": "2025-11-17T10:00:00.000Z"
}
},
"containers": [
{
"id": "ecommerce-spa",
"name": "E-Commerce Customer Portal",
"type": "spa",
"system_id": "ecommerce-system",
"technology": {
"primary_language": "TypeScript",
"framework": "React 18.2.0",
"libraries": [
{"name": "React Router", "version": "6.14.0", "purpose": "Client-side routing"},
{"name": "Redux Toolkit", "version": "1.9.5", "purpose": "State management"}
]
},
"runtime": {
"environment": "browser",
"platform": "Modern browsers (Chrome 90+, Firefox 88+, Safari 14+)",
"containerized": false
},
"relations": [
{
"target": "ecommerce-api",
"type": "http-rest",
"direction": "outbound",
"description": "Fetches product data and submits orders"
}
],
"observations": [],
"metadata": {
"repository": "frontend/",
"discovered_at": "2025-11-17T20:15:00.000Z"
}
}
]
}
```
## Validation
After generating `c2-containers.json`:
```bash
# Validate JSON structure
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c2-containers.py c2-containers.json
# Verify timestamps
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/check-timestamp.sh c2-containers.json c1-systems.json
```
## Required Fields
See main [SKILL.md](./SKILL.md#required-fields-checklist) for complete required fields matrix.

View File

@@ -0,0 +1,445 @@
# Technology Detection Patterns
This document provides comprehensive patterns for detecting technologies and frameworks in C4 Model Level 2 (Container) analysis.
## Pattern 1: npm/package.json Detection
### Frontend Frameworks
**React:**
```json
{
"dependencies": {
"react": "^18.2.0", // → React 18 SPA
"react-dom": "^18.2.0",
"react-router-dom": "^6.14.0" // → Client-side routing
}
}
```
**Container:** React SPA, runs in browser
**Vue:**
```json
{
"dependencies": {
"vue": "^3.3.0", // → Vue 3 SPA
"@vue/runtime-core": "^3.3.0"
}
}
```
**Container:** Vue SPA, runs in browser
**Angular:**
```json
{
"dependencies": {
"@angular/core": "^16.0.0", // → Angular 16 SPA
"@angular/platform-browser": "^16.0.0"
}
}
```
**Container:** Angular SPA, runs in browser
### Backend Frameworks
**Express.js:**
```json
{
"dependencies": {
"express": "^4.18.2", // → Express API Server
"cors": "^2.8.5",
"helmet": "^7.0.0"
}
}
```
**Container:** Express.js API Server, runs on Node.js
**NestJS:**
```json
{
"dependencies": {
"@nestjs/core": "^10.0.0", // → NestJS API Server
"@nestjs/platform-express": "^10.0.0"
}
}
```
**Container:** NestJS API Server, runs on Node.js
**Fastify:**
```json
{
"dependencies": {
"fastify": "^4.20.0", // → Fastify API Server
"@fastify/cors": "^8.3.0"
}
}
```
**Container:** Fastify API Server, runs on Node.js
### Full-Stack Frameworks
**Next.js:**
```json
{
"dependencies": {
"next": "^13.4.0", // → Next.js Full-Stack
"react": "^18.2.0"
}
}
```
**Container:** Next.js Application (SSR + API routes), runs on Node.js server
**Nuxt.js:**
```json
{
"dependencies": {
"nuxt": "^3.6.0", // → Nuxt.js Full-Stack
"vue": "^3.3.0"
}
}
```
**Container:** Nuxt.js Application, runs on Node.js server
### Mobile Frameworks
**React Native:**
```json
{
"dependencies": {
"react-native": "^0.72.0" // → React Native Mobile App
}
}
```
**Container:** React Native Mobile Application, runs on iOS/Android
**Ionic:**
```json
{
"dependencies": {
"@ionic/react": "^7.0.0", // → Ionic Mobile App
"capacitor": "^5.0.0"
}
}
```
**Container:** Ionic Mobile Application, runs on iOS/Android
### Desktop Frameworks
**Electron:**
```json
{
"dependencies": {
"electron": "^25.0.0" // → Electron Desktop App
}
}
```
**Container:** Electron Desktop Application, runs on Windows/macOS/Linux
---
## Pattern 2: Python Detection
### Web Frameworks
**Django:**
```txt
# requirements.txt
Django==4.2.0 # → Django Web Application
djangorestframework==3.14.0 # → Also has REST API
psycopg2-binary==2.9.6 # → Uses PostgreSQL
```
**Container:** Django Web Application + API, runs on Python 3.x
**Flask:**
```txt
# requirements.txt
Flask==2.3.0 # → Flask API Server
Flask-CORS==4.0.0
gunicorn==21.0.0 # → WSGI server for production
```
**Container:** Flask API Server, runs on Python 3.x with Gunicorn
**FastAPI:**
```txt
# requirements.txt
fastapi==0.100.0 # → FastAPI API Server
uvicorn[standard]==0.23.0 # → ASGI server
pydantic==2.0.0 # → Data validation
```
**Container:** FastAPI API Server, runs on Python 3.x with Uvicorn
### Background Workers
**Celery:**
```txt
# requirements.txt
celery==5.3.0 # → Celery Worker
redis==4.6.0 # → Uses Redis as broker
```
**Container:** Celery Worker, runs on Python 3.x
---
## Pattern 3: Java Detection
### Maven (pom.xml)
**Spring Boot:**
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
```
**Container:** Spring Boot API Server, runs on JVM 17+
### Gradle (build.gradle)
**Quarkus:**
```groovy
dependencies {
implementation 'io.quarkus:quarkus-resteasy-reactive'
implementation 'io.quarkus:quarkus-jdbc-postgresql'
}
```
**Container:** Quarkus API Server, runs on JVM or native
---
## Pattern 4: Docker Detection
### Dockerfile Examples
**Node.js API Server:**
```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
```
**Container:** Node.js API Server, containerized with Docker, runs on Node.js 18
**Python FastAPI Server:**
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0"]
```
**Container:** Python FastAPI Server, containerized with Docker, runs on Python 3.11
### docker-compose.yml
**Multi-Container Application:**
```yaml
services:
api:
build: ./api
ports:
- "3000:3000"
depends_on:
- db
db:
image: postgres:15-alpine
environment:
POSTGRES_DB: myapp
volumes:
- pgdata:/var/lib/postgresql/data
redis:
image: redis:7-alpine
```
**Containers identified:**
1. API Server (custom built from ./api)
2. PostgreSQL Database (postgres:15-alpine)
3. Redis Cache (redis:7-alpine)
---
## Pattern 5: Kubernetes Detection
### Deployment YAML
**Frontend SPA with Nginx:**
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend-spa
spec:
replicas: 3
template:
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
```
**Container:** Nginx Web Server, containerized with K8s, serves static SPA
**API Server:**
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-server
spec:
template:
spec:
containers:
- name: api
image: myapp/api:1.0
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
```
**Container:** Custom API Server, containerized with K8s
---
## Pattern 6: Serverless Detection
### Serverless Framework (serverless.yml)
**AWS Lambda:**
```yaml
service: my-api
provider:
name: aws
runtime: nodejs18.x
functions:
api:
handler: handler.main
events:
- http:
path: /api/{proxy+}
method: ANY
```
**Container:** AWS Lambda Function, runs on Node.js 18, serverless
### Vercel (vercel.json)
**Next.js on Vercel:**
```json
{
"builds": [
{
"src": "package.json",
"use": "@vercel/next"
}
]
}
```
**Container:** Next.js Application, serverless deployment on Vercel
---
## Detection CLI Commands
### Find Package Manifests
```bash
# Find npm package.json files
find . -name "package.json" -not -path "*/node_modules/*"
# Find Python requirements files
find . -name "requirements.txt" -o -name "Pipfile" -o -name "pyproject.toml"
# Find Java build files
find . -name "pom.xml" -o -name "build.gradle"
# Find Docker files
find . -name "Dockerfile" -o -name "docker-compose.yml"
# Find Kubernetes manifests
find . -name "*.yaml" -path "*/k8s/*" -o -path "*/kubernetes/*"
```
### Analyze Dependencies
```bash
# Node.js: List dependencies
cat package.json | jq '.dependencies'
# Python: List installed packages
pip list
# Java Maven: Show dependency tree
mvn dependency:tree
# Docker: Show image info
docker inspect <image-name>
```
### Grep for Framework Indicators
```bash
# Search for web frameworks
grep -r "express\|fastify\|nestjs" package.json
# Search for frontend frameworks
grep -r "react\|vue\|angular" package.json
# Search for Python frameworks
grep -r "django\|flask\|fastapi" requirements.txt
# Search for container orchestration
grep -r "kubernetes\|docker-compose" .
```
---
## Best Practices
1. **Check multiple indicators** - Don't rely on a single file
2. **Verify versions** - Framework versions matter for capabilities
3. **Look for actual usage** - Dependency presence doesn't guarantee usage
4. **Consider build artifacts** - Check dist/, build/, target/ folders
5. **Examine runtime configs** - .env files, config/*.json
6. **Review deployment configs** - Dockerfile, K8s manifests, serverless.yml
## Common Pitfalls
1. **Monorepo confusion** - Multiple package.json files may exist
2. **Dev vs prod dependencies** - Only production deps matter for runtime
3. **Transitive dependencies** - Don't confuse direct vs indirect deps
4. **Deprecated patterns** - Some frameworks have legacy detection patterns
5. **Polyglot projects** - May have multiple technologies in different folders

View File

@@ -0,0 +1,645 @@
# Troubleshooting Guide - C2 Container Analysis
This document provides solutions to common problems encountered during C4 Model Level 2 (Container) analysis.
## Problem: Too Many Containers Identified
**Symptom:** 15+ containers for a simple web application
**Root Cause:** Confusing C3 components with C2 containers
**Solution:** Remember the deployment boundary:
- **Containers** are **deployable units** (can be deployed independently)
- **Components** are **code modules** within containers (cannot be deployed alone)
- If it can't be deployed independently, it's probably C3
**Decision Test:**
```
Can this be deployed separately?
├─ ✅ Yes → C2 Container
└─ ❌ No → C3 Component
```
**Examples:**
| Item | Level | Reason |
|------|-------|--------|
| React SPA (builds to static files) | C2 Container | Deployed to CDN/web server |
| Auth module within React app | C3 Component | Part of SPA bundle |
| Express API server | C2 Container | Runs as separate process |
| Payment controller in Express | C3 Component | Code within API server |
| PostgreSQL database | C2 Container | Runs as separate process |
| User table in database | C3 Component | Schema within database |
**HARD LIMITS (Mandatory Validation):**
| Count | Classification | Action Required |
|-------|----------------|-----------------|
| 3-10 | ✅ Standard | Correct C2 abstraction level |
| 11-15 | ⚠️ Review Required | Each container MUST have explicit deployment boundary justification |
| 16-20 | ⚠️ Microservices | Document why this is microservices architecture, not over-granular |
| 20+ | 🛑 **STOP** | You are likely at C3 level. **Mandatory review of every container.** |
**RULE for 20+ Containers:**
- STOP analysis immediately
- Review EVERY identified "container" against the deployment boundary test
- Each item must answer YES to: "Can this be deployed independently?"
- If most answers are NO, you are at C3 level - consolidate to actual containers
- This is NOT guidance - this is a mandatory validation checkpoint
---
## Problem: Can't Determine Technology Stack
**Symptom:** No clear framework or language indicators
**Solution Steps:**
### Step 1: Check All Package Manifests
```bash
# Find all package files
find . -name "package.json" -o -name "requirements.txt" -o -name "pom.xml" -o -name "Cargo.toml"
# Examine dependencies
cat package.json | jq '.dependencies'
cat requirements.txt
```
### Step 2: Check Dockerfiles
```bash
# Find Dockerfiles
find . -name "Dockerfile*"
# Check base image
cat Dockerfile | grep "FROM"
```
**Common base images:**
- `FROM node:18` → Node.js 18
- `FROM python:3.11` → Python 3.11
- `FROM openjdk:17` → Java 17
- `FROM nginx:alpine` → Nginx web server
### Step 3: Count File Types
```bash
# Count source files by extension
find src -name "*.ts" | wc -l # TypeScript
find src -name "*.js" | wc -l # JavaScript
find src -name "*.py" | wc -l # Python
find src -name "*.java" | wc -l # Java
find src -name "*.go" | wc -l # Go
find src -name "*.rs" | wc -l # Rust
```
### Step 4: Check Build Configurations
```bash
# Check for framework config files
ls -la webpack.config.js tsconfig.json angular.json vue.config.js next.config.js
# Read framework configs
cat tsconfig.json | jq '.compilerOptions.jsx' # React indicator
cat angular.json | jq '.projects' # Angular indicator
```
### Step 5: Search for Framework Imports
```bash
# JavaScript/TypeScript frameworks
grep -r "from 'react'\|from 'vue'\|from '@angular" src/ | head -5
# Python frameworks
grep -r "from django\|from flask\|from fastapi" . | head -5
# Java frameworks
grep -r "import.*springframework" src/ | head -5
```
### Step 6: If Still Unclear - RESTRICTED USE ONLY
**"Unknown" is ONLY valid when ALL of these conditions are true:**
- ❌ NO manifest files exist (no package.json, requirements.txt, pom.xml, Cargo.toml, go.mod, Gemfile)
- ❌ NO Dockerfile exists OR Dockerfile does not specify version in FROM statement
- ❌ NO build configuration files found (tsconfig.json, angular.json, etc.)
- ❌ NO import statements reveal framework
**If ANY manifest file exists, you MUST extract the version. "Unknown" is NOT acceptable.**
When "Unknown" is legitimately required:
- Mark technology as **"Unknown"** temporarily
- Document **why** it's unclear with evidence of what you searched:
```json
{
"id": "obs-tech-unknown",
"category": "technology",
"severity": "critical",
"description": "Unable to determine primary framework. Searched for all standard manifest files - none found.",
"evidence": {
"type": "command",
"location": "find . -name 'package.json' -o -name 'requirements.txt' -o -name 'pom.xml' -o -name 'Cargo.toml' -o -name 'go.mod'",
"snippet": "No results found"
}
}
```
- Ask user for clarification immediately
- This triggers a CRITICAL observation, not a warning
**RULE:** If you mark something as "Unknown" when manifest files exist, this is a VIOLATION of C2 methodology.
---
## Problem: Container vs System Confusion
**Symptom:** Unclear if something is C1 System or C2 Container
**Remember the Levels:**
| Level | Abstraction | Example |
|-------|-------------|---------|
| **C1 System** | High-level logical system with business purpose | "E-Commerce System" |
| **C2 Container** | Deployable/runnable unit within a system | "React SPA", "Express API", "PostgreSQL DB" |
| **C3 Component** | Code module within a container | "ProductList.tsx", "PaymentController.ts" |
**Decision Tree:**
```
Does it have a business purpose understood by non-technical stakeholders?
├─ ✅ Yes → Could be C1 System
│ └─ Does it consist of multiple deployable units?
│ ├─ ✅ Yes → C1 System
│ └─ ❌ No → C2 Container (simple system with one container)
└─ ❌ No → Not C1 System
└─ Can it be deployed independently?
├─ ✅ Yes → C2 Container
└─ ❌ No → C3 Component
```
**Real Examples:**
**Example 1: E-Commerce System**
- "E-Commerce System" → **C1 System** (business purpose: sell products online)
- "Customer Web Portal" → **C2 Container** (React SPA)
- "Product API Server" → **C2 Container** (Express API)
- "Order Database" → **C2 Container** (PostgreSQL)
- "Product Catalog Component" → **C3 Component** (code in React SPA)
**Example 2: Payment Processing System**
- "Payment Processing System" → **C1 System** (business purpose: process payments)
- "Payment API Server" → **C2 Container** (NestJS API)
- "Payment Database" → **C2 Container** (PostgreSQL)
- "Stripe Integration Service" → **C2 Container** (Python worker)
- "PaymentController" → **C3 Component** (code in NestJS API)
**Example 3: Monolith Application**
- "Customer Portal System" → **C1 System**
- "Next.js Full-Stack Application" → **C2 Container** (single deployable unit)
- Frontend pages → **C3 Components**
- API routes → **C3 Components**
- "PostgreSQL Database" → **C2 Container**
---
## Problem: Missing Required Fields in Validation
**Symptom:** Validation script fails with "Missing required field"
### Common Missing Fields:
#### 1. `system_id`
**Error:** `Missing required field: system_id`
**Solution:**
```bash
# Check c1-systems.json for valid system IDs
cat c1-systems.json | jq '.systems[].id'
# Use exact ID (case-sensitive)
# Example: "ecommerce-system" NOT "Ecommerce-System"
```
#### 2. `technology.primary_language`
**Error:** `Missing required field: technology.primary_language`
**Solution:**
- JavaScript, TypeScript, Python, Java, Go, Rust, etc.
- Required for all containers except pure infrastructure
- Use capitalized language name
**Example:**
```json
{
"technology": {
"primary_language": "TypeScript",
"framework": "React 18.2.0"
}
}
```
#### 3. `technology.framework`
**Error:** `Missing required field: technology.framework`
**Solution:**
- React, Express, Django, Spring Boot, FastAPI, etc.
- Required for all application containers
- Include version number
**Example:**
```json
{
"technology": {
"primary_language": "JavaScript",
"framework": "Express.js 4.18.2"
}
}
```
**Exception:** Infrastructure containers (databases, caches) may use "N/A":
```json
{
"technology": {
"primary_language": "N/A",
"framework": "PostgreSQL 15.3"
}
}
```
#### 4. `runtime.environment`
**Error:** `Missing required field: runtime.environment`
**Valid Values:**
- `browser` - Client-side web application
- `server` - Server-side application
- `mobile` - iOS/Android application
- `cloud` - Cloud-native/serverless
- `edge` - Edge computing
- `desktop` - Desktop application
**Example:**
```json
{
"runtime": {
"environment": "server",
"platform": "Linux x64, Node.js 18.16.0"
}
}
```
#### 5. `runtime.platform`
**Error:** `Missing required field: runtime.platform`
**Solution:**
Describe the exact platform where the container runs.
**Examples:**
```json
// Browser
"platform": "Modern browsers (Chrome 90+, Firefox 88+, Safari 14+)"
// Server
"platform": "Linux x64, Node.js 18.16.0"
"platform": "Linux x64, Python 3.11.4"
"platform": "Linux x64, JVM 17"
// Mobile
"platform": "iOS 14+, Android 11+"
// Cloud
"platform": "AWS Lambda (Node.js 18 runtime)"
```
#### 6. `runtime.containerized`
**Error:** `Missing required field: runtime.containerized`
**Solution:**
- `true` - Runs in Docker/Kubernetes/container
- `false` - Runs directly on OS or in browser
**Examples:**
```json
// Containerized API
{
"runtime": {
"containerized": true,
"container_technology": "Docker",
"deployment_model": "Kubernetes with 3 replicas"
}
}
// Browser SPA
{
"runtime": {
"containerized": false
}
}
```
---
## Problem: Timestamp Validation Fails
**Symptom:** "Timestamp must be newer than parent timestamp"
**Root Cause:** c2-containers.json timestamp must be > c1-systems.json timestamp
**Solution:**
### Step 1: Check Current Timestamps
```bash
# Check C1 timestamp
cat c1-systems.json | jq '.metadata.timestamp'
# Example output: "2025-11-17T10:00:00.000Z"
# Check C2 timestamp
cat c2-containers.json | jq '.metadata.timestamp'
# Example output: "2025-11-17T09:00:00.000Z" # WRONG! Earlier than C1
```
### Step 2: Regenerate with Current Timestamp
Ensure ISO 8601 format: `YYYY-MM-DDTHH:mm:ss.sssZ`
```bash
# Generate current timestamp
date -u +"%Y-%m-%dT%H:%M:%S.000Z"
# Example: 2025-11-17T20:20:00.000Z
```
### Step 3: Update c2-containers.json
```json
{
"metadata": {
"timestamp": "2025-11-17T20:20:00.000Z",
"generated_by": "c2-abstractor",
"parent": {
"file": "c1-systems.json",
"timestamp": "2025-11-17T10:00:00.000Z"
}
}
}
```
**Rule:** Always ensure C2 timestamp > C1 timestamp
---
## Problem: Communication Pattern Unclear
**Symptom:** Don't know which relation type to use
**Solution: Decision Tree:**
```
What protocol is used?
├─ HTTP
│ ├─ REST API → "http-rest"
│ ├─ GraphQL → "http-graphql"
│ └─ Generic → "http"
├─ gRPC → "grpc"
├─ WebSocket → "websocket"
├─ Database
│ ├─ Read only → "database-read"
│ ├─ Write only → "database-write"
│ └─ Both → "database-query"
├─ Cache
│ ├─ Read only → "cache-read"
│ ├─ Write only → "cache-write"
│ └─ Both → "cache-read-write"
├─ Message Queue
│ ├─ Publish → "message-publish"
│ └─ Subscribe → "message-subscribe"
└─ File Storage
├─ Read → "file-read"
├─ Write → "file-write"
└─ Both → "file-read-write"
```
**Examples:**
- SPA calls API → `http-rest`
- API reads database → `database-query`
- API publishes to queue → `message-publish`
- Worker consumes queue → `message-subscribe`
- API caches responses → `cache-read-write`
---
## Problem: Monorepo vs Microservices Detection
**Symptom:** Unclear how many containers exist in a monorepo
**Solution:**
### Check for Multiple Package Files
```bash
# Find all package.json files (excluding node_modules)
find . -name "package.json" -not -path "*/node_modules/*"
# If multiple found, check structure
ls -la packages/ apps/ services/
```
### Check for Workspace Configuration
```bash
# Check for monorepo tools
cat package.json | jq '.workspaces' # npm/yarn workspaces
cat lerna.json # Lerna
cat nx.json # Nx
cat pnpm-workspace.yaml # pnpm
```
### Identify Deployable Units
**Rule:** Each independently deployable package = 1 container
**Example: Nx Monorepo**
```
monorepo/
├── apps/
│ ├── frontend/ → C2 Container (React SPA)
│ ├── api/ → C2 Container (NestJS API)
│ └── admin/ → C2 Container (Admin SPA)
├── libs/
│ ├── ui-components/ → C3 Component (shared library)
│ ├── data-access/ → C3 Component (shared library)
│ └── utils/ → C3 Component (shared library)
```
**Result:** 3 containers, 3 shared libraries (C3)
---
## Problem: Serverless Function Granularity
**Symptom:** Unclear if each Lambda function is a container
**Solution:**
### Option 1: Single Container (Recommended)
Treat all Lambda functions as **one container** if:
- Deployed together (single serverless.yml)
- Share same codebase
- Same runtime and dependencies
**Example:**
```yaml
# serverless.yml
functions:
getUser: ...
createUser: ...
updateUser: ...
deleteUser: ...
```
→ **One Container:** "User API Lambda Functions"
### Option 2: Multiple Containers
Only split into multiple containers if:
- Deployed independently (separate serverless.yml files)
- Different runtimes or dependencies
- Owned by different teams
**Example:**
```
services/
├── user-service/serverless.yml → C2 Container
├── order-service/serverless.yml → C2 Container
└── payment-service/serverless.yml → C2 Container
```
**Rule:** Deployment boundary = container boundary
---
## Quick Reference Checklists
### Container Type Checklist
- [ ] `spa` - Single-page application (browser)
- [ ] `mobile-app` - iOS/Android application
- [ ] `desktop-app` - Desktop application
- [ ] `api` or `app-server` - Backend API server
- [ ] `web-server` - Web server, reverse proxy
- [ ] `database` - Relational or NoSQL database
- [ ] `cache` - In-memory cache (Redis, Memcached)
- [ ] `message-broker` - Message queue/event streaming
- [ ] `worker` - Background job processor
- [ ] `file-storage` - Object storage, file system
### Technology Detection Checklist
- [ ] **Primary Language** - JavaScript, TypeScript, Python, Java, etc.
- [ ] **Framework** - React, Express, Django, Spring Boot, etc.
- [ ] **Version** - Always include version numbers from manifests
- [ ] **Key Libraries** - List important dependencies with purpose
### Runtime Environment Checklist
- [ ] **Environment** - browser / server / mobile / cloud / edge
- [ ] **Platform** - OS, runtime version, supported browsers
- [ ] **Containerized** - true / false
- [ ] **Container Technology** - Docker, Kubernetes (if containerized)
- [ ] **Deployment Model** - Standalone, replicated, serverless
### Communication Checklist
- [ ] **Protocol** - HTTP, gRPC, WebSocket, database, message queue
- [ ] **Direction** - unidirectional / bidirectional
- [ ] **Authentication** - JWT, OAuth, API key, none
- [ ] **Format** - JSON, Protobuf, XML, binary
### Validation Checklist
- [ ] All required fields present (system_id, technology, runtime)
- [ ] Timestamp newer than c1-systems.json
- [ ] Valid container types used
- [ ] Communication patterns documented
- [ ] Observations categorized (8 categories)
- [ ] Evidence provided for observations
---
## FORBIDDEN Rationalizations (Automatic Validation Failures)
When under pressure, you may be tempted to skip C2 methodology rules. These rationalizations are **always wrong** and trigger **automatic validation failures**:
**RULE:** If your thinking matches ANY of these rationalizations, STOP immediately. You are about to violate C2 methodology. Do not proceed without addressing the actual requirement.
**Consequences:**
- Each rationalization triggers a CRITICAL severity observation
- Validation scripts will fail with explicit error messages
- Work containing these violations will be rejected
| Rationalization | Why It's Wrong |
|-----------------|----------------|
| "Versions can be refined later" | Creates technical debt, violates methodology. Do it right now. |
| "Reading package.json is line-by-line analysis" | Manifest files are metadata, not code. Version detection is standard C2. |
| "Version numbers get outdated anyway" | So does all documentation - not an excuse to skip standards. |
| "Generic names are honest about current state" | Generic names violate C2 standards. Period. |
| "Tech lead/senior approved it" | Authority doesn't override methodology. Push back professionally. |
| "Each module is important" | Important ≠ C2 container. Many important things are C3 components. |
| "Team needs granularity" | Then do C3 analysis. Don't pollute C2. |
| "Good enough for now" | Standards exist for consistency across all analysis. |
| "Being pragmatic not dogmatic" | Pragmatism ≠ violating definitions. The methodology IS pragmatic. |
| "We can add more detail later" | "Later" never comes. Do it correctly now. |
| "The spirit of the rule allows this" | Violating the letter IS violating the spirit. |
| "This case is different" | No it isn't. Apply the same standards uniformly. |
**If you catch yourself thinking any of these - STOP. Follow the methodology.**
---
## Still Having Issues?
### Enable Debug Mode
```bash
# Run validation with verbose output
python scripts/validate-c2-containers.py --verbose c2-containers.json
# Check for specific issues
python scripts/validate-c2-containers.py --check-timestamps c2-containers.json
```
### Common Debug Commands
```bash
# Validate JSON syntax
cat c2-containers.json | jq . > /dev/null && echo "Valid JSON" || echo "Invalid JSON"
# Check required fields
cat c2-containers.json | jq '.containers[] | select(.technology.primary_language == null)'
# Verify timestamps
cat c2-containers.json | jq '.metadata.timestamp, .metadata.parent.timestamp'
# List all container IDs
cat c2-containers.json | jq '.containers[].id'
```
### Get Help
1. Review CLAUDE.md workflow guide
2. Check ${CLAUDE_PLUGIN_ROOT}/validation/templates/ for examples
3. Compare with c4model-c1 successful pattern
4. Ask user for clarification on unclear cases

231
skills/c4model-c3/SKILL.md Normal file
View File

@@ -0,0 +1,231 @@
---
name: c4model-c3
description: Expert methodology for C4 Model Level 3 (Component) analysis - identifying code-level components, their responsibilities, dependencies, and design patterns within containers. Use when analyzing component architecture, mapping code structure, detecting design patterns, identifying component boundaries and responsibilities, analyzing coupling and cohesion, or documenting components after C2 container identification. Essential for c3-abstractor agent during component identification phase.
---
# C4 Model - Level 3: Component Methodology
## Overview
You are an expert in the C4 Model's Level 3 (Component) methodology. This skill provides comprehensive knowledge for identifying and documenting software components at the code-level architectural abstraction.
**Your Mission:** Help identify WHAT code components exist within containers, WHAT responsibilities they have, and HOW they interact - with focus on design patterns and code structure.
### C3 Level Definition
The Component level shows the **internal structure** of containers - the major code building blocks:
- **Components** - Code modules, classes, packages with clear responsibilities
- **Responsibilities** - What each component does (single responsibility)
- **Dependencies** - How components depend on each other
- **Patterns** - Design patterns and architectural patterns used
- **Boundaries** - Package boundaries, module boundaries, layer boundaries
**At C3, we focus on:** Component identification and naming, responsibilities (single responsibility), dependencies and coupling, design patterns and architectural patterns, code organization, layer boundaries, component interactions.
**At C3, we do NOT focus on:** Individual functions/methods (C4), line-by-line code (C4), variable names and implementation details (C4), deployment details (C2).
---
## Detailed References
For comprehensive guidance on specific aspects of C3 component analysis, see:
- **[Component Identification](./component-identification.md)** - Component types, detection rules, boundaries, file structure patterns, responsibility analysis
- **[Dependency Analysis](./dependency-analysis.md)** - Dependency types, coupling analysis, circular dependencies, metrics, direction validation
- **[Pattern Detection](./pattern-detection.md)** - Design patterns (Singleton, Factory, Repository, etc.) and architectural patterns (MVC, Hexagonal, CQRS, etc.)
- **[Observation Guide](./observation-guide.md)** - Observation categories, severity levels, structure, evidence collection, quality metrics
- **[Technology Examples](./technology-examples.md)** - NestJS, Django, Spring Boot, React implementation examples and patterns
- **[Component Template](./templates/c3-component-template.json)** - JSON template for c3-components.json output
These references are loaded progressively when needed for detailed analysis.
---
## Component Identification Summary
A **component** at C3 level is a cohesive code module with clear responsibility - such as a collection of related classes/functions, an architectural building block, or a distinct layer/subsystem. Components include Controllers (HTTP handlers), Services (business logic), Repositories (data access), Models (data structures), Middleware (request processing), Utilities (helpers), DTOs (data transfer objects), and Adapters (external integrations).
**Key principles:** Focus on significant modules (>200 LOC or architecturally important), one primary responsibility per component (Single Responsibility Principle), group related code together (packages, modules, directories), avoid listing every file.
For complete methodology, see [component-identification.md](./component-identification.md).
---
## Dependency Analysis Summary
Component dependencies reveal the architecture's coupling and maintainability. Analyze internal dependencies (within container), external dependencies (libraries, frameworks), and framework dependencies. Validate dependency direction follows proper layering (Controllers → Services → Repositories → Models).
**Key metrics:** Afferent Coupling (Ca), Efferent Coupling (Ce), Instability (I = Ce / (Ca + Ce)), Circular Dependencies.
For complete methodology, see [dependency-analysis.md](./dependency-analysis.md).
---
## Pattern Detection Summary
Design patterns indicate architectural decisions and code quality. Detect Singleton, Factory, Repository, Dependency Injection, Observer, Strategy, Decorator, and Adapter patterns. Architectural patterns include MVC, Layered Architecture, Hexagonal, CQRS, Microkernel, and Event-Driven.
For complete methodology, see [pattern-detection.md](./pattern-detection.md).
---
## Observation Categories
Document findings using these categories: code-structure, design-patterns, dependencies, complexity, coupling, cohesion, testing, documentation.
**Severity levels:** info (informational), ⚠️ warning (potential issue), 🔴 critical (critical issue).
For complete guide, see [observation-guide.md](./observation-guide.md).
---
## Integration with Melly Workflow
### When This Skill is Used
This skill is activated during **Phase 3: C3 Component Identification** (`/melly-c3-components`) for component identification, responsibility analysis, dependency mapping, and pattern detection. Also used in **Phase 5: Documentation** (`/melly-doc-c4model`) for markdown generation.
### Input Expectations
Expects data from `c2-containers.json` with container details including id, name, type, system_id, path, technology (runtime, framework, language), and structure (entry_point, source_directory, build_output).
### Output Format
Generates `c3-components.json` with metadata (schema_version, generator, timestamp, parent_timestamp), components array (id, name, type, container_id, path, description, responsibilities, layer, dependencies, observations, relations, metrics), and summary (total_components, by_type, by_layer).
### Validation
Generated output must pass: Schema validation, timestamp ordering (metadata.timestamp > parent_timestamp), referential integrity (all dependency targets exist), required fields, ID format (kebab-case), container reference validation.
Validation script:
```bash
python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c3-components.py c3-components.json
```
---
## Step-by-Step Workflow
### Systematic Approach for c3-abstractor Agent
**Step 1: Load Input Data**
```bash
cat c2-containers.json | jq '.containers'
```
**Step 2: Analyze Each Container**
Navigate to container path, understand directory structure, identify organization pattern (feature-based, layer-based, domain-driven).
**Step 3: Identify Components**
Analyze files/directories, determine component type, extract responsibilities, identify dependencies.
**Step 4: Map Dependencies**
Find internal dependencies (within container), external dependencies (npm packages), document relationships.
**Step 5: Detect Patterns**
Search for design patterns (Singleton, Factory, Repository, Dependency Injection), identify architectural pattern.
**Step 6: Generate Observations**
Document code structure, design patterns, dependencies, complexity, and quality findings.
**Step 7: Calculate Metrics**
Count lines of code, cyclomatic complexity, dependency count, public methods count.
**Step 8: Validate Output**
Check component IDs (kebab-case, unique), container references, dependencies (all targets exist), timestamps (child > parent), run validation script.
---
## Best Practices
### ✅ DO:
1. **Identify significant components only** - Focus on major building blocks, avoid listing every file
2. **Use clear component names** - "User Service" not "userService.ts"
3. **Define single responsibility** - Each component has one clear purpose
4. **Document dependencies clearly** - Internal vs external, purpose of each
5. **Detect design patterns** - Singleton, Factory, Repository, etc.
6. **Analyze code structure** - Feature-based? Layer-based?
7. **Calculate metrics** - LOC, complexity, dependency count
8. **Check for layer violations** - Controllers should not call Repositories directly
9. **Identify circular dependencies** - Use tools, document as warnings
10. **Provide evidence in observations** - Code snippets, file paths, metrics
### ❌ DON'T:
1. **Don't list every file as a component** - Significant modules only
2. **Don't use file names as component names** - Focus on responsibility
3. **Don't ignore component responsibilities** - Always define purpose
4. **Don't skip dependency analysis** - Dependencies reveal architecture
5. **Don't overlook design patterns** - Patterns indicate architectural decisions
6. **Don't ignore metrics** - Metrics help identify refactoring needs
7. **Don't document test files as components** - Tests verify, aren't components
8. **Don't mix abstraction levels** - Keep C3 focused on components, not functions (C4)
9. **Don't skip validation** - Always validate generated JSON
10. **Don't ignore circular dependencies** - Flag and document
---
## Troubleshooting
**Too Many Components:** Focus on significant components - group small utilities, combine related files, use LOC threshold (>200 LOC).
**Can't Determine Type:** Analyze behavior - HTTP requests → Controller, business logic → Service, database access → Repository.
**Circular Dependencies:** Document as warning, suggest refactoring (extract shared logic, use events, remove circular reference).
**Missing Responsibilities:** Read public methods, check method names (create/update/delete), analyze dependencies, read comments.
**No Patterns Detected:** Look for dependency injection, repository pattern, factory pattern, singleton pattern - use grep commands.
**Can't Calculate Metrics:** Use simple LOC counting, count methods manually, count dependencies, document what you can measure.
---
## Quick Reference
### Component Types
controller, service, repository, model, middleware, utility, dto, adapter, factory, validator, facade, guard
### Layers
presentation (Controllers, Middleware, DTOs), business (Services, Domain Models, Validators), data (Repositories, Database Models), integration (Adapters, External Service Clients)
### Design Patterns
Singleton, Factory, Repository, Dependency Injection, Observer, Strategy, Decorator, Adapter
### Architectural Patterns
MVC, Layered (3-tier), Hexagonal (Ports & Adapters), CQRS, Microkernel, Event-Driven
### Observation Categories
code-structure, design-patterns, dependencies, complexity, coupling, cohesion, testing, documentation
### Metrics
Lines of Code (LOC), Cyclomatic Complexity, Number of Dependencies, Number of Public Methods, Afferent Coupling (Ca), Efferent Coupling (Ce), Instability (I = Ce / (Ca + Ce))
---
## Summary
You now have comprehensive knowledge of C4 Model Level 3 (Component) methodology. When invoked:
1. **Load input data** from `c2-containers.json`
2. **Analyze each container** to understand structure
3. **Identify components** using file structure and code analysis
4. **Classify components** by type (controller, service, repository, etc.)
5. **Define responsibilities** for each component
6. **Map dependencies** between components
7. **Detect patterns** (design patterns and architectural patterns)
8. **Generate observations** with evidence
9. **Calculate metrics** (LOC, complexity, dependencies)
10. **Validate output** before finalizing
Remember: **C3 is about code structure.** Focus on WHAT code components exist, WHAT they do, and HOW they interact - not the implementation details of individual functions (that's C4).
For detailed methodology on specific aspects, refer to the documentation files listed in the "Detailed References" section above.
---
**Skill Version**: 1.0.0
**Last Updated**: 2025-11-17
**Compatibility**: Melly 1.0.0+

View File

@@ -0,0 +1,511 @@
# Component Identification Methodology
This guide provides comprehensive methodology for identifying components at the C3 (Component) level of the C4 Model.
---
## Component Identification Methodology
### Step 1: Understand Container Structure
Start by analyzing the containers from `c2-containers.json`:
**Questions to ask:**
1. What containers exist in this system?
2. What is the technology stack for each container?
3. What is the directory structure?
4. What is the entry point?
**Container-to-Component Mapping:**
- **Backend API** → Controllers, Services, Repositories, Models
- **Web Frontend** → Pages, Components, Services, State Management
- **Mobile App** → Screens, ViewModels, Services, Repositories
- **Worker Service** → Jobs, Handlers, Processors, Queues
- **Library** → Modules, Utilities, Helpers
### Step 2: Apply Component Identification Rules
A **component** at C3 level is:
#### ✅ A Component IS:
1. **A cohesive code module with clear responsibility**
- Has one primary purpose (Single Responsibility Principle)
- Encapsulates related functionality
- Example: `UserAuthenticationService`, `OrderRepository`, `PaymentController`
2. **A collection of related classes/functions**
- Groups related code together
- Organized in a package, module, or directory
- Example: `authentication/` module with auth-related classes
3. **An architectural building block**
- Represents a significant piece of functionality
- Has well-defined interface/API
- Example: `EmailNotificationService`, `DatabaseConnection`
4. **A layer or subsystem**
- Distinct architectural layer
- Clear boundary from other layers
- Example: `data-access-layer/`, `business-logic-layer/`
#### ❌ A Component is NOT:
1. **Individual functions** (too granular - that's C4)
-`validateEmail()` function
-`calculateTotal()` function
-`ValidationService` (collection of validation functions)
2. **Single classes unless architecturally significant**
-`EmailValidator` class (too small)
-`AuthenticationService` class (significant)
- Rule: If class > 200 LOC or has major role, it's a component
3. **Configuration files**
-`config.json`
-`.env`
- These are not components, but configuration
4. **Test files**
-`UserService.test.ts`
- Tests verify components but aren't components themselves
### Step 3: Analyze File Structure
Use file system structure to identify components:
**Common patterns:**
#### Pattern 1: Directory-based Components (Recommended)
```
src/
├── authentication/ # → Component: Authentication
│ ├── AuthService.ts
│ ├── AuthController.ts
│ ├── TokenManager.ts
│ └── index.ts
├── users/ # → Component: User Management
│ ├── UserService.ts
│ ├── UserRepository.ts
│ ├── User.model.ts
│ └── index.ts
└── payments/ # → Component: Payment Processing
├── PaymentService.ts
├── PaymentGateway.ts
└── index.ts
```
#### Pattern 2: Layered Components
```
src/
├── controllers/ # → Component Layer: Controllers
│ ├── UserController.ts
│ ├── OrderController.ts
│ └── ProductController.ts
├── services/ # → Component Layer: Services
│ ├── UserService.ts
│ ├── OrderService.ts
│ └── ProductService.ts
└── repositories/ # → Component Layer: Repositories
├── UserRepository.ts
├── OrderRepository.ts
└── ProductRepository.ts
```
#### Pattern 3: Feature-based Components
```
src/
├── features/
│ ├── user-management/ # → Component: User Management
│ │ ├── components/
│ │ ├── services/
│ │ └── models/
│ ├── order-management/ # → Component: Order Management
│ │ ├── components/
│ │ ├── services/
│ │ └── models/
```
**Detection commands:**
```bash
# Find directories with code files
find src -type d -not -path "*/node_modules/*" -not -path "*/.git/*"
# List files by directory
ls -la src/*/
# Count files per directory
find src -type f \( -name "*.ts" -o -name "*.js" \) | xargs dirname | sort | uniq -c
```
### Step 4: Detect Component Types
Classify each component by type:
**Component Types:**
1. **controller** - HTTP request handlers
- Handles incoming requests
- Routes to services
- Returns responses
- Example: `UserController`, `OrderController`
2. **service** - Business logic
- Core business logic
- Orchestrates operations
- Encapsulates domain logic
- Example: `UserService`, `PaymentService`
3. **repository** - Data access
- Database operations
- Data persistence
- Query abstraction
- Example: `UserRepository`, `OrderRepository`
4. **model** - Data models
- Entity definitions
- Data structures
- Domain objects
- Example: `User`, `Order`, `Product`
5. **middleware** - Request/response processing
- Authentication middleware
- Logging middleware
- Validation middleware
- Example: `AuthMiddleware`, `LoggingMiddleware`
6. **utility** - Helper functions
- Shared utilities
- Common helpers
- Cross-cutting concerns
- Example: `DateUtils`, `StringUtils`
7. **dto** - Data transfer objects
- Request/response schemas
- API contracts
- Validation schemas
- Example: `CreateUserDto`, `LoginResponseDto`
8. **adapter** - External integrations
- Third-party API clients
- External service wrappers
- Protocol adapters
- Example: `StripeAdapter`, `SendGridAdapter`
9. **factory** - Object creation
- Complex object construction
- Dependency creation
- Example: `UserFactory`, `OrderFactory`
10. **validator** - Validation logic
- Input validation
- Business rule validation
- Example: `EmailValidator`, `OrderValidator`
11. **facade** - Simplified interfaces
- Simplifies complex subsystems
- Provides unified interface
- Example: `PaymentFacade`, `NotificationFacade`
12. **guard** - Authorization/authentication
- Access control
- Route protection
- Example: `AuthGuard`, `RoleGuard`
### Step 5: Define Component Boundaries
For each component, define:
#### 1. Package/Module Boundary
- What package or module does it belong to?
- What is the namespace?
- What is the import path?
**Example:**
```typescript
// Component: Authentication Service
// Package: @app/authentication
// Module: src/authentication/AuthService.ts
// Import: import { AuthService } from '@app/authentication';
```
#### 2. Layer Boundary
- What architectural layer?
- Presentation, Business Logic, Data Access?
**Example:**
```
Presentation Layer: Controllers, Middleware, DTOs
Business Logic Layer: Services, Domain Models, Validators
Data Access Layer: Repositories, Database Models, Adapters
```
#### 3. Responsibility Boundary
- What is the single responsibility?
- What does it do?
- What does it NOT do?
**Example:**
```json
{
"id": "user-service",
"name": "User Service",
"responsibility": "Manages user lifecycle operations including registration, profile updates, and account deletion",
"does": [
"Validate user input",
"Create new users",
"Update user profiles",
"Delete user accounts"
],
"does_not": [
"Handle HTTP requests (Controller's job)",
"Access database directly (Repository's job)",
"Send emails (Email Service's job)"
]
}
```
### Step 6: Identify Component Responsibilities
For each component, determine its responsibilities:
**Questions to ask:**
1. What is the primary purpose?
2. What operations does it perform?
3. What data does it manage?
4. What services does it provide?
5. What dependencies does it have?
**Analysis techniques:**
#### Technique 1: Analyze Public Methods
```typescript
// UserService.ts
export class UserService {
// Public interface reveals responsibilities:
async createUser(data: CreateUserDto): Promise<User>
async updateUser(id: string, data: UpdateUserDto): Promise<User>
async deleteUser(id: string): Promise<void>
async getUserById(id: string): Promise<User>
async getUserByEmail(email: string): Promise<User>
}
// Responsibilities:
// - User creation
// - User updates
// - User deletion
// - User retrieval by ID
// - User retrieval by email
```
#### Technique 2: Analyze Dependencies
```typescript
// PaymentService.ts depends on:
import { PaymentGateway } from './PaymentGateway';
import { OrderRepository } from '../orders/OrderRepository';
import { EmailService } from '../notifications/EmailService';
// Responsibilities indicated by dependencies:
// - Processes payments (PaymentGateway)
// - Updates order status (OrderRepository)
// - Sends payment confirmations (EmailService)
```
#### Technique 3: Analyze File Content
```bash
# Count methods in a class (using extended regex)
grep -E '^\s+(public|private|protected|async)\s+\w+\s*\(' UserService.ts
# Find key operations
grep -E '(create|update|delete|get|find|save)' UserService.ts
```
---
## Code Structure Analysis
### Directory Structure Patterns
#### Pattern 1: Feature-based Structure
```
src/
├── users/
│ ├── user.controller.ts # Component: User Controller
│ ├── user.service.ts # Component: User Service
│ ├── user.repository.ts # Component: User Repository
│ ├── user.model.ts # Component: User Model
│ ├── dto/
│ │ ├── create-user.dto.ts
│ │ └── update-user.dto.ts
│ └── index.ts
```
**Advantages:**
- Clear feature boundaries
- Easy to locate related code
- Good for domain-driven design
**Component detection:**
```bash
# List all feature directories
ls -d src/*/
# Count components per feature
find src \( -name "*.service.ts" -o -name "*.controller.ts" -o -name "*.repository.ts" \) | xargs dirname | sort | uniq -c
```
#### Pattern 2: Layer-based Structure
```
src/
├── controllers/
│ ├── user.controller.ts
│ ├── order.controller.ts
│ └── product.controller.ts
├── services/
│ ├── user.service.ts
│ ├── order.service.ts
│ └── product.service.ts
├── repositories/
│ ├── user.repository.ts
│ ├── order.repository.ts
│ └── product.repository.ts
└── models/
├── user.model.ts
├── order.model.ts
└── product.model.ts
```
**Advantages:**
- Clear layer separation
- Easy to enforce layer rules
- Good for traditional MVC
**Component detection:**
```bash
# Count components per layer
wc -l controllers/*.ts services/*.ts repositories/*.ts
```
#### Pattern 3: Domain-Driven Design (DDD)
```
src/
├── domain/
│ ├── user/
│ │ ├── User.entity.ts # Component: User Entity
│ │ ├── UserRepository.ts # Component: User Repository
│ │ └── UserService.ts # Component: User Domain Service
│ └── order/
│ ├── Order.entity.ts
│ ├── OrderRepository.ts
│ └── OrderService.ts
├── application/
│ ├── user/
│ │ ├── CreateUserUseCase.ts # Component: Create User Use Case
│ │ ├── UpdateUserUseCase.ts # Component: Update User Use Case
│ └── order/
│ ├── PlaceOrderUseCase.ts
│ └── CancelOrderUseCase.ts
└── infrastructure/
├── database/
│ ├── UserRepositoryImpl.ts # Component: User Repository Implementation
│ └── OrderRepositoryImpl.ts
└── http/
├── UserController.ts # Component: User Controller
└── OrderController.ts
```
**Advantages:**
- Clear domain boundaries
- Separation of concerns
- Testable use cases
### Export Pattern Analysis
Analyze how components expose their APIs:
#### Pattern 1: Named Exports
```typescript
// authentication/index.ts
export { AuthService } from './AuthService';
export { AuthController } from './AuthController';
export { TokenManager } from './TokenManager';
export * from './dto';
// Component: Authentication Module
// Public API: AuthService, AuthController, TokenManager, DTOs
```
#### Pattern 2: Default Exports
```typescript
// UserService.ts
export default class UserService { ... }
// Component: User Service
// Import: import UserService from './UserService';
```
#### Pattern 3: Facade Exports
```typescript
// payment/index.ts
import { PaymentService } from './PaymentService';
import { PaymentGateway } from './PaymentGateway';
import { PaymentValidator } from './PaymentValidator';
// Facade pattern - single entry point
export class PaymentFacade {
constructor(
private service: PaymentService,
private gateway: PaymentGateway,
private validator: PaymentValidator
) {}
// Simplified API
async processPayment(data: PaymentDto): Promise<PaymentResult> { ... }
}
// Component: Payment Facade
// Hides internal complexity
```
### Code Metrics Analysis
Use metrics to identify significant components:
#### Metric 1: Lines of Code (LOC)
```bash
# Count lines per file
find src -name "*.ts" -print0 | xargs -0 -r wc -l | sort -rn
# Components with > 200 LOC are significant
find src -name "*.ts" -print0 | xargs -0 -r wc -l | awk '$1 > 200 { print $2, $1 }'
```
**Guidelines:**
- **< 100 LOC**: Small component or helper
- **100-300 LOC**: Typical component
- **300-500 LOC**: Large component (consider splitting)
- **> 500 LOC**: Very large (definitely a component, likely needs refactoring)
#### Metric 2: Cyclomatic Complexity
```bash
# Use complexity tools
find src -name "*.ts" -print0 | xargs -0 -r npx ts-complexity
# High complexity (>10) indicates important component
```
#### Metric 3: Dependency Count
```bash
# Count imports per file
find src -name "*.ts" -print0 | xargs -0 -r grep -cH "^import" 2>/dev/null | sort -t: -k2 -rn
# Files with many imports are often important orchestrators (Services)
```
#### Metric 4: Export Count
```bash
# Count exports per file
find src -name "*.ts" -print0 | xargs -0 -r grep -cH "^export" 2>/dev/null | sort -t: -k2 -rn
# Files with many exports are often facades or utility modules
```

View File

@@ -0,0 +1,163 @@
# Dependency Analysis
This guide provides comprehensive methodology for analyzing component dependencies at the C3 level.
---
## Dependency Analysis
### Dependency Types
#### 1. Internal Dependencies (Within Container)
```typescript
// UserService.ts
import { UserRepository } from './UserRepository'; // Same feature
import { EmailService } from '../email/EmailService'; // Different feature
import { ValidationUtil } from '../utils/validation'; // Utility
// Dependencies:
// - UserRepository (direct dependency)
// - EmailService (cross-feature dependency)
// - ValidationUtil (utility dependency)
```
#### 2. External Dependencies (Outside Container)
```typescript
// PaymentService.ts
import Stripe from 'stripe'; // External library
import { Logger } from '@nestjs/common'; // Framework
import axios from 'axios'; // HTTP client
// External dependencies:
// - Stripe SDK
// - NestJS framework
// - Axios library
```
#### 3. Framework Dependencies
```typescript
// UserController.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
// Framework dependencies:
// - NestJS decorators
// - Swagger decorators
```
### Dependency Direction
Analyze the flow of dependencies:
**Recommended flow (Dependency Inversion):**
```
Controllers → Services → Repositories → Models
↓ ↓ ↓
(HTTP) (Business) (Data)
```
**Anti-pattern (Skip layers):**
```
Controllers → Repositories ❌ (skips business logic layer)
```
**Example: Good Dependency Direction**
```typescript
// Good: Controller depends on Service
@Controller('users')
export class UserController {
constructor(private userService: UserService) {}
@Post()
createUser(@Body() dto: CreateUserDto) {
return this.userService.createUser(dto);
}
}
// Good: Service depends on Repository
export class UserService {
constructor(private userRepo: UserRepository) {}
async createUser(dto: CreateUserDto) {
// Business logic here
return this.userRepo.save(user);
}
}
// Good: Repository depends on Model
export class UserRepository {
async save(user: User) {
// Data access here
}
}
```
### Coupling Analysis
**Types of coupling:**
#### 1. Tight Coupling (Bad)
```typescript
// Bad: Direct instantiation
export class UserService {
private emailService = new EmailService(); // ❌ Tightly coupled
async createUser(data: CreateUserDto) {
const user = await this.saveUser(data);
this.emailService.sendWelcome(user); // Can't mock in tests
}
}
```
#### 2. Loose Coupling (Good)
```typescript
// Good: Dependency injection
export class UserService {
constructor(private emailService: EmailService) {} // ✅ Loosely coupled
async createUser(data: CreateUserDto) {
const user = await this.saveUser(data);
this.emailService.sendWelcome(user); // Easy to mock
}
}
```
**Coupling metrics:**
- **Afferent Coupling (Ca)**: Number of components that depend on this component
- **Efferent Coupling (Ce)**: Number of components this component depends on
- **Instability (I)**: Ce / (Ca + Ce)
- I = 0: Very stable (many dependents, no dependencies)
- I = 1: Very unstable (no dependents, many dependencies)
**Detection:**
```bash
# Find components with many imports (high efferent coupling)
while IFS= read -r -d '' file; do
count=$(grep -c '^import' "$file" 2>/dev/null || echo 0)
printf "%d %s\n" "$count" "$file"
done < <(find src -name "*.ts" -print0) | sort -rn | head -20
# Find components imported by many others (high afferent coupling)
grep -rE "from ['\"](\.\./)+[^'\"]+['\"]" src/ | cut -d: -f2 | cut -d"'" -d'"' -f2 | sort | uniq -c | sort -rn
```
### Circular Dependency Detection
**Anti-pattern: Circular dependencies**
```
UserService → OrderService → UserService ❌
```
**Detection:**
```bash
# Use madge for Node.js projects
npx madge --circular src/
# Use dependency-cruiser
npx depcruise --validate .dependency-cruiser.js src/
```
**Solution:**
- Extract shared logic to third component
- Use events instead of direct calls
- Refactor to remove circular reference

View File

@@ -0,0 +1,126 @@
# Observation Guide for C3 Components
This guide provides comprehensive methodology for documenting observations at the C3 level.
---
## Observation Categories for C3
### Observation Categories
When documenting components, capture these observation categories:
#### 1. **code-structure**
Code organization patterns and file structure
**Examples:**
- "Feature-based structure with users/, orders/, products/ directories"
- "Layered architecture with controllers/, services/, repositories/ separation"
- "Domain-driven design with domain/, application/, infrastructure/ layers"
- "Monolithic structure - all code in single src/ directory"
#### 2. **design-patterns**
Design patterns identified in code
**Examples:**
- "Singleton pattern for DatabaseConnection ensures single instance"
- "Repository pattern abstracts data access across all entities"
- "Factory pattern used for creating different user types"
- "Dependency injection via NestJS @Injectable decorators"
- "Observer pattern for event-driven order processing"
#### 3. **dependencies**
Component dependencies and coupling
**Examples:**
- "UserService depends on UserRepository, EmailService, and ValidationUtil"
- "High coupling between OrderService and PaymentService (7 method calls)"
- "Circular dependency detected: UserService ↔ OrderService"
- "Controllers depend only on Services (proper layering)"
#### 4. **complexity**
Code complexity metrics
**Examples:**
- "OrderService has cyclomatic complexity of 24 (high risk)"
- "UserController is 450 LOC (consider splitting)"
- "PaymentService has 12 public methods (large interface)"
- "Average complexity across services: 8 (acceptable)"
#### 5. **coupling**
Coupling and cohesion analysis
**Examples:**
- "Tight coupling: UserService directly instantiates EmailService (no DI)"
- "Loose coupling: All dependencies injected via constructor"
- "High afferent coupling: UserModel imported by 15 components"
- "Low cohesion: UtilityService has unrelated helper methods"
#### 6. **cohesion**
Component cohesion and single responsibility
**Examples:**
- "UserService has high cohesion - all methods relate to user management"
- "UtilityService has low cohesion - contains unrelated helpers"
- "OrderController violates SRP - handles both orders and payments"
- "Each repository focused on single entity (good cohesion)"
#### 7. **testing**
Test coverage and testability
**Examples:**
- "UserService has 95% test coverage with 24 unit tests"
- "PaymentGateway untestable - uses hardcoded external URLs"
- "All services use dependency injection for easy mocking"
- "Controllers have integration tests covering main flows"
#### 8. **documentation**
Code documentation quality
**Examples:**
- "All public methods have JSDoc comments"
- "UserService missing documentation for complex methods"
- "README.md in authentication/ explains module architecture"
- "Inline comments explain business logic in PaymentService"
### Observation Structure for C3
```json
{
"id": "obs-repo-pattern-all-entities",
"title": "Repository pattern used for all entity data access",
"category": "design-patterns",
"severity": "info",
"pattern": "repository",
"description": "All entities (User, Order, Product, Payment) have dedicated repository classes that abstract database operations using the Repository pattern. Repositories provide methods like findById, findAll, save, delete.",
"evidence": [
{
"type": "pattern",
"location": "src/users/UserRepository.ts",
"snippet": "export class UserRepository { async findById(id: string): Promise<User> { ... } }"
},
{
"type": "pattern",
"location": "src/orders/OrderRepository.ts",
"snippet": "export class OrderRepository { async findById(id: string): Promise<Order> { ... } }"
}
],
"impact": {
"maintainability": "high",
"testability": "high",
"scalability": "medium"
},
"tags": ["repository-pattern", "data-access", "abstraction"]
}
```
### Observation Severity Levels
- **info** - Informational observation (neutral)
- **warning** - Potential issue requiring attention
- **critical** - Critical issue requiring immediate action
**Examples:**
- **info**: "Repository pattern used for data access abstraction"
- ⚠️ **warning**: "Circular dependency between UserService and OrderService"
- 🔴 **critical**: "No input validation in UserController endpoints"

View File

@@ -0,0 +1,522 @@
# Pattern Detection
This guide provides comprehensive methodology for detecting design patterns and architectural patterns at the C3 level.
---
## Pattern Detection
### Design Patterns
#### Pattern 1: Singleton Pattern
**Description:** Ensures a class has only one instance
**Detection:**
```typescript
// Singleton pattern indicators
export class DatabaseConnection {
private static instance: DatabaseConnection;
private constructor() {} // Private constructor
static getInstance(): DatabaseConnection {
if (!this.instance) {
this.instance = new DatabaseConnection();
}
return this.instance;
}
}
```
**Grep detection:**
```bash
grep -r "private static.*instance" src/
grep -r "private constructor" src/
grep -r "getInstance()" src/
```
**Observation:**
```json
{
"id": "obs-singleton-database",
"title": "Singleton pattern for database connection",
"category": "design-patterns",
"severity": "info",
"pattern": "singleton",
"description": "DatabaseConnection uses Singleton pattern to ensure single instance across application"
}
```
#### Pattern 2: Factory Pattern
**Description:** Creates objects without specifying exact class
**Detection:**
```typescript
// Factory pattern indicators
export class UserFactory {
static createUser(type: string, data: any): User {
switch (type) {
case 'admin':
return new AdminUser(data);
case 'customer':
return new CustomerUser(data);
default:
return new GuestUser(data);
}
}
}
```
**Grep detection:**
```bash
grep -r "Factory" src/
grep -r "static create" src/
```
#### Pattern 3: Repository Pattern
**Description:** Abstracts data access logic
**Detection:**
```typescript
// Repository pattern indicators
export class UserRepository {
async findById(id: string): Promise<User> { ... }
async findAll(): Promise<User[]> { ... }
async save(user: User): Promise<User> { ... }
async delete(id: string): Promise<void> { ... }
}
```
**Grep detection:**
```bash
grep -r "Repository" src/
grep -rE "findById|findAll|save.*Promise" src/
```
#### Pattern 4: Dependency Injection
**Description:** Dependencies provided externally
**Detection in NestJS:**
```typescript
@Injectable()
export class UserService {
constructor(
@Inject(UserRepository) private userRepo: UserRepository,
@Inject(EmailService) private emailService: EmailService
) {}
}
```
**Detection in Spring (Java):**
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private EmailService emailService;
}
```
**Grep detection:**
```bash
# NestJS
grep -rE "@Injectable|@Inject" src/
# Spring
grep -rE "@Service|@Autowired|@Component" src/
# Constructor injection
grep -r "constructor(" src/ | grep "private"
```
#### Pattern 5: Observer Pattern (Event-Driven)
**Description:** Publish-subscribe mechanism
**Detection:**
```typescript
// Observer pattern indicators
export class OrderService {
async createOrder(data: CreateOrderDto) {
const order = await this.orderRepo.save(data);
// Emit event
this.eventEmitter.emit('order.created', order);
return order;
}
}
// Observers
export class EmailService {
@OnEvent('order.created')
handleOrderCreated(order: Order) {
this.sendOrderConfirmation(order);
}
}
```
**Grep detection:**
```bash
grep -rE "\.emit|\.on|@OnEvent|subscribe|publish" src/
```
#### Pattern 6: Strategy Pattern
**Description:** Select algorithm at runtime
**Detection:**
```typescript
// Strategy pattern
interface PaymentStrategy {
pay(amount: number): Promise<PaymentResult>;
}
class CreditCardPayment implements PaymentStrategy {
async pay(amount: number) { ... }
}
class PayPalPayment implements PaymentStrategy {
async pay(amount: number) { ... }
}
class PaymentContext {
constructor(private strategy: PaymentStrategy) {}
async executePayment(amount: number) {
return this.strategy.pay(amount);
}
}
```
**Grep detection:**
```bash
grep -rE "implements.*Strategy|Strategy.*interface" src/
```
#### Pattern 7: Decorator Pattern
**Description:** Add behavior dynamically
**Detection in TypeScript:**
```typescript
// Decorator pattern (using TypeScript decorators)
@Controller('users')
@UseGuards(AuthGuard) // Decorator
@UseInterceptors(LoggingInterceptor) // Decorator
export class UserController {
@Get()
@Roles('admin') // Decorator
findAll() { ... }
}
```
**Grep detection:**
```bash
grep -rE "^@\w+\(" src/
```
#### Pattern 8: Adapter Pattern
**Description:** Converts interface to another interface
**Detection:**
```typescript
// Adapter pattern
export class StripeAdapter {
constructor(private stripeClient: Stripe) {}
// Adapt Stripe API to internal interface
async processPayment(payment: PaymentDto): Promise<PaymentResult> {
const stripePayment = this.convertToStripeFormat(payment);
const result = await this.stripeClient.charges.create(stripePayment);
return this.convertFromStripeFormat(result);
}
}
```
**Grep detection:**
```bash
grep -r "Adapter" src/
grep -r "convert.*Format" src/
```
---
## Common Architecture Patterns
### Pattern 1: MVC (Model-View-Controller)
**Description:** Separates concerns into Model, View, Controller
**Component structure:**
```
src/
├── models/ # Models (Data)
│ ├── User.ts
│ ├── Order.ts
│ └── Product.ts
├── views/ # Views (Presentation) - if server-rendered
│ ├── user-list.ejs
│ └── order-detail.ejs
└── controllers/ # Controllers (Logic)
├── UserController.ts
├── OrderController.ts
└── ProductController.ts
```
**Components identified:**
- **Controllers**: UserController, OrderController, ProductController
- **Models**: User, Order, Product
- **Views**: (if applicable)
**Observation:**
```json
{
"id": "obs-mvc-pattern",
"title": "MVC pattern with controllers and models",
"category": "architectural-pattern",
"pattern": "mvc",
"description": "Application follows MVC pattern with clear separation between controllers (request handling) and models (data representation)"
}
```
---
### Pattern 2: Layered Architecture (3-Tier)
**Description:** Separates into Presentation, Business Logic, Data Access layers
**Component structure:**
```
src/
├── presentation/ # Presentation Layer
│ ├── controllers/
│ │ ├── UserController.ts
│ │ └── OrderController.ts
│ └── middleware/
│ ├── AuthMiddleware.ts
│ └── ValidationMiddleware.ts
├── business/ # Business Logic Layer
│ ├── services/
│ │ ├── UserService.ts
│ │ └── OrderService.ts
│ └── validators/
│ ├── UserValidator.ts
│ └── OrderValidator.ts
└── data/ # Data Access Layer
├── repositories/
│ ├── UserRepository.ts
│ └── OrderRepository.ts
└── models/
├── User.model.ts
└── Order.model.ts
```
**Layer rules:**
- Presentation → Business Logic → Data Access (one direction only)
- No skipping layers (Controller can't call Repository directly)
**Components identified:**
- **Presentation**: UserController, OrderController, AuthMiddleware
- **Business Logic**: UserService, OrderService, UserValidator
- **Data Access**: UserRepository, OrderRepository, User Model, Order Model
**Detection:**
```bash
# Check for layer violations
grep -r "Repository" src/controllers/ # ❌ Controller calling Repository directly
# Verify proper layering
grep -r "Service" src/controllers/ # ✅ Controller calling Service
grep -r "Repository" src/services/ # ✅ Service calling Repository
```
---
### Pattern 3: Hexagonal Architecture (Ports & Adapters)
**Description:** Core business logic isolated from external concerns
**Component structure:**
```
src/
├── domain/ # Core Domain (Business Logic)
│ ├── user/
│ │ ├── User.entity.ts
│ │ ├── UserService.ts
│ │ └── ports/
│ │ ├── UserRepository.port.ts # Interface
│ │ └── EmailService.port.ts # Interface
│ └── order/
│ ├── Order.entity.ts
│ └── OrderService.ts
├── application/ # Application Services (Use Cases)
│ ├── CreateUserUseCase.ts
│ ├── PlaceOrderUseCase.ts
│ └── ProcessPaymentUseCase.ts
└── infrastructure/ # Infrastructure (Adapters)
├── database/
│ └── UserRepositoryImpl.ts # Implementation
├── email/
│ └── EmailServiceImpl.ts # Implementation
└── http/
├── UserController.ts # HTTP Adapter
└── OrderController.ts # HTTP Adapter
```
**Key concepts:**
- **Ports**: Interfaces defined by domain (UserRepository.port.ts)
- **Adapters**: Implementations in infrastructure (UserRepositoryImpl.ts)
- **Dependency Inversion**: Domain defines interfaces, infrastructure implements
**Components identified:**
- **Domain**: User, Order, UserService, OrderService
- **Ports**: UserRepository (interface), EmailService (interface)
- **Adapters**: UserRepositoryImpl, EmailServiceImpl, UserController
- **Use Cases**: CreateUserUseCase, PlaceOrderUseCase
**Observation:**
```json
{
"id": "obs-hexagonal-arch",
"title": "Hexagonal architecture with ports and adapters",
"category": "architectural-pattern",
"pattern": "hexagonal",
"description": "Application uses hexagonal architecture. Domain defines port interfaces (UserRepository.port.ts), infrastructure provides adapter implementations (UserRepositoryImpl.ts). Business logic isolated from external dependencies."
}
```
---
### Pattern 4: CQRS (Command Query Responsibility Segregation)
**Description:** Separate read and write operations
**Component structure:**
```
src/
├── commands/ # Write side (Commands)
│ ├── CreateUserCommand.ts
│ ├── UpdateUserCommand.ts
│ └── handlers/
│ ├── CreateUserHandler.ts
│ └── UpdateUserHandler.ts
├── queries/ # Read side (Queries)
│ ├── GetUserQuery.ts
│ ├── ListUsersQuery.ts
│ └── handlers/
│ ├── GetUserHandler.ts
│ └── ListUsersHandler.ts
└── models/
├── write/ # Write models
│ └── User.entity.ts
└── read/ # Read models (often denormalized)
└── UserView.ts
```
**Key concepts:**
- **Commands**: Change state (CreateUser, UpdateUser)
- **Queries**: Read state (GetUser, ListUsers)
- **Separate models**: Write model vs Read model
**Components identified:**
- **Commands**: CreateUserCommand, UpdateUserCommand
- **Command Handlers**: CreateUserHandler, UpdateUserHandler
- **Queries**: GetUserQuery, ListUsersQuery
- **Query Handlers**: GetUserHandler, ListUsersHandler
- **Write Models**: User (entity)
- **Read Models**: UserView
**Detection:**
```bash
grep -rE "Command|Handler" src/
grep -rE "Query|Handler" src/
grep -rE "@CommandHandler|@QueryHandler" src/ # NestJS CQRS
```
---
### Pattern 5: Microkernel (Plugin Architecture)
**Description:** Core system with pluggable modules
**Component structure:**
```
src/
├── core/ # Core System
│ ├── Application.ts
│ ├── PluginManager.ts
│ └── interfaces/
│ └── Plugin.interface.ts
└── plugins/ # Plugins
├── authentication/
│ ├── AuthPlugin.ts
│ └── AuthService.ts
├── logging/
│ ├── LoggingPlugin.ts
│ └── Logger.ts
└── cache/
├── CachePlugin.ts
└── CacheService.ts
```
**Key concepts:**
- **Core**: Minimal core system
- **Plugins**: Optional modules that extend core
- **Plugin Interface**: Contract for plugins
**Components identified:**
- **Core**: Application, PluginManager
- **Plugins**: AuthPlugin, LoggingPlugin, CachePlugin
- **Plugin Interface**: Plugin.interface.ts
---
### Pattern 6: Event-Driven Architecture
**Description:** Components communicate via events
**Component structure:**
```
src/
├── events/ # Event Definitions
│ ├── UserCreatedEvent.ts
│ ├── OrderPlacedEvent.ts
│ └── PaymentProcessedEvent.ts
├── publishers/ # Event Publishers
│ ├── UserEventPublisher.ts
│ └── OrderEventPublisher.ts
└── subscribers/ # Event Subscribers
├── EmailSubscriber.ts
├── AnalyticsSubscriber.ts
└── NotificationSubscriber.ts
```
**Component flow:**
```
UserService → publishes UserCreatedEvent
[Event Bus / Message Queue]
EmailSubscriber receives event → sends welcome email
AnalyticsSubscriber receives event → tracks user registration
```
**Components identified:**
- **Event Publishers**: UserEventPublisher, OrderEventPublisher
- **Event Subscribers**: EmailSubscriber, AnalyticsSubscriber, NotificationSubscriber
- **Events**: UserCreatedEvent, OrderPlacedEvent, PaymentProcessedEvent
- **Event Bus**: EventEmitter, Message Queue
**Detection:**
```bash
grep -rE "Event|emit|publish|subscribe" src/
grep -rE "@OnEvent|@Subscribe" src/ # Framework decorators
```

View File

@@ -0,0 +1,198 @@
# Technology-Specific Examples
This guide provides technology-specific examples for component identification at the C3 level.
---
## Technology-Specific Examples
### NestJS Example
**Component identification in NestJS backend:**
```typescript
// src/users/user.controller.ts
@Controller('users')
export class UserController { // Component: User Controller (controller)
constructor(private userService: UserService) {}
@Post()
create(@Body() dto: CreateUserDto) {
return this.userService.create(dto);
}
}
// src/users/user.service.ts
@Injectable()
export class UserService { // Component: User Service (service)
constructor(private userRepo: UserRepository) {}
async create(dto: CreateUserDto) {
return this.userRepo.save(dto);
}
}
// src/users/user.repository.ts
@Injectable()
export class UserRepository { // Component: User Repository (repository)
constructor(@InjectRepository(User) private repo: Repository<User>) {}
async save(data: CreateUserDto) {
return this.repo.save(data);
}
}
```
**Components:**
1. **User Controller** (controller) - Handles HTTP requests
2. **User Service** (service) - Business logic
3. **User Repository** (repository) - Data access
**Patterns:**
- Dependency Injection (@Injectable, constructor injection)
- Repository Pattern (UserRepository)
- Layered Architecture (Controller → Service → Repository)
---
### Django Example (Python)
**Component identification in Django backend:**
```python
# users/views.py
class UserViewSet(viewsets.ModelViewSet): # Component: User ViewSet (controller)
queryset = User.objects.all()
serializer_class = UserSerializer
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
user = UserService.create_user(serializer.validated_data)
return Response(UserSerializer(user).data)
# users/services.py
class UserService: # Component: User Service (service)
@staticmethod
def create_user(data):
# Business logic
user = User.objects.create(**data)
EmailService.send_welcome(user)
return user
# users/models.py
class User(models.Model): # Component: User Model (model)
email = models.EmailField(unique=True)
name = models.CharField(max_length=100)
class Meta:
db_table = 'users'
```
**Components:**
1. **User ViewSet** (controller) - Handles HTTP requests
2. **User Service** (service) - Business logic
3. **User Model** (model) - Data model
---
### Spring Boot Example (Java)
**Component identification in Spring Boot backend:**
```java
// UserController.java
@RestController
@RequestMapping("/users")
public class UserController { // Component: User Controller (controller)
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity<User> createUser(@RequestBody CreateUserDto dto) {
User user = userService.createUser(dto);
return ResponseEntity.ok(user);
}
}
// UserService.java
@Service
public class UserService { // Component: User Service (service)
@Autowired
private UserRepository userRepository;
@Autowired
private EmailService emailService;
public User createUser(CreateUserDto dto) {
User user = new User(dto);
userRepository.save(user);
emailService.sendWelcome(user);
return user;
}
}
// UserRepository.java
@Repository
public interface UserRepository extends JpaRepository<User, Long> { // Component: User Repository (repository)
Optional<User> findByEmail(String email);
}
```
**Components:**
1. **User Controller** (controller) - HTTP request handling
2. **User Service** (service) - Business logic
3. **User Repository** (repository) - Data access
**Patterns:**
- Dependency Injection (@Autowired)
- Repository Pattern (Spring Data JPA)
- Layered Architecture
---
### React Example (Frontend)
**Component identification in React frontend:**
```typescript
// src/features/users/UserList.tsx
export function UserList() { // Component: User List (page/screen)
const { users, loading } = useUsers();
return (
<div>
{users.map(user => <UserCard key={user.id} user={user} />)}
</div>
);
}
// src/features/users/hooks/useUsers.ts
export function useUsers() { // Component: User Hook (state management)
const [users, setUsers] = useState([]);
useEffect(() => {
UserService.fetchUsers().then(setUsers);
}, []);
return { users, loading };
}
// src/services/UserService.ts
export class UserService { // Component: User Service (service)
static async fetchUsers() {
const response = await api.get('/users');
return response.data;
}
static async createUser(data: CreateUserDto) {
const response = await api.post('/users', data);
return response.data;
}
}
```
**Components:**
1. **User List** (page) - UI component
2. **useUsers Hook** (state-management) - State management
3. **User Service** (service) - API client

View File

@@ -0,0 +1,246 @@
{
"metadata": {
"schema_version": "1.0.0",
"generator": "melly-workflow",
"generated_by": "c3-abstractor",
"timestamp": "2025-11-17T10:30:00.000Z",
"melly_version": "1.0.0",
"parent_timestamp": "2025-11-17T10:20:00.000Z"
},
"components": [
{
"id": "user-controller",
"name": "User Controller",
"type": "controller",
"container_id": "backend-api",
"path": "src/users/user.controller.ts",
"description": "Handles HTTP requests for user management operations",
"responsibilities": [
"Validate incoming HTTP requests",
"Route requests to UserService",
"Transform service responses to HTTP responses",
"Handle authentication and authorization"
],
"layer": "presentation",
"dependencies": [
{
"target": "user-service",
"type": "internal",
"purpose": "Delegates business logic to UserService"
}
],
"observations": [
{
"id": "obs-controller-rest-api",
"title": "RESTful API design for user endpoints",
"category": "design-patterns",
"severity": "info",
"description": "UserController follows RESTful conventions with standard HTTP methods (GET, POST, PUT, DELETE) for CRUD operations",
"evidence": [
{
"type": "code",
"location": "src/users/user.controller.ts",
"snippet": "@Get() findAll() { ... }\n@Post() create(@Body() dto: CreateUserDto) { ... }"
}
],
"impact": {
"maintainability": "high",
"testability": "high",
"scalability": "medium"
},
"tags": ["rest-api", "http", "design-pattern"]
}
],
"relations": [
{
"id": "rel-controller-to-service",
"source_id": "user-controller",
"target_id": "user-service",
"type": "depends-on",
"protocol": "method-call",
"description": "UserController delegates business logic to UserService",
"bidirectional": false
}
],
"metrics": {
"lines_of_code": 150,
"cyclomatic_complexity": 6,
"public_methods": 5,
"dependencies_count": 2
}
},
{
"id": "user-service",
"name": "User Service",
"type": "service",
"container_id": "backend-api",
"path": "src/users/user.service.ts",
"description": "Manages user lifecycle operations including registration, updates, and deletion",
"responsibilities": [
"Validate user business rules",
"Orchestrate user operations",
"Coordinate between repositories and external services",
"Implement user domain logic"
],
"layer": "business",
"dependencies": [
{
"target": "user-repository",
"type": "internal",
"purpose": "Persists user data to database"
},
{
"target": "email-service",
"type": "internal",
"purpose": "Sends user-related email notifications"
}
],
"observations": [
{
"id": "obs-service-dependency-injection",
"title": "Dependency injection pattern for loose coupling",
"category": "design-patterns",
"severity": "info",
"description": "UserService uses constructor-based dependency injection for all dependencies, enabling loose coupling and easy testing",
"evidence": [
{
"type": "code",
"location": "src/users/user.service.ts",
"snippet": "constructor(private userRepo: UserRepository, private emailService: EmailService) {}"
}
],
"impact": {
"maintainability": "high",
"testability": "high",
"scalability": "high"
},
"tags": ["dependency-injection", "loose-coupling", "testability"]
}
],
"relations": [
{
"id": "rel-service-to-repository",
"source_id": "user-service",
"target_id": "user-repository",
"type": "depends-on",
"protocol": "method-call",
"description": "UserService delegates data persistence to UserRepository",
"bidirectional": false
}
],
"metrics": {
"lines_of_code": 280,
"cyclomatic_complexity": 12,
"public_methods": 8,
"dependencies_count": 3
}
},
{
"id": "user-repository",
"name": "User Repository",
"type": "repository",
"container_id": "backend-api",
"path": "src/users/user.repository.ts",
"description": "Abstracts data access operations for User entity",
"responsibilities": [
"Execute database queries for user data",
"Map database rows to User entities",
"Handle database transaction management",
"Provide query abstraction layer"
],
"layer": "data",
"dependencies": [
{
"target": "user-model",
"type": "internal",
"purpose": "Defines the User entity structure"
}
],
"observations": [
{
"id": "obs-repository-pattern",
"title": "Repository pattern for data access abstraction",
"category": "design-patterns",
"severity": "info",
"description": "UserRepository implements the Repository pattern, providing standard methods (findById, findAll, save, delete) to abstract database operations",
"evidence": [
{
"type": "pattern",
"location": "src/users/user.repository.ts",
"snippet": "async findById(id: string): Promise<User>\nasync findAll(): Promise<User[]>\nasync save(user: User): Promise<User>\nasync delete(id: string): Promise<void>"
}
],
"impact": {
"maintainability": "high",
"testability": "high",
"scalability": "medium"
},
"tags": ["repository-pattern", "data-access", "abstraction"]
}
],
"relations": [
{
"id": "rel-repository-to-model",
"source_id": "user-repository",
"target_id": "user-model",
"type": "uses",
"protocol": "type-reference",
"description": "UserRepository uses User model for entity definition",
"bidirectional": false
}
],
"metrics": {
"lines_of_code": 120,
"cyclomatic_complexity": 4,
"public_methods": 6,
"dependencies_count": 1
}
}
],
"summary": {
"total_components": 3,
"by_type": {
"controller": 1,
"service": 1,
"repository": 1,
"model": 0,
"middleware": 0,
"utility": 0,
"dto": 0,
"adapter": 0,
"factory": 0,
"validator": 0,
"facade": 0,
"guard": 0
},
"by_layer": {
"presentation": 1,
"business": 1,
"data": 1,
"integration": 0
},
"patterns_detected": [
"repository-pattern",
"dependency-injection",
"layered-architecture"
],
"observations_summary": {
"total": 3,
"by_category": {
"design-patterns": 3,
"code-structure": 0,
"dependencies": 0,
"complexity": 0,
"coupling": 0,
"cohesion": 0,
"testing": 0,
"documentation": 0
},
"by_severity": {
"info": 3,
"warning": 0,
"critical": 0
}
}
}
}

341
skills/c4model-c4/SKILL.md Normal file
View File

@@ -0,0 +1,341 @@
---
name: c4model-c4
description: Expert methodology for C4 Model Level 4 (Code) analysis - identifying classes, functions, methods, interfaces, and types within components. Use when analyzing code-level structure, mapping signatures, detecting complexity, identifying code patterns, or documenting code elements after C3 component identification. Essential for c4-abstractor agent during code element identification phase.
---
# C4 Model - Level 4: Code Methodology
## Overview
You are an expert in the C4 Model's Level 4 (Code) methodology. This skill provides comprehensive knowledge for identifying and documenting code elements at the most granular level of architectural abstraction.
**Your Mission:** Help identify WHAT code elements exist within components, WHAT they do, and HOW they interact - focusing on classes, functions, methods, interfaces, and types.
### C4 Level Definition
The Code level shows the **internal implementation** of components - the actual code building blocks:
- **Classes** - Object-oriented class definitions with inheritance and interfaces
- **Functions** - Standalone functions and async functions
- **Methods** - Class methods with visibility modifiers
- **Interfaces** - Type contracts and interface definitions
- **Types** - Type aliases, generics, and type definitions
- **Constants/Enums** - Constant values and enumerations
**At C4, we focus on:** Class structure, function signatures, method implementations, type definitions, code metrics, inheritance hierarchies, interface implementations, parameter types, return types, decorators/annotations.
**At C4, we do NOT focus on:** System boundaries (C1), container technologies (C2), component organization (C3), infrastructure configuration.
**Important Note (per C4 Model methodology):** The Code level is often skipped or auto-generated because:
- IDEs can generate this automatically
- UML class diagrams serve this purpose
- It's too detailed to maintain manually
- Code is the source of truth
Focus on **significant code elements** only - public APIs, complex functions, key classes.
---
## Detailed References
For comprehensive guidance on specific aspects of C4 code analysis, see:
- **[Code Element Identification](./code-element-identification.md)** - Element types, detection rules, significance criteria, naming conventions
- **[Signature Analysis](./signature-analysis.md)** - Parameter extraction, return types, generics, decorators
- **[Complexity Metrics](./complexity-metrics.md)** - Cyclomatic complexity, cognitive complexity, nesting depth, LOC
- **[Observation Guide](./observation-guide-c4.md)** - 10 observation categories, severity levels, evidence collection
- **[Relation Types](./relation-types-c4.md)** - calls, returns, imports, inherits, implements, and more
These references are loaded progressively when needed for detailed analysis.
---
## Code Element Identification Summary
A **code element** at C4 level is a discrete unit of code with clear purpose - such as a class definition, function declaration, interface contract, or type alias.
### Element Types
1. **class** - Object-oriented class definition
2. **function** - Standalone function (sync)
3. **async-function** - Async function returning Promise
4. **method** - Class or object method
5. **interface** - TypeScript/Java interface
6. **type** - Type alias or type definition
7. **constant** - Exported constant value
8. **variable** - Module-level variable
9. **enum** - Enumeration definition
10. **decorator** - Decorator/annotation definition
11. **generator** - Generator function
12. **module** - Module or namespace export
13. **namespace** - Namespace declaration
### Significance Criteria
Document a code element if **ANY** apply:
- Public API (exported from module)
- Lines of code > 20
- Cyclomatic complexity > 4
- Multiple callers or dependencies
- Implements design pattern
- Contains critical business logic
- Has security implications
- Is entry point or controller action
- Defines key data structure
**Key principles:** Focus on significant elements, preserve original naming, document public APIs thoroughly, calculate metrics for functions/methods.
For complete methodology, see [code-element-identification.md](./code-element-identification.md).
---
## Signature Analysis Summary
Extract signature information for functions, methods, and interfaces:
### Parameters
- Name (original case)
- Type (full type including generics)
- Optional flag
- Default value (if any)
### Return Type
- Full return type
- Promise type for async functions
- Void for procedures
### Modifiers
- async (true/false)
- generic_params (type parameters)
- visibility (public/private/protected)
For complete methodology, see [signature-analysis.md](./signature-analysis.md).
---
## Complexity Metrics Summary
Calculate and document these metrics:
1. **Lines of Code (LOC)** - Actual code lines excluding comments
2. **Cyclomatic Complexity** - Number of independent paths through code
3. **Cognitive Complexity** - Mental effort to understand code
4. **Parameter Count** - Number of function/method parameters
5. **Nesting Depth** - Maximum depth of nested structures
### Thresholds
| Metric | Good | Warning | Critical |
|--------|------|---------|----------|
| Cyclomatic | 1-6 | 7-10 | >10 |
| Cognitive | 0-10 | 11-20 | >20 |
| Parameters | 0-3 | 4-5 | >5 |
| Nesting | 0-3 | 4-5 | >5 |
| LOC | 1-30 | 31-50 | >50 |
For complete methodology, see [complexity-metrics.md](./complexity-metrics.md).
---
## Observation Categories
Document findings using these 10 categories:
1. **implementation** - Code patterns, algorithms, logic flow
2. **error-handling** - Exception handling, error propagation
3. **type-safety** - Type definitions, generics, type guards
4. **documentation** - JSDoc, docstrings, inline comments
5. **testing** - Test coverage, testability, mocking
6. **complexity** - Cyclomatic/cognitive complexity metrics
7. **performance** - Algorithm efficiency, memory, async patterns
8. **security** - Input validation, sanitization, auth
9. **concurrency** - Async/await, promises, race conditions
10. **patterns** - Design patterns, code patterns, anti-patterns
**Severity levels:**
- info (informational)
- ⚠️ warning (potential issue)
- 🔴 critical (requires immediate action)
For complete guide, see [observation-guide-c4.md](./observation-guide-c4.md).
---
## Relation Types
Document relationships between code elements:
### Code Flow Relations
- **calls** - Invokes another function/method
- **awaits** - Awaits an async function
- **returns** - Returns a specific type
- **throws** - Throws an exception type
### Structural Relations
- **inherits** - Extends another class
- **implements** - Implements an interface
- **declares** - Declares a type or interface
- **uses-type** - Uses a type in signature/body
### Data Relations
- **creates** - Instantiates a class
- **mutates** - Modifies state or data
- **reads** - Reads from data source
### Dependency Relations
- **imports** - Imports from module
- **depends-on** - General dependency
- **overrides** - Overrides parent method
For complete guide, see [relation-types-c4.md](./relation-types-c4.md).
---
## Integration with Melly Workflow
### When This Skill is Used
This skill is activated during **Phase 4: C4 Code Identification** (`/melly-c4-code`) for code element identification, signature analysis, metrics calculation, and pattern detection. Also used in **Phase 5: Documentation** (`/melly-doc-c4model`) for markdown generation.
### Input Expectations
Expects data from `c3-components.json` with component details including id, name, type, container_id, structure (path, language, files, exports).
### Output Format
Generates `c4-code.json` with metadata, code_elements array, and summary.
### Validation
Generated output must pass: Schema validation, timestamp ordering (c4 > c3), referential integrity (all component_ids exist), required fields, ID format (kebab-case).
Validation script:
```bash
python3 ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c4-code.py c4-code.json
```
---
## Step-by-Step Workflow
### Systematic Approach for c4-abstractor Agent
**Step 1: Load Input Data**
```bash
cat c3-components.json | jq '.components'
```
**Step 2: Analyze Each Component**
Navigate to component path, understand file structure, identify source files.
**Step 3: Identify Code Elements**
For each source file:
- Parse class definitions
- Extract function declarations
- Identify interfaces and types
- Find constants and enums
**Step 4: Extract Signatures**
For functions/methods:
- Parameter names and types
- Return type
- Async modifier
- Generic parameters
For classes:
- Parent class (extends)
- Implemented interfaces
- Decorators/annotations
- Abstract modifier
**Step 5: Calculate Metrics**
- Count lines of code
- Calculate cyclomatic complexity
- Measure cognitive complexity
- Determine nesting depth
**Step 6: Map Relationships**
- Find function calls
- Identify imports
- Track inheritance
- Document interface implementations
**Step 7: Generate Observations**
Document findings across 10 categories with evidence.
**Step 8: Validate Output**
Check element IDs, component references, timestamps, run validation script.
---
## Best Practices
### ✅ DO:
1. **Focus on significant elements** - Public APIs, complex functions, key classes
2. **Preserve original names** - Use original case in name field
3. **Use kebab-case IDs** - Convert PascalCase/camelCase to kebab-case for IDs
4. **Document signatures thoroughly** - Parameters, types, return values
5. **Calculate metrics** - LOC, complexity for all functions/methods
6. **Track inheritance** - Document extends and implements
7. **Note decorators** - Record applied decorators/annotations
8. **Provide evidence** - File paths, line numbers, code snippets
9. **Document relationships** - calls, imports, inherits, implements
10. **Validate output** - Always run validation script
### ❌ DON'T:
1. **Don't document every element** - Skip trivial getters/setters, private helpers
2. **Don't use file names as IDs** - Use meaningful descriptive IDs
3. **Don't skip signatures** - Always extract parameter and return types
4. **Don't ignore complexity** - High complexity deserves observations
5. **Don't miss inheritance** - Always document class hierarchies
6. **Don't skip validation** - Always validate generated JSON
7. **Don't forget async** - Mark async functions appropriately
8. **Don't miss generics** - Document type parameters
9. **Don't ignore decorators** - They indicate patterns and behaviors
10. **Don't mix abstraction levels** - Keep C4 focused on code, not components
---
## Quick Reference
### Element Types
class, function, async-function, method, interface, type, constant, variable, enum, decorator, generator, module, namespace
### Visibility Levels
public, private, protected, internal, unknown
### Observation Categories
implementation, error-handling, type-safety, documentation, testing, complexity, performance, security, concurrency, patterns
### Relation Types
calls, returns, imports, inherits, implements, declares, uses-type, depends-on, throws, awaits, creates, mutates, reads, overrides
### Complexity Thresholds
- Cyclomatic: 1-6 (good), 7-10 (warning), >10 (critical)
- Cognitive: 0-10 (good), 11-20 (warning), >20 (critical)
- Parameters: 0-3 (good), 4-5 (warning), >5 (critical)
---
## Summary
You now have comprehensive knowledge of C4 Model Level 4 (Code) methodology. When invoked:
1. **Load input data** from `c3-components.json`
2. **Analyze each component** to understand structure
3. **Identify code elements** (classes, functions, interfaces, types)
4. **Extract signatures** (parameters, return types, modifiers)
5. **Calculate metrics** (LOC, complexity, nesting)
6. **Map relationships** (calls, inherits, implements)
7. **Generate observations** with evidence
8. **Validate output** before finalizing
Remember: **C4 is about code implementation.** Focus on WHAT code elements exist, WHAT they do, and HOW they relate - at the most granular level. But be selective - only document significant elements.
---
**Skill Version**: 1.0.0
**Last Updated**: 2025-11-26
**Compatibility**: Melly 1.0.0+

View File

@@ -0,0 +1,343 @@
# Code Element Identification Methodology
This guide provides comprehensive methodology for identifying code elements at the C4 (Code) level of the C4 Model.
---
## Code Element Types
### 1. Classes
**Detection patterns:**
```typescript
// TypeScript/JavaScript
class ClassName { }
export class ClassName { }
abstract class ClassName { }
export default class ClassName { }
```
```python
# Python
class ClassName:
pass
class ClassName(ParentClass):
pass
class ClassName(ABC): # Abstract
pass
```
```java
// Java
public class ClassName { }
public abstract class ClassName { }
public final class ClassName { }
```
**ID format:** `{component}-{class-name}-class`
**Example:** `auth-service-user-manager-class`
---
### 2. Functions
**Detection patterns:**
```typescript
// TypeScript/JavaScript
function functionName() { }
export function functionName() { }
const functionName = () => { }
export const functionName = () => { }
export default function functionName() { }
```
```python
# Python
def function_name():
pass
```
```java
// Java - methods are always in classes
public static void functionName() { }
```
**ID format:** `{component}-{function-name}`
**Example:** `auth-service-validate-token`
---
### 3. Async Functions
**Detection patterns:**
```typescript
// TypeScript/JavaScript
async function functionName() { }
export async function functionName() { }
const functionName = async () => { }
```
```python
# Python
async def function_name():
pass
```
**ID format:** `{component}-{function-name}`
**Example:** `auth-service-authenticate`
---
### 4. Methods
**Detection patterns:**
```typescript
// TypeScript/JavaScript - inside class
class Example {
methodName() { }
async methodName() { }
private methodName() { }
static methodName() { }
get propertyName() { }
set propertyName(value) { }
}
```
```python
# Python
class Example:
def method_name(self):
pass
@classmethod
def class_method(cls):
pass
@staticmethod
def static_method():
pass
```
**ID format:** `{class-id}-{method-name}`
**Example:** `auth-service-class-get-user`
---
### 5. Interfaces
**Detection patterns:**
```typescript
// TypeScript
interface InterfaceName { }
export interface InterfaceName { }
interface InterfaceName extends OtherInterface { }
```
```java
// Java
public interface InterfaceName { }
public interface InterfaceName extends OtherInterface { }
```
**ID format:** `{component}-{interface-name}-interface`
**Example:** `auth-service-i-user-repository-interface`
---
### 6. Types
**Detection patterns:**
```typescript
// TypeScript
type TypeName = string | number;
export type TypeName = { field: string };
type TypeName<T> = T[];
type TypeName = Pick<OtherType, 'field'>;
```
**ID format:** `{component}-{type-name}-type`
**Example:** `auth-service-user-credentials-type`
---
### 7. Constants
**Detection patterns:**
```typescript
// TypeScript/JavaScript
const CONSTANT_NAME = 'value';
export const CONSTANT_NAME = 42;
export const CONFIG = { ... } as const;
```
```python
# Python
CONSTANT_NAME = 'value'
MAX_RETRIES = 3
```
```java
// Java
public static final String CONSTANT_NAME = "value";
public static final int MAX_RETRIES = 3;
```
**ID format:** `{component}-{constant-name}-const`
**Example:** `auth-service-max-login-attempts-const`
---
### 8. Enums
**Detection patterns:**
```typescript
// TypeScript
enum EnumName { A, B, C }
export enum EnumName { A = 'a', B = 'b' }
const enum EnumName { A, B, C }
```
```python
# Python
from enum import Enum
class EnumName(Enum):
A = 1
B = 2
```
```java
// Java
public enum EnumName { A, B, C }
```
**ID format:** `{component}-{enum-name}-enum`
**Example:** `auth-service-user-role-enum`
---
### 9. Decorators
**Detection patterns:**
```typescript
// TypeScript
function DecoratorName(target: any) { }
export function DecoratorName(): MethodDecorator { }
```
```python
# Python
def decorator_name(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
```
**ID format:** `{component}-{decorator-name}-decorator`
**Example:** `auth-service-authenticated-decorator`
---
## Significance Criteria
Only document a code element if **ANY** of these apply:
### Public API
- Exported from module
- Part of public interface
- Used by external callers
### Complexity
- Lines of code > 20
- Cyclomatic complexity > 4
- Cognitive complexity > 10
### Architecture
- Implements design pattern
- Key abstraction or facade
- Entry point or controller action
### Business Logic
- Contains critical business rules
- Handles sensitive data
- Has security implications
### Dependencies
- Multiple callers (> 2)
- Multiple dependencies (> 3)
- Central to component
---
## Detection Commands
```bash
# TypeScript - Find classes
grep -rn "^export class\|^class " src/ --include="*.ts"
# TypeScript - Find functions
grep -rn "^export function\|^export async function\|^export const.*=.*=>" src/ --include="*.ts"
# TypeScript - Find interfaces
grep -rn "^export interface\|^interface " src/ --include="*.ts"
# TypeScript - Find types
grep -rn "^export type\|^type " src/ --include="*.ts"
# TypeScript - Find enums
grep -rn "^export enum\|^enum " src/ --include="*.ts"
# Python - Find classes
grep -rn "^class " src/ --include="*.py"
# Python - Find functions
grep -rn "^def \|^async def " src/ --include="*.py"
# Count lines per file
wc -l src/**/*.ts | sort -n
```
---
## Naming Conventions
### ID Format
- Use kebab-case
- Include component prefix
- Include element type suffix where helpful
- Pattern: `{component-id}-{element-name}[-{type}]`
### Name Field
- Preserve original case (PascalCase, camelCase, snake_case)
- Use exact name from source code
### Examples
| Source Name | ID | name |
|------------|-----|------|
| `UserService` | `auth-user-service-class` | `UserService` |
| `authenticate` | `auth-authenticate` | `authenticate` |
| `IUserRepository` | `auth-i-user-repository-interface` | `IUserRepository` |
| `LoginCredentials` | `auth-login-credentials-type` | `LoginCredentials` |
| `MAX_RETRIES` | `auth-max-retries-const` | `MAX_RETRIES` |
| `UserRole` | `auth-user-role-enum` | `UserRole` |
---
## Best Practices
### ✅ DO:
- Focus on significant, public elements
- Use consistent ID naming
- Preserve original casing in name field
- Document all public API elements
- Include classes that define key abstractions
### ❌ DON'T:
- Document every private helper function
- Document trivial getters/setters
- Document test files as code elements
- Use file names as element IDs
- Skip exported functions/classes

View File

@@ -0,0 +1,364 @@
# Complexity Metrics Methodology
This guide provides methodology for calculating and documenting code complexity metrics at the C4 Code level.
---
## Metrics Overview
| Metric | Description | Threshold |
|--------|-------------|-----------|
| Lines of Code (LOC) | Actual code lines | Warning: >30, Critical: >50 |
| Cyclomatic Complexity | Decision paths | Warning: >6, Critical: >10 |
| Cognitive Complexity | Mental effort | Warning: >10, Critical: >20 |
| Parameter Count | Function parameters | Warning: >3, Critical: >5 |
| Nesting Depth | Max nesting level | Warning: >3, Critical: >5 |
---
## Lines of Code (LOC)
### Definition
Count of actual code lines excluding:
- Blank lines
- Comments
- Import statements (debatable)
### Calculation
```typescript
// Example function - LOC = 8
function processOrder(order: Order): ProcessedOrder {
const validated = validateOrder(order); // 1
if (!validated) { // 2
throw new Error('Invalid order'); // 3
} // 4
const enriched = enrichOrder(validated); // 5
const processed = applyRules(enriched); // 6
logOrder(processed); // 7
return processed; // 8
}
```
### Thresholds
| Range | Rating | Action |
|-------|--------|--------|
| 1-30 | Good | No action needed |
| 31-50 | Warning | Consider extracting methods |
| >50 | Critical | Must refactor |
---
## Cyclomatic Complexity
### Definition
Number of linearly independent paths through code. Calculated as:
- Start with 1
- Add 1 for each: `if`, `else if`, `case`, `for`, `while`, `do`, `catch`, `&&`, `||`, `?:`
### Calculation Example
```typescript
function processPayment(payment: Payment): Result { // CC = 1 (base)
if (payment.amount <= 0) { // CC = 2
return { error: 'Invalid amount' };
}
if (payment.type === 'credit') { // CC = 3
if (payment.amount > 10000) { // CC = 4
return { error: 'Amount exceeds limit' };
}
return processCreditCard(payment);
} else if (payment.type === 'debit') { // CC = 5
return processDebitCard(payment);
} else if (payment.type === 'crypto') { // CC = 6
return processCrypto(payment);
}
return { error: 'Unknown payment type' };
}
// Total Cyclomatic Complexity = 6
```
### Decision Points
| Construct | Adds |
|-----------|------|
| `if` | +1 |
| `else if` | +1 |
| `case` (switch) | +1 per case |
| `for` | +1 |
| `while` | +1 |
| `do...while` | +1 |
| `catch` | +1 |
| `&&` | +1 |
| `||` | +1 |
| `?:` (ternary) | +1 |
| `?.` (optional chain) | +1 |
| `??` (nullish coalesce) | +1 |
### Thresholds
| Range | Rating | Interpretation |
|-------|--------|----------------|
| 1-6 | Good | Simple, easy to test |
| 7-10 | Warning | Moderate complexity |
| 11-20 | High | Difficult to test |
| >20 | Critical | Untestable, must refactor |
---
## Cognitive Complexity
### Definition
A metric that measures the mental effort required to understand code. Unlike cyclomatic complexity, it:
- Penalizes nesting
- Ignores shorthand structures
- Focuses on readability
### Calculation Rules
1. **Increment for each:**
- `if`, `else if`, `else`
- `switch`
- `for`, `foreach`, `while`, `do`
- `catch`
- `break`/`continue` to label
- Sequences of logical operators
2. **Nesting penalty:**
- Add +1 for each level of nesting when incrementing
### Example
```typescript
function example(arr: number[], target: number): number {
// Base: 0
for (const item of arr) { // +1 (increment)
if (item === target) { // +2 (increment + 1 nesting)
return item;
} else if (item > target) { // +2 (increment + 1 nesting)
if (item % 2 === 0) { // +3 (increment + 2 nesting)
return item * 2;
}
}
}
return -1;
}
// Total Cognitive Complexity = 8
```
### Thresholds
| Range | Rating | Action |
|-------|--------|--------|
| 0-10 | Good | Understandable |
| 11-20 | Warning | Getting complex |
| >20 | Critical | Hard to understand |
---
## Parameter Count
### Definition
Number of parameters a function accepts.
### Guidelines
| Count | Rating | Recommendation |
|-------|--------|----------------|
| 0-3 | Good | Ideal range |
| 4-5 | Warning | Consider parameter object |
| >5 | Critical | Use parameter object |
### Refactoring Example
```typescript
// Before: 6 parameters (Critical)
function createUser(
name: string,
email: string,
age: number,
address: string,
phone: string,
role: string
) { }
// After: 1 parameter object (Good)
interface CreateUserInput {
name: string;
email: string;
age: number;
address: string;
phone: string;
role: string;
}
function createUser(input: CreateUserInput) { }
```
---
## Nesting Depth
### Definition
Maximum depth of nested control structures.
### Calculation
```typescript
function process(data: Data): Result {
if (data.valid) { // Depth 1
for (const item of data.items) { // Depth 2
if (item.active) { // Depth 3
try { // Depth 4
if (item.type === 'A') { // Depth 5 (Critical!)
// ...
}
} catch (e) {
// ...
}
}
}
}
return result;
}
// Maximum Nesting Depth = 5
```
### Thresholds
| Depth | Rating | Action |
|-------|--------|--------|
| 0-3 | Good | Easy to follow |
| 4-5 | Warning | Consider extracting |
| >5 | Critical | Must refactor |
### Refactoring Techniques
1. **Early returns (guard clauses)**
```typescript
// Before
function process(data) {
if (data) {
if (data.valid) {
// actual logic
}
}
}
// After
function process(data) {
if (!data) return;
if (!data.valid) return;
// actual logic
}
```
2. **Extract nested logic**
```typescript
// Before
for (const item of items) {
if (item.active) {
if (item.valid) {
// complex logic
}
}
}
// After
function processItem(item) {
if (!item.active || !item.valid) return;
// complex logic
}
for (const item of items) {
processItem(item);
}
```
---
## Metrics JSON Structure
```json
{
"metrics": {
"lines_of_code": 45,
"cyclomatic_complexity": 8,
"cognitive_complexity": 15,
"parameter_count": 3,
"nesting_depth": 4
}
}
```
---
## Threshold Summary Table
| Metric | Good | Warning | Critical |
|--------|------|---------|----------|
| LOC | 1-30 | 31-50 | >50 |
| Cyclomatic | 1-6 | 7-10 | >10 |
| Cognitive | 0-10 | 11-20 | >20 |
| Parameters | 0-3 | 4-5 | >5 |
| Nesting | 0-3 | 4-5 | >5 |
---
## Observation Examples
### High Complexity Warning
```json
{
"id": "obs-auth-service-complexity-01",
"category": "complexity",
"severity": "warning",
"description": "Cyclomatic complexity of 8 exceeds recommended threshold of 6. Consider extracting authentication steps into separate methods.",
"evidence": [
{
"location": "src/services/auth.ts:45-120",
"type": "metric"
}
],
"tags": ["complexity", "refactoring-candidate"]
}
```
### Critical Nesting
```json
{
"id": "obs-order-processor-nesting-01",
"category": "complexity",
"severity": "critical",
"description": "Maximum nesting depth of 6 makes code difficult to understand. Extract nested logic into helper functions.",
"evidence": [
{
"location": "src/services/order.ts:78-150",
"type": "code",
"snippet": "if (order.valid) { for (...) { if (...) { try { if (...) {"
}
],
"tags": ["nesting", "refactoring-required"]
}
```
---
## Best Practices
### ✅ DO:
- Calculate all five metrics for functions/methods
- Flag any metric exceeding warning threshold
- Provide specific refactoring suggestions
- Include evidence with line numbers
### ❌ DON'T:
- Skip metrics for simple functions
- Ignore nesting depth
- Accept critical thresholds without observation
- Forget to suggest refactoring approaches

View File

@@ -0,0 +1,317 @@
# Observation Guide for C4 Code Elements
This guide provides comprehensive methodology for documenting observations at the C4 Code level.
---
## Observation Categories
### 1. **implementation**
Code implementation patterns, algorithms, logic flow
**Examples:**
- "Uses async/await pattern for non-blocking database operations"
- "Implements retry logic with exponential backoff"
- "Uses memoization to cache expensive calculations"
- "Implements pagination with cursor-based navigation"
- "Uses builder pattern for complex object construction"
**Evidence types:** code, pattern
---
### 2. **error-handling**
Exception handling, error propagation, recovery mechanisms
**Examples:**
- "Generic catch block masks specific error types - consider typed error handling"
- "Custom error classes with proper error codes and stack traces"
- "Missing error handling for null/undefined cases"
- "Proper error boundary implementation with fallback UI"
- "Silently catches and ignores errors - may hide bugs"
**Evidence types:** code, pattern
---
### 3. **type-safety**
Type definitions, generics, type guards, null safety
**Examples:**
- "Uses strict null checks with proper type guards"
- "Generic function with proper type constraints"
- "Missing type annotation on public API - should be explicit"
- "Type narrowing with discriminated unions for safe handling"
- "Uses `any` type extensively - reduces type safety benefits"
**Evidence types:** code, pattern
---
### 4. **documentation**
JSDoc, docstrings, inline comments, API documentation
**Examples:**
- "Comprehensive JSDoc with @param, @returns, and @example"
- "Missing documentation for complex algorithm - add explanatory comments"
- "Inline comments explain business logic decisions"
- "API endpoint documentation includes request/response examples"
- "Outdated comments don't match current implementation"
**Evidence types:** documentation, code
---
### 5. **testing**
Test coverage, testability, mocking concerns
**Examples:**
- "90% test coverage with edge cases covered"
- "Hard to test due to static dependencies - consider dependency injection"
- "Proper use of dependency injection improves testability"
- "Missing tests for error paths and edge cases"
- "Test file exists but only covers happy path"
**Evidence types:** test, code
---
### 6. **complexity**
Cyclomatic complexity, cognitive complexity, nesting depth
**Examples:**
- "Cyclomatic complexity of 15 exceeds threshold (6) - extract methods"
- "Deep nesting (5 levels) reduces readability - use guard clauses"
- "Function has 8 parameters - consider parameter object pattern"
- "Method is 150 LOC - split into smaller focused functions"
- "Single method handles multiple responsibilities - violates SRP"
**Evidence types:** metric, code
---
### 7. **performance**
Algorithm efficiency, memory usage, async patterns
**Examples:**
- "O(n²) algorithm could be optimized to O(n log n)"
- "Memory leak: event listener not removed on cleanup"
- "Unnecessary database queries in loop - use batch query"
- "Proper use of lazy loading for large data sets"
- "Missing debounce on rapid event handler"
**Evidence types:** code, metric, pattern
---
### 8. **security**
Input validation, sanitization, authentication, authorization
**Examples:**
- "Missing input validation on user-provided data"
- "SQL query properly parameterized against injection"
- "Password stored with bcrypt hashing (cost factor 12)"
- "Sensitive data logged in debug output - security risk"
- "Authorization check missing before data access"
**Evidence types:** code, pattern
---
### 9. **concurrency**
Async/await, promises, race conditions, thread safety
**Examples:**
- "Potential race condition in concurrent state updates"
- "Proper use of Promise.all for parallel independent requests"
- "Missing await on async function call - returns Promise instead of value"
- "Deadlock potential with multiple lock acquisitions"
- "Uses mutex pattern for thread-safe resource access"
**Evidence types:** code, pattern
---
### 10. **patterns**
Design patterns, code patterns, anti-patterns
**Examples:**
- "Factory pattern used for creating validator instances"
- "God object anti-pattern - class has too many responsibilities"
- "Proper use of strategy pattern for payment processing"
- "Singleton pattern ensures single database connection pool"
- "Repository pattern cleanly separates data access concerns"
**Evidence types:** pattern, code
---
## Observation Structure
```json
{
"id": "obs-{element-id}-{category}-{number}",
"category": "implementation|error-handling|type-safety|documentation|testing|complexity|performance|security|concurrency|patterns",
"severity": "info|warning|critical",
"description": "Clear, actionable description of the observation",
"evidence": [
{
"location": "src/path/to/file.ts:45-67",
"type": "code|metric|pattern|test|documentation",
"snippet": "Optional relevant code snippet"
}
],
"tags": ["relevant", "searchable", "tags"]
}
```
---
## Severity Guidelines
### info
Use for:
- Best practices being followed
- Interesting implementation details
- Documentation notes
- Positive observations
**Examples:**
- "Uses dependency injection for loose coupling"
- "Well-documented API with comprehensive JSDoc"
- "Implements singleton pattern correctly"
---
### ⚠️ warning
Use for:
- Potential issues that should be addressed
- Technical debt
- Performance concerns
- Missing tests
- Minor security considerations
**Examples:**
- "Cyclomatic complexity exceeds threshold"
- "Missing input validation on internal API"
- "No tests for edge cases"
- "Consider using more specific error types"
---
### 🔴 critical
Use for:
- Security vulnerabilities
- Breaking bugs
- Data loss potential
- Production-impacting issues
- Immediate action required
**Examples:**
- "SQL injection vulnerability - user input not sanitized"
- "Unhandled promise rejection crashes application"
- "Sensitive data exposed in logs"
- "Race condition causes data corruption"
---
## Evidence Types
| Type | Description | Example |
|------|-------------|---------|
| `code` | Code snippet or reference | `"snippet": "if (user.role === 'admin')"` |
| `metric` | Calculated metric value | Complexity score, LOC count |
| `pattern` | Design pattern identification | Factory, Singleton, Repository |
| `test` | Test file or coverage info | Test file location |
| `documentation` | Doc reference | JSDoc, README section |
---
## Complete Example
```json
{
"observations": [
{
"id": "obs-auth-service-security-01",
"category": "security",
"severity": "critical",
"description": "Password comparison uses timing-vulnerable equality check. Use constant-time comparison to prevent timing attacks.",
"evidence": [
{
"location": "src/services/auth.ts:78",
"type": "code",
"snippet": "if (password === storedPassword)"
}
],
"tags": ["security", "timing-attack", "authentication"]
},
{
"id": "obs-auth-service-patterns-01",
"category": "patterns",
"severity": "info",
"description": "Implements repository pattern for data access, providing clean separation between business logic and persistence.",
"evidence": [
{
"location": "src/services/auth.ts:15-20",
"type": "pattern"
}
],
"tags": ["repository-pattern", "clean-architecture"]
},
{
"id": "obs-auth-service-complexity-01",
"category": "complexity",
"severity": "warning",
"description": "Authenticate method has cyclomatic complexity of 12, exceeding recommended threshold of 6. Consider extracting validation and token generation into separate methods.",
"evidence": [
{
"location": "src/services/auth.ts:45-120",
"type": "metric"
}
],
"tags": ["complexity", "refactoring-candidate"]
}
]
}
```
---
## Writing Good Observations
### ✅ DO:
- Be specific and actionable
- Include exact file paths and line numbers
- Provide code snippets for context
- Use appropriate severity levels
- Include relevant tags for searchability
- Suggest fixes for warnings/critical issues
### ❌ DON'T:
- Be vague ("code is complex")
- Skip evidence
- Overuse critical severity
- Write observations without actionable insight
- Forget to tag important categories
- Mix multiple issues in one observation
---
## Tags Reference
Common useful tags:
**Architecture:** `clean-architecture`, `hexagonal`, `layered`, `microservices`
**Patterns:** `singleton`, `factory`, `repository`, `strategy`, `observer`, `decorator`
**Anti-patterns:** `god-object`, `spaghetti-code`, `magic-numbers`, `primitive-obsession`
**Quality:** `refactoring-candidate`, `technical-debt`, `needs-review`
**Security:** `input-validation`, `authentication`, `authorization`, `sql-injection`, `xss`
**Performance:** `n-plus-one`, `memory-leak`, `optimization-candidate`
**Testing:** `needs-tests`, `integration-test`, `unit-test`, `edge-cases`

View File

@@ -0,0 +1,442 @@
# Relation Types for C4 Code Elements
This guide provides comprehensive documentation of relationship types between code elements at the C4 Code level.
---
## Overview
Relations describe how code elements interact with each other. Each relation has:
- **target**: The code element being related to
- **type**: The nature of the relationship
- **description**: Active voice description of the relationship
---
## Code Flow Relations
### calls
**Definition:** Invokes another function or method
**When to use:** When a function/method directly calls another
**Examples:**
```typescript
function processOrder(order: Order) {
validateOrder(order); // calls validateOrder
calculateTotal(order); // calls calculateTotal
}
```
**JSON:**
```json
{
"target": "validate-order",
"type": "calls",
"description": "Calls validateOrder to validate order structure"
}
```
---
### awaits
**Definition:** Awaits an async function
**When to use:** When async function awaits another async function
**Examples:**
```typescript
async function getUser(id: string) {
const user = await userRepository.findById(id); // awaits findById
return user;
}
```
**JSON:**
```json
{
"target": "user-repository-find-by-id",
"type": "awaits",
"description": "Awaits UserRepository.findById for user lookup"
}
```
---
### returns
**Definition:** Returns a specific type
**When to use:** When documenting what type a function returns
**Examples:**
```typescript
function createUser(data: UserInput): User {
return new User(data); // returns User
}
```
**JSON:**
```json
{
"target": "user-class",
"type": "returns",
"description": "Returns User instance with provided data"
}
```
---
### throws
**Definition:** Throws an exception type
**When to use:** When function explicitly throws an exception
**Examples:**
```typescript
function validateAge(age: number) {
if (age < 0) {
throw new ValidationError('Age cannot be negative'); // throws ValidationError
}
}
```
**JSON:**
```json
{
"target": "validation-error-class",
"type": "throws",
"description": "Throws ValidationError when age is negative"
}
```
---
## Structural Relations
### inherits
**Definition:** Extends another class
**When to use:** When a class extends a parent class
**Examples:**
```typescript
class AdminUser extends User { // inherits from User
permissions: string[];
}
```
**JSON:**
```json
{
"target": "user-class",
"type": "inherits",
"description": "Inherits from User base class"
}
```
---
### implements
**Definition:** Implements an interface
**When to use:** When a class implements an interface contract
**Examples:**
```typescript
class UserService implements IUserService { // implements IUserService
getUser(id: string): User { ... }
}
```
**JSON:**
```json
{
"target": "i-user-service-interface",
"type": "implements",
"description": "Implements IUserService interface contract"
}
```
---
### declares
**Definition:** Declares a type or interface
**When to use:** When defining the shape of data used elsewhere
**Examples:**
```typescript
interface UserInput { // declares shape for createUser
name: string;
email: string;
}
function createUser(input: UserInput) { ... }
```
**JSON:**
```json
{
"target": "create-user-function",
"type": "declares",
"description": "Declares the input shape for createUser function"
}
```
---
### uses-type
**Definition:** Uses a type in signature or body
**When to use:** When function uses a type for parameters, return, or internally
**Examples:**
```typescript
function processPayment(payment: Payment): PaymentResult {
// Uses Payment type for input
// Uses PaymentResult type for output
}
```
**JSON:**
```json
{
"target": "payment-type",
"type": "uses-type",
"description": "Uses Payment type for input parameter"
}
```
---
## Data Relations
### creates
**Definition:** Instantiates a class
**When to use:** When function creates new instance of a class
**Examples:**
```typescript
function createOrder(items: Item[]): Order {
return new Order(items); // creates Order instance
}
```
**JSON:**
```json
{
"target": "order-class",
"type": "creates",
"description": "Creates new Order instance with provided items"
}
```
---
### mutates
**Definition:** Modifies state or data
**When to use:** When function modifies object state
**Examples:**
```typescript
function updateUser(user: User, data: Partial<User>) {
Object.assign(user, data); // mutates user object
}
```
**JSON:**
```json
{
"target": "user-class",
"type": "mutates",
"description": "Mutates User instance with provided data"
}
```
---
### reads
**Definition:** Reads from data source
**When to use:** When function reads data without modifying
**Examples:**
```typescript
function getUserName(user: User): string {
return user.name; // reads from User
}
```
**JSON:**
```json
{
"target": "user-class",
"type": "reads",
"description": "Reads name property from User instance"
}
```
---
## Dependency Relations
### imports
**Definition:** Imports from another module
**When to use:** When code imports from another file/module
**Examples:**
```typescript
import { UserService } from './services/user'; // imports UserService
```
**JSON:**
```json
{
"target": "user-service-class",
"type": "imports",
"description": "Imports UserService from services module"
}
```
---
### depends-on
**Definition:** General dependency relationship
**When to use:** When there's a dependency that doesn't fit other categories
**Examples:**
```typescript
class OrderService {
constructor(
private userService: UserService, // depends-on UserService
private paymentService: PaymentService // depends-on PaymentService
) {}
}
```
**JSON:**
```json
{
"target": "user-service-class",
"type": "depends-on",
"description": "Depends on UserService for user operations"
}
```
---
### overrides
**Definition:** Overrides parent class method
**When to use:** When method overrides a parent method
**Examples:**
```typescript
class AdminUser extends User {
override toString(): string { // overrides User.toString
return `Admin: ${this.name}`;
}
}
```
**JSON:**
```json
{
"target": "user-class-to-string",
"type": "overrides",
"description": "Overrides User.toString to include admin prefix"
}
```
---
## Relation Type Summary
| Type | Category | Description |
|------|----------|-------------|
| `calls` | Code Flow | Invokes function/method |
| `awaits` | Code Flow | Awaits async function |
| `returns` | Code Flow | Returns specific type |
| `throws` | Code Flow | Throws exception |
| `inherits` | Structural | Extends class |
| `implements` | Structural | Implements interface |
| `declares` | Structural | Declares type/interface |
| `uses-type` | Structural | Uses type in signature |
| `creates` | Data | Instantiates class |
| `mutates` | Data | Modifies state |
| `reads` | Data | Reads data |
| `imports` | Dependency | Imports from module |
| `depends-on` | Dependency | General dependency |
| `overrides` | Dependency | Overrides parent method |
---
## Complete Example
```json
{
"relations": [
{
"target": "base-service-class",
"type": "inherits",
"description": "Inherits common service functionality from BaseService"
},
{
"target": "i-user-service-interface",
"type": "implements",
"description": "Implements IUserService interface contract"
},
{
"target": "user-repository",
"type": "depends-on",
"description": "Depends on UserRepository for data persistence"
},
{
"target": "user-repository-find-by-id",
"type": "awaits",
"description": "Awaits UserRepository.findById for user lookup"
},
{
"target": "user-class",
"type": "returns",
"description": "Returns User instance to caller"
},
{
"target": "user-not-found-error",
"type": "throws",
"description": "Throws UserNotFoundError when user doesn't exist"
}
]
}
```
---
## Best Practices
### ✅ DO:
- Use active voice in descriptions
- Be specific about what is being called/used
- Document all significant relationships
- Use the most specific relation type
### ❌ DON'T:
- Use passive voice ("is called by")
- Skip obvious but important relations
- Use generic descriptions
- Mix relation types inappropriately
---
## Relation Direction
All relations are **outbound** from the source element:
- Source element → **calls** → Target element
- Source element → **inherits** → Target element
- Source element → **depends-on** → Target element
Do NOT document reverse relations (e.g., "is called by"). The target element's incoming relations can be derived from the source elements' outbound relations.

View File

@@ -0,0 +1,314 @@
# Signature Analysis Methodology
This guide provides methodology for extracting and documenting function, method, and interface signatures at the C4 Code level.
---
## Parameter Extraction
### Required Information
For each parameter, extract:
| Field | Description | Example |
|-------|-------------|---------|
| `name` | Parameter name (original case) | `userId`, `options` |
| `type` | Full type including generics | `string`, `UserOptions<T>` |
| `optional` | Whether parameter is optional | `true`, `false` |
| `default` | Default value if any | `{}`, `null`, `10` |
### TypeScript Examples
```typescript
// Required parameter
function getUser(userId: string) { }
// → { name: "userId", type: "string", optional: false }
// Optional parameter
function getUser(userId: string, includeDeleted?: boolean) { }
// → { name: "includeDeleted", type: "boolean", optional: true }
// Default parameter
function getUsers(limit: number = 10) { }
// → { name: "limit", type: "number", optional: true, default: "10" }
// Generic parameter
function transform<T>(input: T[]): T { }
// → { name: "input", type: "T[]", optional: false }
// Object destructuring
function create({ name, age }: UserInput) { }
// → { name: "{ name, age }", type: "UserInput", optional: false }
// Rest parameters
function concat(...items: string[]) { }
// → { name: "...items", type: "string[]", optional: false }
```
### Python Examples
```python
# Required parameter
def get_user(user_id: str) -> User:
# → { name: "user_id", type: "str", optional: false }
# Optional parameter (with default)
def get_users(limit: int = 10) -> List[User]:
# → { name: "limit", type: "int", optional: true, default: "10" }
# Optional type hint
def find_user(user_id: Optional[str]) -> Optional[User]:
# → { name: "user_id", type: "Optional[str]", optional: false }
# *args and **kwargs
def call_api(*args, **kwargs):
# → { name: "*args", type: "Any", optional: true }
# → { name: "**kwargs", type: "Any", optional: true }
```
---
## Return Type Analysis
### TypeScript Return Types
```typescript
// Simple return
function getName(): string { }
// → return_type: "string"
// Promise return (async)
async function getUser(): Promise<User> { }
// → return_type: "Promise<User>", async: true
// Void return
function logMessage(msg: string): void { }
// → return_type: "void"
// Union return
function find(): User | null { }
// → return_type: "User | null"
// Generic return
function first<T>(arr: T[]): T | undefined { }
// → return_type: "T | undefined"
// No explicit return (inferred)
function calculate() { return 42; }
// → return_type: "number" (inferred)
```
### Python Return Types
```python
# Simple return
def get_name() -> str:
# → return_type: "str"
# Optional return
def find_user() -> Optional[User]:
# → return_type: "Optional[User]"
# Async return
async def get_user() -> User:
# → return_type: "User", async: true
# No return type (None)
def log_message(msg: str) -> None:
# → return_type: "None"
```
---
## Async Detection
### Patterns to Detect
| Language | Pattern | Example |
|----------|---------|---------|
| TypeScript | `async` keyword | `async function fetchData()` |
| TypeScript | Returns `Promise<T>` | `function fetch(): Promise<Data>` |
| Python | `async def` | `async def fetch_data():` |
| Java | Returns `CompletableFuture<T>` | `CompletableFuture<Data> fetchData()` |
### Examples
```typescript
// Explicit async
async function fetchUser(id: string): Promise<User> { }
// → async: true, return_type: "Promise<User>"
// Returns Promise but not async keyword
function fetchUser(id: string): Promise<User> {
return fetch(`/users/${id}`).then(r => r.json());
}
// → async: false, return_type: "Promise<User>"
```
---
## Generic Type Parameters
### Extracting Generics
```typescript
// Single generic
function identity<T>(value: T): T { }
// → generic_params: ["T"]
// Multiple generics
function map<T, U>(arr: T[], fn: (item: T) => U): U[] { }
// → generic_params: ["T", "U"]
// Constrained generic
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { }
// → generic_params: ["T", "K extends keyof T"]
// Default generic
function createArray<T = string>(length: number): T[] { }
// → generic_params: ["T = string"]
```
### Python Generics
```python
from typing import TypeVar, Generic
T = TypeVar('T')
def identity(value: T) -> T:
return value
# → generic_params: ["T"]
class Container(Generic[T]):
def get(self) -> T: ...
# → generic_params: ["T"]
```
---
## Decorator Extraction
### TypeScript/JavaScript Decorators
```typescript
@Injectable()
@Singleton()
class UserService { }
// → decorators: ["@Injectable()", "@Singleton()"]
@Get('/users/:id')
@UseGuards(AuthGuard)
async getUser(@Param('id') id: string) { }
// → decorators: ["@Get('/users/:id')", "@UseGuards(AuthGuard)"]
```
### Python Decorators
```python
@classmethod
def from_dict(cls, data: dict) -> 'User':
# → decorators: ["@classmethod"]
@staticmethod
def validate(data: dict) -> bool:
# → decorators: ["@staticmethod"]
@property
def full_name(self) -> str:
# → decorators: ["@property"]
@app.route('/users/<id>')
@require_auth
def get_user(id: str):
# → decorators: ["@app.route('/users/<id>')", "@require_auth"]
```
### Java Annotations
```java
@Override
public String toString() { }
// → decorators: ["@Override"]
@GetMapping("/users/{id}")
@PreAuthorize("hasRole('USER')")
public User getUser(@PathVariable String id) { }
// → decorators: ["@GetMapping(\"/users/{id}\")", "@PreAuthorize(\"hasRole('USER')\")"]
```
---
## Visibility Modifiers
### TypeScript/JavaScript
| Modifier | Visibility |
|----------|------------|
| `public` | public |
| `private` | private |
| `protected` | protected |
| `#field` (private field) | private |
| (no modifier) | public |
### Python
| Pattern | Visibility |
|---------|------------|
| `_method` | internal (convention) |
| `__method` | private (name mangling) |
| (no prefix) | public |
### Java
| Modifier | Visibility |
|----------|------------|
| `public` | public |
| `private` | private |
| `protected` | protected |
| (package-private) | internal |
---
## Complete Signature Example
```json
{
"signature": {
"parameters": [
{
"name": "userId",
"type": "string",
"optional": false
},
{
"name": "options",
"type": "GetUserOptions",
"optional": true,
"default": "{}"
}
],
"return_type": "Promise<User>",
"async": true,
"generic_params": []
}
}
```
---
## Best Practices
### ✅ DO:
- Extract full type information including generics
- Note optional parameters and defaults
- Identify async functions correctly
- Preserve exact decorator syntax
- Document visibility modifiers
### ❌ DON'T:
- Skip type information
- Ignore generic parameters
- Miss async/Promise patterns
- Forget decorators that indicate behavior
- Assume visibility without checking

View File

@@ -0,0 +1,214 @@
---
name: c4model-observations
description: Use when documenting observations, architectural findings, or discoveries across C4 Model levels (C1, C2, C3). Triggers include "observations", "findings", "document architecture", "security concerns", "performance issues", "quality attributes". Creates structured observations for c1-systems.json, c2-containers.json, and c3-components.json files with evidence, severity levels, and recommendations.
---
# C4 Model - Observation Documentation Methodology
## Overview
This skill provides methodology for identifying, categorizing, and documenting architectural observations across all C4 Model levels (C1, C2, C3).
**Mission:** Document WHAT you observe about systems, containers, and components—factual findings that inform architectural understanding.
---
## When to Use
- Documenting architectural findings during code analysis
- Categorizing security, performance, or quality issues
- Creating structured observations for C4 model documentation
- Recording evidence with file paths and code snippets
## When NOT to Use
- Writing C4 diagrams themselves (use c4model-c1/c2/c3)
- Documenting relationships between entities (use c4model-relations)
- General code documentation without architectural significance
---
## What is an Observation?
An **observation** is a factual finding about an entity that describes:
- Architectural characteristics, patterns, and decisions
- Technical details, technologies, frameworks
- Quality attributes like performance, scalability, maintainability
- Security concerns and vulnerabilities
- Design decisions and their rationale
- Performance patterns and bottlenecks
**Observations are facts, not opinions.** Document what you see in the code, configuration, and architecture.
---
## Observation Structure
### Required Fields
```json
{
"id": "obs-unique-identifier",
"category": "architecture|technology|security|...",
"severity": "critical|warning|info",
"title": "Short descriptive title (max 100 chars)",
"description": "Detailed description of what was observed"
}
```
### Optional Fields (Recommended)
```json
{
"evidence": [
{
"type": "file|code|config|pattern|metric|dependency",
"location": "path/to/file.js:45-52",
"snippet": "code excerpt or config value",
"note": "additional context"
}
],
"tags": ["searchable", "keywords"],
"impact": "What this means for the system",
"recommendation": "Suggested action (for warnings/critical)"
}
```
---
## Severity Levels
**Critical** - Immediate attention required:
- Security vulnerabilities, data loss risks, system unavailability
**Warning** - Should be addressed:
- Performance bottlenecks, code quality issues, anti-patterns
**Info** - Informational or positive findings:
- Design patterns, technology stack, good practices
---
## Evidence Types
| Type | Usage | Example |
|------|-------|---------|
| `file` | File paths, directory structure | `package.json` |
| `code` | Code snippets | `localStorage.setItem('token', jwt)` |
| `config` | Configuration values | `DATABASE_URL=...` |
| `pattern` | Architectural patterns | `Repository pattern` |
| `metric` | Measurements | `Complexity: 45` |
| `dependency` | Package dependencies | `"express": "^4.18.0"` |
---
## Categories by Level
| Level | Categories |
|-------|------------|
| **C1** | `architecture`, `integration`, `boundaries`, `security`, `scalability`, `actors`, `external-dependencies`, `deployment`, `data-flow` |
| **C2** | `technology`, `runtime`, `communication`, `data-storage`, `authentication`, `deployment`, `scalability`, `performance`, `dependencies`, `configuration`, `monitoring`, `security` |
| **C3** | `design-patterns`, `code-structure`, `dependencies`, `error-handling`, `testing`, `performance`, `security`, `code-quality`, `documentation`, `complexity`, `coupling`, `cohesion`, `maintainability` |
See [categories.md](categories.md) for detailed definitions.
---
## Quick Examples
**C3 Component (Critical):**
```json
{
"id": "obs-jwt-localstorage",
"category": "security",
"severity": "critical",
"title": "JWT tokens stored in localStorage",
"description": "Tokens in localStorage are vulnerable to XSS attacks.",
"evidence": [
{"type": "code", "location": "src/auth/storage.ts:45", "snippet": "localStorage.setItem('token', jwt)"}
],
"recommendation": "Use httpOnly cookies for token storage"
}
```
**C2 Container (Warning):**
```json
{
"id": "obs-no-connection-pool",
"category": "performance",
"severity": "warning",
"title": "Database connections not pooled",
"description": "New connection created for each request, causing overhead.",
"evidence": [
{"type": "code", "location": "src/db/connection.ts:12", "snippet": "new Client(config)"}
],
"recommendation": "Implement connection pooling with pg-pool"
}
```
**C1 System Context (Info):**
```json
{
"id": "obs-event-driven-arch",
"category": "architecture",
"severity": "info",
"title": "Event-driven architecture with message queues",
"description": "System uses RabbitMQ for async processing, enabling loose coupling.",
"evidence": [
{"type": "config", "location": "docker-compose.yml", "snippet": "rabbitmq:..."}
],
"impact": "Enables horizontal scaling and resilience"
}
```
See [examples.md](examples.md) for 30+ complete examples across all levels.
---
## Best Practices
1. **Be specific** - Detailed descriptions with concrete evidence
2. **Choose correct severity** - Critical for security/data issues, warning for should-fix, info for neutral
3. **Provide evidence** - Always include file paths and code snippets
4. **Use proper categories** - Match category to C4 level (C1/C2/C3)
5. **Add impact and recommendations** - For warnings and critical issues
6. **Include tags** - Aid searchability and cross-referencing
---
## Detailed Reference
For comprehensive methodology:
- **[reference.md](reference.md)** - Category definitions, evidence guidelines, best practices
- **[examples.md](examples.md)** - 30+ examples across C1, C2, C3 levels
- **[categories.md](categories.md)** - Complete category reference by level
---
## Common Mistakes
1. **Opinion instead of fact** - Document observations, not judgments ("poorly designed" vs "tight coupling between modules")
2. **Vague descriptions** - Be specific with file paths and evidence
3. **Wrong severity** - Critical for security/data loss, warning for should-fix, info for neutral findings
4. **Wrong category level** - Use C1 categories at C1 level, C3 at C3 level
---
## Integration
Observations are used by:
- **Abstractor agents** (c1/c2/c3) - Generate observations during analysis
- **c4model-writer** - Convert observations to markdown docs
- **Validation scripts** - Validate structure and content
- **basic-memory MCP** - Search and retrieve observations
---
## Related Skills
- **c4model-c1** - C1 System Context methodology
- **c4model-c2** - C2 Container methodology
- **c4model-c3** - C3 Component methodology
- **c4model-relations** - Relationship documentation methodology

View File

@@ -0,0 +1,513 @@
# Observation Categories Reference
**Quick reference guide for observation categories across C1, C2, and C3 levels.**
---
## Table of Contents
1. [C1 System Context Categories](#c1-system-context-categories)
2. [C2 Container Categories](#c2-container-categories)
3. [C3 Component Categories](#c3-component-categories)
4. [Category Selection Guide](#category-selection-guide)
---
## C1 System Context Categories
**Focus:** System-level architecture, external integrations, and high-level concerns.
### architecture
**Use for:** Overall system patterns, architectural styles, strategic decisions
**Examples:**
- Event-driven architecture with message queues
- Microservices architecture with API gateway
- Monolithic layered architecture
- CQRS pattern implementation
---
### integration
**Use for:** How systems communicate and integrate with each other
**Examples:**
- REST API communication over HTTPS
- GraphQL gateway for unified access
- Event-driven integration via message queues
- Service mesh for inter-service communication
---
### boundaries
**Use for:** System scope, ownership, organizational limits
**Examples:**
- System boundary includes web app and API
- Frontend team owns UI, backend team owns API
- Deployment boundary per service
- Network boundary: public vs private subnets
---
### security
**Use for:** System-level security, authentication, authorization
**Examples:**
- OAuth2 authentication via Auth0
- JWT-based authentication
- No rate limiting on public endpoints
- TLS encryption for all communications
---
### scalability
**Use for:** System's ability to scale and handle growth
**Examples:**
- Horizontally scalable via Kubernetes
- Auto-scaling based on CPU metrics
- Database sharding for horizontal scaling
- Stateless design enables cloud scaling
---
### actors
**Use for:** User types, roles, external actors
**Examples:**
- Three user roles: Customer, Admin, Support
- External audit system queries via API
- Mobile app acts as user of REST API
- Third-party integrations as system actors
---
### external-dependencies
**Use for:** Third-party systems, critical external services
**Examples:**
- Stripe payment gateway (critical)
- SendGrid email service with AWS SES fallback
- Auth0 for authentication (no fallback)
- Snowflake data warehouse for analytics
---
### deployment
**Use for:** Infrastructure, hosting, deployment strategies
**Examples:**
- AWS ECS Fargate deployment
- Kubernetes with blue-green deployments
- Multi-region active-active setup
- Infrastructure as code with Terraform
---
### data-flow
**Use for:** How data moves between systems
**Examples:**
- User data flows: web → API → database
- Analytics pipeline: app → Kafka → warehouse
- Batch ETL nightly to data lake
- Real-time streaming to analytics platform
---
## C2 Container Categories
**Focus:** Deployable units, runtime characteristics, technology stack.
### technology
**Use for:** Tech stack, frameworks, libraries, languages
**Examples:**
- React 18 SPA with Redux Toolkit
- Node.js 18 with Express.js
- Python FastAPI with SQLAlchemy
- .NET 7 with Entity Framework Core
---
### runtime
**Use for:** Runtime environment and characteristics
**Examples:**
- Node.js event loop (single-threaded)
- JVM with 4GB heap configuration
- Python 3.11 with uvicorn ASGI server
- Requires 16 environment variables
---
### communication
**Use for:** Inter-container protocols and patterns
**Examples:**
- REST API with JSON payloads
- gRPC with Protobuf serialization
- WebSocket for real-time updates
- Message queue for async communication
---
### data-storage
**Use for:** Databases, caches, storage mechanisms
**Examples:**
- PostgreSQL 14 for relational data
- Redis for session and caching
- MongoDB for document storage
- S3 for file storage
---
### authentication
**Use for:** Container-level auth and authorization
**Examples:**
- JWT bearer token authentication
- Session cookies with Redis storage
- API key for service-to-service auth
- OAuth2 client credentials flow
---
### deployment
**Use for:** Containerization, orchestration, deployment
**Examples:**
- Docker container on Kubernetes
- Health check at /health endpoint
- Blue-green deployment via ArgoCD
- Auto-scaling 2-10 replicas
---
### scalability
**Use for:** Container scaling capabilities
**Examples:**
- Horizontal pod autoscaling based on CPU
- Stateless design enables replication
- Limited by database connection pool
- Scales independently of other services
---
### performance
**Use for:** Container performance characteristics
**Examples:**
- Average response time: 50ms
- Code splitting and lazy loading
- Caching strategy reduces DB load
- No query optimization with indexes
---
### dependencies
**Use for:** Container dependencies on others
**Examples:**
- Depends on API container and Redis
- Critical dependency on PostgreSQL
- Loose coupling via message queue
- No direct database dependencies
---
### configuration
**Use for:** Configuration management approaches
**Examples:**
- Environment variables for config
- Kubernetes ConfigMaps and Secrets
- Feature flags in LaunchDarkly
- Config validation on startup
---
### monitoring
**Use for:** Observability, logging, monitoring
**Examples:**
- Winston logger with JSON format
- Prometheus metrics at /metrics
- OpenTelemetry distributed tracing
- No structured logging implemented
---
### security
**Use for:** Container-level security implementation
**Examples:**
- Container runs as non-root user
- Security scanning with Trivy
- Secrets injected via Kubernetes
- HTTPS only, no HTTP allowed
---
## C3 Component Categories
**Focus:** Code-level implementation, patterns, quality.
### design-patterns
**Use for:** Design patterns in code
**Examples:**
- Repository pattern for data access
- Factory pattern for service creation
- Singleton pattern for configuration
- Observer pattern for event handling
---
### code-structure
**Use for:** Code organization and modularity
**Examples:**
- Feature-based directory structure
- Layered architecture: controllers/services/repositories
- Domain-driven design modules
- Clean separation of concerns
---
### dependencies
**Use for:** Component imports and coupling
**Examples:**
- Dependency injection via constructor
- Circular dependency between modules
- Interface-based dependencies
- Heavy reliance on utility modules
---
### error-handling
**Use for:** Error handling strategies
**Examples:**
- Try-catch blocks in async operations
- Global error handler middleware
- Custom error classes for domain errors
- No error handling in critical paths
---
### testing
**Use for:** Test coverage and quality
**Examples:**
- 95% unit test coverage with Jest
- Integration tests for API endpoints
- No tests for edge cases
- Tests use mocks appropriately
---
### performance
**Use for:** Algorithm efficiency, optimization
**Examples:**
- O(n²) algorithm for data processing
- Memoization for expensive calculations
- N+1 query problem in data loading
- Efficient caching of computed values
---
### security
**Use for:** Security implementation in code
**Examples:**
- SQL injection vulnerability
- JWT tokens in localStorage (XSS risk)
- Input validation with Joi
- Output encoding prevents XSS
---
### code-quality
**Use for:** Code quality metrics
**Examples:**
- High cyclomatic complexity (>20)
- Consistent naming conventions
- Significant code duplication
- Clean, readable code
---
### documentation
**Use for:** Code documentation quality
**Examples:**
- Comprehensive JSDoc/TSDoc
- README files for each module
- No documentation for complex logic
- Inline comments explain why, not what
---
### complexity
**Use for:** Code complexity measurements
**Examples:**
- Function cyclomatic complexity: 45
- Deep nesting (6 levels) in conditionals
- Functions average 150 lines
- Cognitive complexity manageable
---
### coupling
**Use for:** Interdependence between components
**Examples:**
- Tight coupling to ORM throughout
- Loose coupling via interfaces
- Direct database access in UI
- Service layer properly abstracted
---
### cohesion
**Use for:** How related component responsibilities are
**Examples:**
- High cohesion: single responsibility
- Low cohesion: mixed concerns
- Each module has clear focus
- Service handles auth, logging, config (bad)
---
### maintainability
**Use for:** How easy to maintain and modify
**Examples:**
- High maintainability with clean separation
- Technical debt: hardcoded values
- Difficult to modify due to coupling
- Well-structured, easy to understand
---
## Category Selection Guide
### Decision Tree
**Question 1: What C4 level are you documenting?**
- **C1 (System Context)** → Use C1 categories
- **C2 (Container)** → Use C2 categories
- **C3 (Component)** → Use C3 categories
---
**Question 2: What aspect are you observing?**
#### C1 Level
| Observation About | Use Category |
|-------------------|--------------|
| Overall architecture pattern | `architecture` |
| How systems communicate | `integration` |
| What's in/out of system | `boundaries` |
| System-level auth/security | `security` |
| Scaling approach | `scalability` |
| Who uses the system | `actors` |
| Third-party services | `external-dependencies` |
| Where/how deployed | `deployment` |
| How data moves | `data-flow` |
---
#### C2 Level
| Observation About | Use Category |
|-------------------|--------------|
| Languages, frameworks | `technology` |
| Runtime environment | `runtime` |
| Container communication | `communication` |
| Databases, storage | `data-storage` |
| Auth mechanisms | `authentication` |
| Containerization | `deployment` |
| Container scaling | `scalability` |
| Container performance | `performance` |
| Container dependencies | `dependencies` |
| Config management | `configuration` |
| Logging, metrics | `monitoring` |
| Container security | `security` |
---
#### C3 Level
| Observation About | Use Category |
|-------------------|--------------|
| Design patterns used | `design-patterns` |
| Code organization | `code-structure` |
| Imports, dependencies | `dependencies` |
| Error handling approach | `error-handling` |
| Tests, coverage | `testing` |
| Algorithms, optimization | `performance` |
| Security in code | `security` |
| Code quality metrics | `code-quality` |
| Documentation | `documentation` |
| Code complexity | `complexity` |
| Component coupling | `coupling` |
| Component cohesion | `cohesion` |
| How easy to maintain | `maintainability` |
---
## Common Mistakes
### Using Wrong Level Category
**Wrong:**
```json
{
"level": "C1",
"category": "code-quality" // C3 category!
}
```
**Right:**
```json
{
"level": "C1",
"category": "architecture" // C1 category
}
```
---
### Too Granular for Level
**Wrong (C1):**
```json
{
"category": "architecture",
"title": "Repository pattern in UserService" // Too detailed!
}
```
**Right (C1):**
```json
{
"category": "architecture",
"title": "Microservices architecture with API gateway"
}
```
---
### Not Granular Enough
**Wrong (C3):**
```json
{
"category": "design-patterns",
"title": "Microservices architecture" // Too high-level!
}
```
**Right (C3):**
```json
{
"category": "design-patterns",
"title": "Repository pattern for data access"
}
```
---
## Category Counts
- **C1 System Context**: 9 categories
- **C2 Container**: 12 categories
- **C3 Component**: 13 categories
**Total**: 34 categories across all levels
---
## Related Resources
- **[SKILL.md](SKILL.md)** - Main skill documentation
- **[reference.md](reference.md)** - Comprehensive methodology
- **[examples.md](examples.md)** - 30+ examples with categories

View File

@@ -0,0 +1,901 @@
# Observation Examples
**30+ real-world examples across C1, C2, and C3 levels.**
---
## Table of Contents
1. [C1 System Context Examples](#c1-system-context-examples)
2. [C2 Container Examples](#c2-container-examples)
3. [C3 Component Examples](#c3-component-examples)
---
## C1 System Context Examples
### Example 1: Event-Driven Architecture
```json
{
"id": "obs-event-driven-arch",
"category": "architecture",
"severity": "info",
"title": "Event-driven architecture with message queues",
"description": "The system uses event-driven architecture with RabbitMQ message queues for asynchronous processing between services. This enables loose coupling and improved scalability.",
"evidence": [
{
"type": "config",
"location": "docker-compose.yml",
"snippet": "rabbitmq:\n image: rabbitmq:3-management\n ports:\n - '5672:5672'\n - '15672:15672'",
"note": "RabbitMQ configured as message broker"
},
{
"type": "dependency",
"location": "backend/package.json",
"snippet": "\"amqplib\": \"^0.10.3\"",
"note": "AMQP library for queue integration"
}
],
"tags": ["architecture", "messaging", "async", "rabbitmq"],
"impact": "Enables horizontal scaling and system resilience. Services can process events asynchronously without blocking."
}
```
---
### Example 2: Third-Party Payment Dependency
```json
{
"id": "obs-third-party-payment",
"category": "external-dependencies",
"severity": "warning",
"title": "Critical dependency on third-party payment gateway",
"description": "System has a hard dependency on Stripe payment gateway with no fallback mechanism. Stripe outages directly impact payment processing capability.",
"evidence": [
{
"type": "code",
"location": "src/services/payment.ts:23",
"snippet": "const stripe = new Stripe(process.env.STRIPE_KEY);",
"note": "Direct Stripe integration with no abstraction layer"
},
{
"type": "file",
"location": "src/services/payment.ts",
"note": "Single payment provider implementation, no interface"
}
],
"tags": ["external-dependency", "payments", "stripe", "resilience"],
"impact": "System unavailable for payments during Stripe outages. No ability to switch payment providers.",
"recommendation": "Implement payment gateway abstraction layer to support multiple providers (Stripe, PayPal, Square) with failover capability."
}
```
---
### Example 3: Microservices Architecture
```json
{
"id": "obs-microservices-pattern",
"category": "architecture",
"severity": "info",
"title": "Microservices architecture with API gateway",
"description": "System follows microservices architecture pattern with Kong API gateway routing requests to independent services (user-service, product-service, order-service).",
"evidence": [
{
"type": "config",
"location": "kong/kong.yml",
"snippet": "services:\n - name: user-service\n url: http://user-api:3000\n - name: product-service\n url: http://product-api:3001",
"note": "Kong gateway configuration"
},
{
"type": "pattern",
"location": "repos/",
"note": "Separate repositories for each service: user-service/, product-service/, order-service/"
}
],
"tags": ["architecture", "microservices", "api-gateway", "kong"],
"impact": "Enables independent deployment and scaling of services. Increases operational complexity."
}
```
---
### Example 4: Public API Without Rate Limiting
```json
{
"id": "obs-no-rate-limiting",
"category": "security",
"severity": "critical",
"title": "Public API lacks rate limiting",
"description": "REST API is publicly accessible without rate limiting, making it vulnerable to denial-of-service attacks and API abuse.",
"evidence": [
{
"type": "file",
"location": "src/middleware/",
"note": "No rate limiting middleware found"
},
{
"type": "config",
"location": "package.json",
"note": "No rate limiting library installed (express-rate-limit, rate-limiter-flexible)"
}
],
"tags": ["security", "rate-limiting", "dos", "api"],
"impact": "System vulnerable to denial-of-service attacks, API abuse, and resource exhaustion.",
"recommendation": "Implement rate limiting using express-rate-limit or API gateway rate limiting policies."
}
```
---
### Example 5: OAuth2 Authentication
```json
{
"id": "obs-oauth2-integration",
"category": "integration",
"severity": "info",
"title": "OAuth2 authentication via Auth0",
"description": "System integrates with Auth0 for OAuth2 authentication, supporting social login (Google, Facebook, GitHub) and enterprise SSO.",
"evidence": [
{
"type": "config",
"location": ".env.example",
"snippet": "AUTH0_DOMAIN=example.auth0.com\nAUTH0_CLIENT_ID=xxx\nAUTH0_CALLBACK_URL=https://app.example.com/callback"
},
{
"type": "dependency",
"location": "frontend/package.json",
"snippet": "\"@auth0/auth0-react\": \"^2.0.1\""
}
],
"tags": ["authentication", "oauth2", "auth0", "sso"],
"impact": "Enables enterprise SSO and social login. Reduces authentication implementation complexity."
}
```
---
### Example 6: Multi-Tenant Architecture
```json
{
"id": "obs-multi-tenant-saas",
"category": "architecture",
"severity": "info",
"title": "Multi-tenant SaaS architecture with tenant isolation",
"description": "System implements multi-tenant architecture with database-per-tenant isolation strategy. Each customer organization has a dedicated PostgreSQL schema.",
"evidence": [
{
"type": "code",
"location": "src/db/tenant.ts:34-38",
"snippet": "const schema = `tenant_${tenantId}`;\nawait db.raw(`SET search_path TO ${schema}`);\nreturn db;",
"note": "Schema-based tenant isolation"
},
{
"type": "pattern",
"location": "src/middleware/tenant-context.ts",
"note": "Middleware extracts tenant from subdomain and sets context"
}
],
"tags": ["architecture", "multi-tenant", "saas", "isolation"],
"impact": "Strong tenant data isolation. Schema-per-tenant approach may limit scalability with thousands of tenants."
}
```
---
### Example 7: Cloud-Native Deployment
```json
{
"id": "obs-cloud-native-aws",
"category": "deployment",
"severity": "info",
"title": "Cloud-native deployment on AWS with auto-scaling",
"description": "System deployed on AWS using ECS Fargate for container orchestration with auto-scaling based on CPU and memory metrics.",
"evidence": [
{
"type": "config",
"location": "infrastructure/terraform/ecs.tf",
"snippet": "resource \"aws_appautoscaling_target\" \"ecs_target\" {\n max_capacity = 10\n min_capacity = 2\n resource_id = aws_ecs_service.main.id\n}",
"note": "Terraform configuration for ECS auto-scaling"
},
{
"type": "file",
"location": "infrastructure/terraform/",
"note": "Infrastructure as code using Terraform"
}
],
"tags": ["deployment", "aws", "ecs", "auto-scaling", "cloud-native"],
"impact": "Enables automatic scaling based on demand. Reduces infrastructure management overhead."
}
```
---
### Example 8: Data Lake Integration
```json
{
"id": "obs-data-lake-snowflake",
"category": "data-flow",
"severity": "info",
"title": "Batch data export to Snowflake data lake",
"description": "System exports operational data to Snowflake data lake nightly for analytics and reporting. ETL pipeline implemented using Apache Airflow.",
"evidence": [
{
"type": "file",
"location": "airflow/dags/export-to-snowflake.py",
"note": "Airflow DAG for nightly data export"
},
{
"type": "config",
"location": "airflow/config/connections.yml",
"snippet": "snowflake_conn:\n conn_type: snowflake\n account: xy12345\n database: analytics_db"
}
],
"tags": ["data-flow", "etl", "snowflake", "analytics", "airflow"],
"impact": "Enables advanced analytics and reporting without impacting operational database performance."
}
```
---
### Example 9: Service Mesh Implementation
```json
{
"id": "obs-istio-service-mesh",
"category": "integration",
"severity": "info",
"title": "Istio service mesh for service-to-service communication",
"description": "Microservices communicate through Istio service mesh providing mTLS encryption, traffic management, and observability.",
"evidence": [
{
"type": "config",
"location": "k8s/istio/virtual-service.yml",
"snippet": "apiVersion: networking.istio.io/v1beta1\nkind: VirtualService\nmetadata:\n name: user-service"
},
{
"type": "pattern",
"location": "k8s/",
"note": "Istio sidecar proxies injected into all service pods"
}
],
"tags": ["integration", "service-mesh", "istio", "mtls", "microservices"],
"impact": "Provides mTLS encryption, circuit breaking, and distributed tracing without application code changes."
}
```
---
### Example 10: Geographic Distribution
```json
{
"id": "obs-multi-region-active-active",
"category": "scalability",
"severity": "info",
"title": "Multi-region active-active deployment for global users",
"description": "System deployed in active-active configuration across US-East, US-West, and EU-Central regions with Route53 latency-based routing.",
"evidence": [
{
"type": "config",
"location": "infrastructure/terraform/route53.tf",
"snippet": "routing_policy = \"latency\"\nset_identifier = \"us-east-1\""
},
{
"type": "pattern",
"location": "infrastructure/",
"note": "Three Terraform workspaces: us-east, us-west, eu-central"
}
],
"tags": ["scalability", "multi-region", "global", "high-availability"],
"impact": "Reduces latency for global users. Provides regional failover capability. Increases infrastructure cost and complexity."
}
```
---
## C2 Container Examples
### Example 11: React SPA with State Management
```json
{
"id": "obs-spa-state-mgmt",
"category": "technology",
"severity": "info",
"title": "Redux Toolkit for state management in React SPA",
"description": "Frontend SPA uses Redux Toolkit for global state management, following best practices with feature-based slices and RTK Query for API calls.",
"evidence": [
{
"type": "dependency",
"location": "frontend/package.json",
"snippet": "\"@reduxjs/toolkit\": \"^1.9.5\",\n\"react-redux\": \"^8.1.1\""
},
{
"type": "file",
"location": "frontend/src/store/",
"note": "Well-organized store structure with feature slices: authSlice, userSlice, productSlice"
},
{
"type": "code",
"location": "frontend/src/store/index.ts",
"snippet": "import { configureStore } from '@reduxjs/toolkit';\nimport authReducer from './authSlice';"
}
],
"tags": ["state-management", "redux", "frontend", "react"],
"impact": "Provides predictable state updates, improved debugging with Redux DevTools, and type-safe API calls."
}
```
---
### Example 12: Database Connection Pool Missing
```json
{
"id": "obs-db-no-connection-pool",
"category": "performance",
"severity": "warning",
"title": "Database connections not pooled",
"description": "Backend API creates new database connections for each request instead of using connection pooling, leading to performance degradation under load.",
"evidence": [
{
"type": "code",
"location": "src/db/connection.ts:12-15",
"snippet": "export async function getConnection() {\n return await mysql.createConnection(config);\n}",
"note": "New connection created for every query"
},
{
"type": "code",
"location": "src/routes/users.ts:23",
"snippet": "const conn = await getConnection();\nconst users = await conn.query('SELECT * FROM users');",
"note": "Pattern repeated throughout codebase"
}
],
"tags": ["performance", "database", "connection-pool", "scalability"],
"impact": "High latency for database queries. Connection exhaustion under concurrent load. Potential database server overload.",
"recommendation": "Implement connection pooling using mysql2/pool with min 5, max 20 connections."
}
```
---
### Example 13: Container Health Checks
```json
{
"id": "obs-health-check-implemented",
"category": "deployment",
"severity": "info",
"title": "Comprehensive health check endpoints",
"description": "Container implements /health (liveness) and /ready (readiness) endpoints with dependency checks for database, cache, and message queue.",
"evidence": [
{
"type": "code",
"location": "src/routes/health.ts:10-25",
"snippet": "app.get('/health', async (req, res) => {\n const dbOk = await checkDatabase();\n const redisOk = await checkRedis();\n const queueOk = await checkQueue();\n res.status(dbOk && redisOk && queueOk ? 200 : 503).json({...});\n});"
},
{
"type": "config",
"location": "k8s/deployment.yml:45-52",
"snippet": "livenessProbe:\n httpGet:\n path: /health\n port: 3000\nreadinessProbe:\n httpGet:\n path: /ready\n port: 3000"
}
],
"tags": ["deployment", "health-check", "kubernetes", "reliability"],
"impact": "Kubernetes can detect and restart unhealthy containers. Prevents routing traffic to containers not ready to serve requests."
}
```
---
### Example 14: WebSocket Real-Time Communication
```json
{
"id": "obs-websocket-notifications",
"category": "communication",
"severity": "info",
"title": "WebSocket server for real-time notifications",
"description": "Container implements WebSocket server using Socket.io for real-time push notifications to connected clients.",
"evidence": [
{
"type": "dependency",
"location": "backend/package.json",
"snippet": "\"socket.io\": \"^4.6.1\""
},
{
"type": "code",
"location": "src/websocket/server.ts:15-20",
"snippet": "const io = new Server(httpServer, {\n cors: { origin: process.env.CORS_ORIGIN },\n transports: ['websocket', 'polling']\n});"
}
],
"tags": ["communication", "websocket", "real-time", "socket.io"],
"impact": "Enables instant notifications without polling. Maintains persistent connections, increasing server memory usage."
}
```
---
### Example 15: Docker Multi-Stage Build
```json
{
"id": "obs-docker-multi-stage",
"category": "deployment",
"severity": "info",
"title": "Multi-stage Docker build for optimized image size",
"description": "Container uses multi-stage Dockerfile separating build and runtime stages, reducing final image size from 1.2GB to 180MB.",
"evidence": [
{
"type": "config",
"location": "Dockerfile:1-15",
"snippet": "# Build stage\nFROM node:18-alpine AS builder\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci\nCOPY . .\nRUN npm run build\n\n# Runtime stage\nFROM node:18-alpine\nWORKDIR /app\nCOPY --from=builder /app/dist ./dist\nCOPY package*.json ./\nRUN npm ci --production"
}
],
"tags": ["deployment", "docker", "optimization", "image-size"],
"impact": "Reduces image size by 84%, faster deployments, lower storage costs, smaller attack surface."
}
```
---
### Example 16: Redis Session Storage
```json
{
"id": "obs-redis-sessions",
"category": "data-storage",
"severity": "info",
"title": "Redis for session storage with TTL",
"description": "Container stores user sessions in Redis with 24-hour TTL, enabling horizontal scaling and fast session lookups.",
"evidence": [
{
"type": "code",
"location": "src/config/session.ts:8-14",
"snippet": "app.use(session({\n store: new RedisStore({ client: redisClient }),\n secret: process.env.SESSION_SECRET,\n resave: false,\n saveUninitialized: false,\n cookie: { maxAge: 24 * 60 * 60 * 1000 }\n}));"
},
{
"type": "dependency",
"location": "package.json",
"snippet": "\"connect-redis\": \"^7.1.0\",\n\"redis\": \"^4.6.5\""
}
],
"tags": ["data-storage", "redis", "sessions", "caching"],
"impact": "Enables stateless application design. Session data survives container restarts. Fast session access (~1ms)."
}
```
---
### Example 17: Environment Variable Overload
```json
{
"id": "obs-env-var-overload",
"category": "configuration",
"severity": "warning",
"title": "Excessive environment variables (42 required)",
"description": "Container requires 42 environment variables to start, making configuration error-prone and deployment complex.",
"evidence": [
{
"type": "file",
"location": ".env.example",
"note": "42 environment variables listed"
},
{
"type": "code",
"location": "src/config/index.ts:5-50",
"snippet": "export const config = {\n dbHost: required('DB_HOST'),\n dbPort: required('DB_PORT'),\n // ... 40 more",
"note": "Long list of required config values"
}
],
"tags": ["configuration", "environment-variables", "complexity"],
"impact": "High configuration complexity. Prone to misconfiguration errors. Difficult onboarding for new developers.",
"recommendation": "Consolidate configuration using a config server (e.g., Spring Cloud Config) or use sensible defaults with override capability."
}
```
---
### Example 18: No Distributed Tracing
```json
{
"id": "obs-no-distributed-tracing",
"category": "monitoring",
"severity": "warning",
"title": "Missing distributed tracing in microservices",
"description": "Container has logging but no distributed tracing instrumentation, making it difficult to debug cross-service request flows.",
"evidence": [
{
"type": "file",
"location": "package.json",
"note": "No OpenTelemetry, Jaeger, or Zipkin dependencies"
},
{
"type": "pattern",
"location": "src/middleware/",
"note": "No trace context propagation middleware"
}
],
"tags": ["monitoring", "distributed-tracing", "observability", "microservices"],
"impact": "Difficult to trace requests across service boundaries. Hard to identify performance bottlenecks in multi-service flows.",
"recommendation": "Implement OpenTelemetry instrumentation with Jaeger or Tempo backend for distributed tracing."
}
```
---
### Example 19: gRPC Inter-Service Communication
```json
{
"id": "obs-grpc-communication",
"category": "communication",
"severity": "info",
"title": "gRPC for high-performance inter-service communication",
"description": "Container uses gRPC with Protocol Buffers for efficient inter-service communication, providing better performance than REST for internal APIs.",
"evidence": [
{
"type": "dependency",
"location": "package.json",
"snippet": "\"@grpc/grpc-js\": \"^1.8.14\",\n\"@grpc/proto-loader\": \"^0.7.6\""
},
{
"type": "file",
"location": "proto/user-service.proto",
"snippet": "service UserService {\n rpc GetUser (GetUserRequest) returns (User);\n rpc ListUsers (ListUsersRequest) returns (UserList);\n}",
"note": "Protocol Buffer service definition"
}
],
"tags": ["communication", "grpc", "protobuf", "performance"],
"impact": "Lower latency and bandwidth usage vs REST. Type-safe service contracts. Requires gRPC-compatible clients."
}
```
---
### Example 20: JWT Authentication with Refresh Tokens
```json
{
"id": "obs-jwt-refresh-tokens",
"category": "authentication",
"severity": "info",
"title": "JWT authentication with refresh token rotation",
"description": "Container implements JWT access tokens (15min TTL) with refresh tokens (7 days) stored in httpOnly cookies, following OAuth2 best practices.",
"evidence": [
{
"type": "code",
"location": "src/auth/jwt.ts:45-52",
"snippet": "const accessToken = jwt.sign(payload, secret, { expiresIn: '15m' });\nconst refreshToken = jwt.sign({ userId }, refreshSecret, { expiresIn: '7d' });\nres.cookie('refreshToken', refreshToken, { httpOnly: true, secure: true });",
"note": "Token generation with appropriate TTLs"
}
],
"tags": ["authentication", "jwt", "refresh-tokens", "security"],
"impact": "Balances security (short-lived access tokens) with UX (long refresh window). Refresh tokens in httpOnly cookies prevent XSS theft."
}
```
---
## C3 Component Examples
### Example 21: JWT in localStorage (Security Issue)
```json
{
"id": "obs-auth-jwt-localstorage",
"category": "security",
"severity": "critical",
"title": "JWT tokens stored in localStorage",
"description": "Authentication component stores JWT tokens in browser localStorage, making them accessible to JavaScript and vulnerable to XSS attacks. Tokens should be stored in httpOnly cookies.",
"evidence": [
{
"type": "code",
"location": "src/features/auth/authSlice.ts:45",
"snippet": "localStorage.setItem('authToken', action.payload.token);",
"note": "Token persisted in localStorage"
},
{
"type": "code",
"location": "src/features/auth/authSlice.ts:52",
"snippet": "const token = localStorage.getItem('authToken');\nif (token) { setAuthHeader(token); }",
"note": "Token retrieved from localStorage on app init"
}
],
"tags": ["security", "authentication", "xss", "jwt"],
"impact": "High security risk - Any XSS vulnerability can lead to token theft and account takeover. Tokens persist across browser sessions.",
"recommendation": "Migrate to httpOnly cookies for token storage. Tokens will be automatically included in requests and inaccessible to JavaScript."
}
```
---
### Example 22: Repository Pattern Implementation
```json
{
"id": "obs-repository-pattern",
"category": "design-patterns",
"severity": "info",
"title": "Repository pattern for data access layer",
"description": "UserService component implements the repository pattern to abstract database operations, improving testability and separation of concerns.",
"evidence": [
{
"type": "file",
"location": "src/repositories/UserRepository.ts",
"note": "Dedicated repository class implementing IUserRepository interface"
},
{
"type": "code",
"location": "src/services/UserService.ts:23",
"snippet": "constructor(private userRepo: IUserRepository) {}",
"note": "Dependency injection of repository interface, not concrete implementation"
},
{
"type": "code",
"location": "src/repositories/UserRepository.ts:15-20",
"snippet": "async findById(id: string): Promise<User | null> {\n const row = await this.db('users').where({ id }).first();\n return row ? this.mapToEntity(row) : null;\n}",
"note": "Repository handles ORM queries and entity mapping"
}
],
"tags": ["design-pattern", "repository", "data-access", "separation-of-concerns"],
"impact": "Improved testability through dependency injection. Clean separation between business logic and data access. Easier to swap database implementations."
}
```
---
### Example 23: Missing Error Handling
```json
{
"id": "obs-no-error-handling",
"category": "error-handling",
"severity": "warning",
"title": "Missing error handling in async operations",
"description": "PaymentService component performs async Stripe operations without proper error handling, risking unhandled promise rejections and application crashes.",
"evidence": [
{
"type": "code",
"location": "src/features/payment/PaymentService.ts:78-82",
"snippet": "async processPayment(amount: number) {\n const charge = await stripe.charges.create({ amount });\n await this.recordPayment(charge.id);\n return charge.id;\n}",
"note": "No try-catch block or .catch() handler"
},
{
"type": "code",
"location": "src/features/payment/PaymentService.ts:95-98",
"snippet": "async refundPayment(chargeId: string) {\n const refund = await stripe.refunds.create({ charge: chargeId });\n return refund;\n}",
"note": "Same pattern - no error handling"
}
],
"tags": ["error-handling", "async", "reliability", "payment"],
"impact": "Application crashes or silent failures when Stripe API errors occur. No user feedback on payment failures. Potential data inconsistency.",
"recommendation": "Add try-catch blocks to all async operations. Handle specific error types (network, API errors, validation). Log errors and return user-friendly messages."
}
```
---
### Example 24: High Cyclomatic Complexity
```json
{
"id": "obs-high-complexity-validation",
"category": "complexity",
"severity": "warning",
"title": "High cyclomatic complexity in validation function",
"description": "FormValidator.validate() function has cyclomatic complexity of 45, making it difficult to understand, test, and maintain.",
"evidence": [
{
"type": "metric",
"location": "src/utils/FormValidator.ts:validate",
"snippet": "Cyclomatic complexity: 45",
"note": "Measured with ESLint complexity rule"
},
{
"type": "code",
"location": "src/utils/FormValidator.ts:25-180",
"snippet": "function validate(form: Form): ValidationResult {\n if (form.email) {\n if (!isEmail(form.email)) {\n if (form.email.includes('@')) {\n // 150+ lines of nested conditions...",
"note": "Deep nesting (7 levels) with many branches"
}
],
"tags": ["complexity", "code-quality", "maintainability", "testing"],
"impact": "Difficult to understand control flow. Hard to achieve full test coverage. High risk of bugs when modifying. New developers struggle to maintain.",
"recommendation": "Refactor into smaller functions, each validating one field. Extract common validation logic. Consider using validation library like Joi or Yup."
}
```
---
### Example 25: Comprehensive Unit Tests
```json
{
"id": "obs-good-test-coverage",
"category": "testing",
"severity": "info",
"title": "High unit test coverage with quality tests",
"description": "AuthService component has 95% unit test coverage with well-structured tests covering happy paths, edge cases, and error scenarios.",
"evidence": [
{
"type": "metric",
"location": "coverage/auth/AuthService.ts.html",
"snippet": "Lines: 95.2% (120/126)\nBranches: 92.5% (37/40)",
"note": "Jest coverage report"
},
{
"type": "file",
"location": "src/features/auth/__tests__/AuthService.test.ts",
"note": "12 test cases covering login, logout, token refresh, error scenarios"
},
{
"type": "code",
"location": "src/features/auth/__tests__/AuthService.test.ts:45-52",
"snippet": "describe('login', () => {\n it('should return tokens on valid credentials', async () => {...});\n it('should throw on invalid credentials', async () => {...});\n it('should lock account after 5 failed attempts', async () => {...});\n});"
}
],
"tags": ["testing", "unit-tests", "coverage", "quality"],
"impact": "High confidence in component behavior. Early bug detection. Safe refactoring. Good documentation through tests."
}
```
---
### Example 26: N+1 Query Problem
```json
{
"id": "obs-n-plus-one-queries",
"category": "performance",
"severity": "warning",
"title": "N+1 query problem in dashboard data loading",
"description": "DashboardController loads user posts in a loop, executing one query per post (N+1 problem). For a user with 100 posts, this results in 101 database queries.",
"evidence": [
{
"type": "code",
"location": "src/controllers/DashboardController.ts:78-82",
"snippet": "const posts = await Post.find({ userId });\nfor (const post of posts) {\n post.comments = await Comment.find({ postId: post.id }); // N queries\n post.likes = await Like.count({ postId: post.id }); // N queries\n}",
"note": "Separate query for each post's comments and likes"
}
],
"tags": ["performance", "database", "n+1", "orm"],
"impact": "Dashboard load time scales linearly with number of posts. 100 posts = 201 queries = ~2 seconds. Severe performance degradation with large datasets.",
"recommendation": "Use eager loading or JOIN queries to load related data in single query. Example: Post.find({ userId }).populate('comments likes')"
}
```
---
### Example 27: Tight Coupling to ORM
```json
{
"id": "obs-tight-orm-coupling",
"category": "coupling",
"severity": "warning",
"title": "Business logic tightly coupled to Sequelize ORM",
"description": "Service layer components directly use Sequelize models and queries throughout, making it difficult to test or switch ORMs.",
"evidence": [
{
"type": "code",
"location": "src/services/OrderService.ts:34-38",
"snippet": "async createOrder(data: OrderData) {\n const order = await Order.create(data);\n const items = await OrderItem.bulkCreate(order.id, data.items);\n return order;\n}",
"note": "Direct Sequelize model usage in service"
},
{
"type": "pattern",
"location": "src/services/",
"note": "All 15 service files directly import and use Sequelize models"
}
],
"tags": ["coupling", "orm", "architecture", "testability"],
"impact": "Difficult to unit test services (requires database). Hard to switch ORM. Business logic mixed with data access concerns.",
"recommendation": "Introduce repository layer to abstract ORM. Services depend on repository interfaces, not concrete ORM implementations."
}
```
---
### Example 28: Factory Pattern for Service Creation
```json
{
"id": "obs-factory-pattern-services",
"category": "design-patterns",
"severity": "info",
"title": "Factory pattern for creating service instances",
"description": "ServiceFactory component uses factory pattern to create service instances with appropriate dependencies, improving modularity and testability.",
"evidence": [
{
"type": "code",
"location": "src/factories/ServiceFactory.ts:12-25",
"snippet": "class ServiceFactory {\n createUserService(): UserService {\n const repo = new UserRepository(this.db);\n const cache = new RedisCache(this.redis);\n const notifier = new EmailNotifier(this.mailer);\n return new UserService(repo, cache, notifier);\n }\n}",
"note": "Factory encapsulates complex service construction"
}
],
"tags": ["design-pattern", "factory", "dependency-injection", "modularity"],
"impact": "Centralized service creation logic. Easy to swap implementations. Supports testing with mock dependencies."
}
```
---
### Example 29: Missing Input Validation
```json
{
"id": "obs-no-input-validation",
"category": "security",
"severity": "critical",
"title": "No input validation in API controllers",
"description": "UserController accepts user input without validation, allowing malformed data to reach the database and potentially causing SQL injection or data corruption.",
"evidence": [
{
"type": "code",
"location": "src/controllers/UserController.ts:23-27",
"snippet": "async createUser(req: Request, res: Response) {\n const user = await userService.create(req.body);\n res.json(user);\n}",
"note": "req.body used directly without validation"
},
{
"type": "pattern",
"location": "src/controllers/",
"note": "No validation middleware (joi, class-validator, zod) found in any controller"
}
],
"tags": ["security", "validation", "input-validation", "api"],
"impact": "Critical security vulnerability. Risk of SQL injection, NoSQL injection, data corruption. Invalid data can crash application.",
"recommendation": "Implement input validation using Joi, class-validator, or Zod. Validate all inputs at controller level before processing."
}
```
---
### Example 30: Code Documentation with TSDoc
```json
{
"id": "obs-tsdoc-documentation",
"category": "documentation",
"severity": "info",
"title": "Comprehensive TSDoc documentation for public APIs",
"description": "All public methods and classes in the API layer have comprehensive TSDoc comments including descriptions, parameter types, return values, and usage examples.",
"evidence": [
{
"type": "code",
"location": "src/api/UserAPI.ts:15-24",
"snippet": "/**\n * Creates a new user account.\n * @param userData - User registration data\n * @param userData.email - User email (must be unique)\n * @param userData.password - Password (min 8 characters)\n * @returns Newly created user object (password excluded)\n * @throws {ValidationError} If email already exists\n * @example\n * const user = await userAPI.createUser({ email: 'test@example.com', password: 'secret123' });\n */\nasync createUser(userData: UserRegistrationData): Promise<User>"
}
],
"tags": ["documentation", "tsdoc", "api", "code-quality"],
"impact": "Excellent developer experience. IntelliSense shows detailed information. Easier onboarding for new developers. Reduced need for external documentation."
}
```
---
## Summary
This examples document provides 30 real-world observation examples:
- **C1 System Context**: 10 examples covering architecture, integration, security, scalability, deployment
- **C2 Container**: 10 examples covering technology, performance, communication, monitoring, authentication
- **C3 Component**: 10 examples covering design patterns, security, testing, complexity, code quality
Each example demonstrates:
- Proper structure with all required fields
- Concrete evidence with file paths and code snippets
- Appropriate severity levels
- Clear impact and recommendations
- Relevant tags for searchability
Use these examples as templates when documenting your own architectural observations.

View File

@@ -0,0 +1,883 @@
# Observation Documentation Reference
**Complete guide for documenting architectural observations across C1, C2, and C3 levels.**
---
## Table of Contents
1. [Category Definitions](#category-definitions)
2. [Evidence Collection Guidelines](#evidence-collection-guidelines)
3. [Severity Level Best Practices](#severity-level-best-practices)
4. [Anti-Patterns to Avoid](#anti-patterns-to-avoid)
5. [Cross-Level Consistency](#cross-level-consistency)
6. [Validation Requirements](#validation-requirements)
---
## Category Definitions
### C1 System Context Categories
#### architecture
**Definition:** Overall system architecture patterns, styles, and strategic decisions.
**What to document:**
- Architectural styles (monolith, microservices, event-driven, layered)
- System decomposition approach
- Major architectural patterns (CQRS, event sourcing, etc.)
- High-level structural decisions
**Examples:**
- "Event-driven architecture with message queues"
- "Microservices architecture with API gateway"
- "Monolithic layered architecture"
---
#### integration
**Definition:** How systems integrate and communicate with each other.
**What to document:**
- Integration patterns (REST, GraphQL, gRPC, messaging)
- API contracts and interfaces
- Data exchange formats
- Synchronous vs asynchronous communication
**Examples:**
- "Systems communicate via REST APIs over HTTPS"
- "Event-driven integration using RabbitMQ"
- "GraphQL gateway for unified API access"
---
#### boundaries
**Definition:** System scope, ownership boundaries, and organizational limits.
**What to document:**
- What's inside vs outside the system
- Team ownership boundaries
- Deployment boundaries
- Network boundaries (public/private/DMZ)
**Examples:**
- "System boundary includes web app and API, excludes database"
- "Frontend team owns UI system, backend team owns API system"
---
#### security
**Definition:** System-level security concerns, authentication, and authorization.
**What to document:**
- Authentication mechanisms (OAuth, JWT, SAML)
- Authorization approaches (RBAC, ABAC)
- Security vulnerabilities
- Data protection strategies
**Examples:**
- "JWT-based authentication with OAuth2"
- "No rate limiting on public API endpoints"
- "TLS encryption for all inter-system communication"
---
#### scalability
**Definition:** System's ability to scale and handle growth.
**What to document:**
- Horizontal vs vertical scaling approaches
- Scaling limitations
- Load balancing strategies
- Stateless vs stateful design
**Examples:**
- "Horizontally scalable via container orchestration"
- "Vertical scaling limited by database constraints"
- "Stateless design enables cloud auto-scaling"
---
#### actors
**Definition:** User types and external actors interacting with the system.
**What to document:**
- User personas and roles
- External systems acting as users
- Actor permissions and capabilities
**Examples:**
- "Three user types: Customer, Admin, Support Agent"
- "External audit system queries via API"
---
#### external-dependencies
**Definition:** Third-party systems, services, and critical external dependencies.
**What to document:**
- SaaS services and APIs
- Third-party integrations
- Dependency criticality
- Fallback mechanisms
**Examples:**
- "Critical dependency on Stripe payment gateway"
- "SendGrid for email, with fallback to AWS SES"
- "No fallback for authentication via Auth0"
---
#### deployment
**Definition:** Infrastructure, hosting, and deployment approaches.
**What to document:**
- Cloud vs on-premise
- Deployment strategies (blue-green, canary)
- Infrastructure as code
- Container orchestration
**Examples:**
- "Deployed on AWS using Kubernetes"
- "Blue-green deployment strategy with Terraform"
- "On-premise deployment with Docker Swarm"
---
#### data-flow
**Definition:** How data moves between systems and external actors.
**What to document:**
- Data flow directions
- Data transformations
- Data formats
- Real-time vs batch processing
**Examples:**
- "User data flows from web app to API to database"
- "Analytics data streamed to data warehouse via Kafka"
---
### C2 Container Categories
#### technology
**Definition:** Technology stack, frameworks, libraries, and languages.
**What to document:**
- Programming languages
- Frameworks and libraries
- Runtime environments
- Major dependencies
**Examples:**
- "React 18 SPA with Redux Toolkit"
- "Node.js 18 with Express.js framework"
- "Python 3.11 with FastAPI"
---
#### runtime
**Definition:** Runtime characteristics, environment, and execution context.
**What to document:**
- Runtime environment (Node.js, JVM, .NET)
- Process model (single-threaded, multi-threaded)
- Memory and resource requirements
- Environment variables
**Examples:**
- "Single-threaded Node.js event loop"
- "JVM with 4GB heap size"
- "Requires 16 environment variables"
---
#### communication
**Definition:** Inter-container communication protocols and patterns.
**What to document:**
- Communication protocols (HTTP, gRPC, WebSocket)
- API styles (REST, GraphQL)
- Message formats (JSON, Protobuf)
- Communication patterns (request/response, pub/sub)
**Examples:**
- "REST API with JSON payloads"
- "gRPC with Protobuf serialization"
- "WebSocket for real-time updates"
---
#### data-storage
**Definition:** Databases, caches, and storage mechanisms.
**What to document:**
- Database types (relational, NoSQL, graph)
- Caching strategies
- Storage technologies
- Data persistence approaches
**Examples:**
- "PostgreSQL 14 for relational data"
- "Redis for session caching"
- "MongoDB for document storage"
---
#### authentication
**Definition:** Container-level authentication and authorization.
**What to document:**
- Authentication mechanisms
- Token management
- Session handling
- Authorization strategies
**Examples:**
- "JWT bearer token authentication"
- "Session cookies with Redis storage"
- "API key authentication for service-to-service"
---
#### deployment
**Definition:** Container deployment strategies and configurations.
**What to document:**
- Containerization (Docker, etc.)
- Orchestration (Kubernetes, Docker Swarm)
- Deployment pipelines
- Health checks and readiness probes
**Examples:**
- "Docker container deployed on Kubernetes"
- "Health check endpoint at /health"
- "Blue-green deployment via ArgoCD"
---
#### scalability
**Definition:** Container-level scaling capabilities.
**What to document:**
- Horizontal pod autoscaling
- Replica counts
- Resource limits
- Scaling triggers
**Examples:**
- "Auto-scales 2-10 pods based on CPU"
- "Stateless design enables horizontal scaling"
- "Limited by database connection pool size"
---
#### performance
**Definition:** Container performance characteristics and optimizations.
**What to document:**
- Response times
- Throughput capacity
- Resource utilization
- Performance optimizations
**Examples:**
- "Average response time: 50ms"
- "Code splitting and lazy loading implemented"
- "Database queries not optimized with indexes"
---
#### dependencies
**Definition:** Container dependencies on other containers or services.
**What to document:**
- Direct dependencies
- Dependency versions
- Dependency criticality
- Coupling strength
**Examples:**
- "Depends on API container and Redis cache"
- "Critical dependency on database"
- "Loose coupling via message queue"
---
#### configuration
**Definition:** Configuration management approaches.
**What to document:**
- Configuration sources (env vars, config files, config servers)
- Secret management
- Feature flags
- Configuration validation
**Examples:**
- "Configuration via environment variables"
- "Secrets stored in Kubernetes secrets"
- "Feature flags managed in LaunchDarkly"
---
#### monitoring
**Definition:** Observability, logging, and monitoring.
**What to document:**
- Logging frameworks and formats
- Metrics collection
- Tracing and APM
- Alerting
**Examples:**
- "Winston logger with JSON format"
- "Prometheus metrics exposed at /metrics"
- "No distributed tracing implemented"
---
### C3 Component Categories
#### design-patterns
**Definition:** Design patterns and architectural patterns in code.
**What to document:**
- Creational patterns (Factory, Singleton, Builder)
- Structural patterns (Adapter, Decorator, Facade)
- Behavioral patterns (Observer, Strategy, Command)
- Domain patterns (Repository, Service, Entity)
**Examples:**
- "Repository pattern for data access"
- "Factory pattern for creating services"
- "Observer pattern for event handling"
---
#### code-structure
**Definition:** Code organization, modularity, and file structure.
**What to document:**
- Directory structure
- Module organization
- File naming conventions
- Code grouping strategies
**Examples:**
- "Feature-based directory structure"
- "Layered architecture: controllers/services/repositories"
- "Modules organized by domain"
---
#### dependencies
**Definition:** Component-level imports and dependencies.
**What to document:**
- Import patterns
- Circular dependencies
- Dependency injection
- Module coupling
**Examples:**
- "Dependency injection via constructor"
- "Circular dependency between User and Order modules"
- "Heavy reliance on utility modules"
---
#### error-handling
**Definition:** Error handling strategies and patterns.
**What to document:**
- Try-catch usage
- Error propagation
- Error logging
- Custom error types
**Examples:**
- "No error handling in async operations"
- "Custom error classes for domain errors"
- "Global error handler middleware"
---
#### testing
**Definition:** Test coverage, quality, and strategies.
**What to document:**
- Unit test coverage
- Integration tests
- Test frameworks
- Test quality
**Examples:**
- "85% unit test coverage with Jest"
- "No integration tests"
- "Tests use actual database instead of mocks"
---
#### performance
**Definition:** Algorithm efficiency and code-level optimizations.
**What to document:**
- Algorithm complexity
- Performance bottlenecks
- Optimization techniques
- Resource usage
**Examples:**
- "O(n²) algorithm for data processing"
- "Memoization used for expensive calculations"
- "No caching of computed values"
---
#### security
**Definition:** Security implementation details in code.
**What to document:**
- Input validation
- Output encoding
- Secret handling
- Vulnerability patterns
**Examples:**
- "SQL injection vulnerability in query builder"
- "JWT tokens stored in localStorage"
- "Input validation using Joi schema"
---
#### code-quality
**Definition:** Code quality metrics and standards.
**What to document:**
- Code complexity
- Code duplication
- Naming conventions
- Code style
**Examples:**
- "High cyclomatic complexity (>20)"
- "Consistent naming conventions followed"
- "Significant code duplication in controllers"
---
#### documentation
**Definition:** Code documentation quality and coverage.
**What to document:**
- JSDoc/TSDoc comments
- README files
- API documentation
- Inline comments
**Examples:**
- "Comprehensive JSDoc for all public APIs"
- "No documentation for complex algorithms"
- "README outdated, doesn't match implementation"
---
#### complexity
**Definition:** Code complexity measurements.
**What to document:**
- Cyclomatic complexity
- Cognitive complexity
- Function length
- Nesting depth
**Examples:**
- "Function with cyclomatic complexity of 45"
- "Deep nesting (6 levels) in conditional logic"
- "Functions average 150 lines (too long)"
---
#### coupling
**Definition:** Degree of interdependence between components.
**What to document:**
- Tight vs loose coupling
- Coupling to external libraries
- Coupling to infrastructure
- Circular dependencies
**Examples:**
- "Tight coupling to ORM throughout codebase"
- "Components loosely coupled via interfaces"
- "Direct database access in UI components"
---
#### cohesion
**Definition:** How closely related component responsibilities are.
**What to document:**
- Single Responsibility Principle adherence
- Component focus
- Mixed concerns
**Examples:**
- "High cohesion: each service has single responsibility"
- "Low cohesion: AuthService handles auth, logging, and config"
---
#### maintainability
**Definition:** How easy it is to maintain and modify the code.
**What to document:**
- Code readability
- Modification complexity
- Technical debt
- Refactoring needs
**Examples:**
- "High maintainability with clear separation of concerns"
- "Technical debt: hardcoded values throughout"
- "Difficult to modify due to tight coupling"
---
## Evidence Collection Guidelines
### Best Practices
1. **Always provide file paths**
- Use relative paths from repository root
- Include line numbers for code snippets: `src/auth.ts:45-52`
- For directories, use trailing slash: `src/controllers/`
2. **Keep snippets concise**
- 1-10 lines maximum
- Focus on the relevant part
- Use `...` to indicate omitted code
3. **Match evidence type to content**
- `file` - For file/directory existence: `package.json`, `src/config/`
- `code` - For actual code snippets
- `config` - For configuration values: `.env`, `docker-compose.yml`
- `pattern` - For architectural patterns without specific file
- `metric` - For quantitative measurements
- `dependency` - For package dependencies from manifests
4. **Add context with notes**
- Explain what the evidence shows
- Clarify non-obvious connections
- Provide additional context
### Evidence Examples
**Good file evidence:**
```json
{
"type": "file",
"location": "src/repositories/UserRepository.ts",
"note": "Repository pattern implementation"
}
```
**Good code evidence:**
```json
{
"type": "code",
"location": "src/auth/AuthService.ts:45-47",
"snippet": "localStorage.setItem('token', jwt);\nconst decoded = jwtDecode(jwt);\nreturn decoded;",
"note": "JWT stored in localStorage, vulnerable to XSS"
}
```
**Good config evidence:**
```json
{
"type": "config",
"location": "docker-compose.yml:15-18",
"snippet": "redis:\n image: redis:7-alpine\n ports:\n - '6379:6379'",
"note": "Redis configured for caching"
}
```
**Good pattern evidence:**
```json
{
"type": "pattern",
"location": "src/services/",
"note": "Service layer pattern with dependency injection throughout codebase"
}
```
---
## Severity Level Best Practices
### Critical Severity
**Use for:**
- **Security vulnerabilities**: XSS, SQL injection, exposed secrets, insecure authentication
- **Data loss risks**: No backups, data deletion without confirmation
- **System unavailability**: Single points of failure, no failover
- **Critical bugs**: Core functionality broken, data corruption
**Checklist:**
- ✅ Does this pose immediate risk to security, data, or availability?
- ✅ Could this result in data breach or data loss?
- ✅ Would this cause system downtime or service outage?
- ✅ Is immediate action required?
**Example:**
```json
{
"severity": "critical",
"title": "SQL injection vulnerability in user query",
"description": "User input directly concatenated into SQL query without sanitization.",
"impact": "Attackers can execute arbitrary SQL commands, access/modify all data",
"recommendation": "Use parameterized queries immediately"
}
```
---
### Warning Severity
**Use for:**
- **Performance issues**: N+1 queries, inefficient algorithms, resource leaks
- **Code quality**: High complexity, duplication, poor naming
- **Missing best practices**: No error handling, no tests, deprecated dependencies
- **Architectural concerns**: Anti-patterns, tight coupling, violations of SOLID
**Checklist:**
- ✅ Should this be fixed but isn't immediately critical?
- ✅ Does this impact performance, maintainability, or scalability?
- ✅ Is this a violation of best practices?
- ✅ Could this become critical if left unaddressed?
**Example:**
```json
{
"severity": "warning",
"title": "Database connections not pooled",
"description": "New database connection created for each request.",
"impact": "High latency and connection exhaustion under load",
"recommendation": "Implement connection pooling"
}
```
---
### Info Severity
**Use for:**
- **Design patterns**: Documented architectural patterns
- **Technology stack**: Frameworks and libraries in use
- **Good practices**: Well-implemented features
- **Architectural decisions**: Strategic technical choices
- **System capabilities**: Features and functionality
**Checklist:**
- ✅ Is this neutral or positive information?
- ✅ Does this document "what is" without judgment?
- ✅ Is this useful for understanding the system?
- ✅ Is no action required?
**Example:**
```json
{
"severity": "info",
"title": "Event-driven architecture with RabbitMQ",
"description": "System uses message queues for async processing between services.",
"impact": "Enables loose coupling and horizontal scaling"
}
```
---
## Anti-Patterns to Avoid
### 1. Opinion Instead of Fact
**Bad:**
```json
{
"description": "The authentication approach is poorly designed and should be refactored."
}
```
**Good:**
```json
{
"description": "JWT tokens stored in localStorage are vulnerable to XSS attacks.",
"recommendation": "Migrate to httpOnly cookies"
}
```
---
### 2. Vague Observations
**Bad:**
```json
{
"title": "Performance issues",
"description": "The system is slow."
}
```
**Good:**
```json
{
"title": "N+1 query problem in user dashboard",
"description": "Dashboard loads user posts in a loop, executing one query per post instead of batching.",
"evidence": [{"type": "code", "location": "src/dashboard.ts:78"}]
}
```
---
### 3. Missing Evidence
**Bad:**
```json
{
"title": "Uses event-driven architecture",
"description": "The system has an event-driven design."
}
```
**Good:**
```json
{
"title": "Event-driven architecture with RabbitMQ",
"description": "System uses RabbitMQ message broker for async event processing.",
"evidence": [
{"type": "config", "location": "docker-compose.yml", "snippet": "rabbitmq:..."},
{"type": "dependency", "location": "package.json", "snippet": "\"amqplib\": \"^0.10.3\""}
]
}
```
---
### 4. Wrong Severity
**Bad:**
```json
{
"severity": "critical",
"title": "Using older version of React",
"description": "React 17 instead of React 18"
}
```
**Good:**
```json
{
"severity": "warning",
"title": "React version outdated",
"description": "Using React 17.0.2, missing React 18 performance improvements",
"recommendation": "Upgrade to React 18 for concurrent features"
}
```
---
### 5. Wrong Category Level
**Bad (C1 level):**
```json
{
"category": "code-quality",
"title": "High cyclomatic complexity in AuthService"
}
```
**Good (C1 level):**
```json
{
"category": "architecture",
"title": "Microservices architecture with API gateway"
}
```
*Code quality is a C3 category; architecture is appropriate for C1*
---
## Cross-Level Consistency
### Observation Granularity
**C1 observations** should be high-level:
- System-wide patterns
- External integrations
- System boundaries
- Actor interactions
**C2 observations** should be mid-level:
- Container technologies
- Inter-container communication
- Container deployment
- Container-level performance
**C3 observations** should be detailed:
- Code patterns
- Component structure
- Implementation details
- Code quality metrics
### Avoid Duplication Across Levels
If the same observation applies to multiple levels, document it at the **highest appropriate level** and reference it at lower levels.
**Example:**
- C1: "System uses PostgreSQL for data persistence"
- C2: "API container connects to PostgreSQL database"
- C3: Don't repeat—focus on component-specific details like query patterns
---
## Validation Requirements
### Required Field Validation
1. **ID format**: Must match `^obs-[a-z0-9-]+$`
-`obs-event-driven-arch`
-`OBS-001`, `observation1`
2. **Category**: Must be valid for the C4 level
- C1: 9 categories (architecture, integration, boundaries, ...)
- C2: 12 categories (technology, runtime, communication, ...)
- C3: 13 categories (design-patterns, code-structure, dependencies, ...)
3. **Severity**: Must be `critical`, `warning`, or `info`
4. **Title**: Max 100 characters, descriptive
5. **Description**: Min 10 characters, detailed
### Evidence Validation
1. **Type**: Must be valid evidence type
2. **Location**: Required, should be a valid path
3. **Snippet**: Optional but recommended
4. **Note**: Optional but helpful for context
### Recommendation Validation
- **Critical** observations MUST include `recommendation`
- **Warning** observations SHOULD include `recommendation`
- **Info** observations MAY include `recommendation`
---
## Additional Resources
- **[examples.md](examples.md)** - 30+ complete examples
- **[categories.md](categories.md)** - Category quick reference
- **Validation scripts** - `${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-*.py`
- **Type definitions** - `${CLAUDE_PLUGIN_ROOT}/validation/templates/types-observations.json`

View File

@@ -0,0 +1,126 @@
---
name: c4model-relations
description: Use when documenting relations, dependencies, and communications between systems, containers, or components in C4 Model architecture. Invoke during dependency mapping, integration analysis, or when users mention "relations", "dependencies", "connections", "how systems communicate", "API calls", "integrations", "data flow", or need to understand inter-system/component relationships.
---
# C4 Model - Relations Documentation
## Overview
Document HOW systems, containers, and components communicate—what flows between them, in which direction, and through which protocols.
**Core Principle:** Relations describe communication and dependencies. Use level-appropriate types with active voice descriptions.
## When to Use
- Documenting system-to-system communication (C1)
- Mapping container interactions (C2)
- Describing component dependencies (C3)
- Integration analysis and dependency mapping
## When NOT to Use
- Documenting static properties → use c4model-observations
- Describing internal implementation details
- Non-architectural documentation
---
## Quick Reference
| Level | Key Fields | Common Types | Focus |
|-------|------------|--------------|-------|
| C1 | `direction`, `protocol` | http-rest, message-queue, authentication | Protocols between systems |
| C2 | `protocol`, `isAsync` | database-read-write, cache-read | Container interactions |
| C3 | `coupling` | uses, injects, implements, observes | Code-level dependencies |
**IMPORTANT:** `direction` is C1 ONLY. Never use `direction` for C2 or C3 relations.
**Type specificity:** Match type to actual operation:
- `cache-read` for read-only, `cache-write` for write-only, `cache-read-write` for both
- `database-query` for read-only, `database-read-write` for both
**Complete type definitions** → [types.md](./types.md)
---
## Relation Structure
```json
{
"id": "rel-frontend-to-api",
"target": "backend-api",
"type": "http-rest",
"description": "Sends HTTP requests to fetch user data"
}
```
**Required:** `id`, `target`, `type`, `description`
**Optional:** `protocol`, `direction` (C1), `coupling` (C3), `isAsync`, `tags`
---
## Direction and Coupling
**Direction (C1 only):**
- `outbound` - Source initiates (Frontend → API)
- `inbound` - Target initiates (Webhook → Your system)
- `bidirectional` - Both ways (WebSocket)
**Coupling (C3 only):**
- `loose` - Easily replaceable (DI, interfaces)
- `tight` - Hard to replace (inheritance, direct refs)
---
## Writing Descriptions
✅ Active voice, start with verb, be specific:
- "Sends HTTP requests to fetch user profile"
- "Reads customer records from PostgreSQL"
- "Injects UserRepository via DI"
❌ Avoid:
- "Data is sent" (passive)
- "Connection" (vague)
- "Talks to the API" (unspecific)
---
## Examples
**C1:** `{ "type": "http-rest", "direction": "outbound", "protocol": "HTTP/REST" }`
**C2:** `{ "type": "database-read-write", "protocol": "PostgreSQL Wire Protocol" }`
**C3:** `{ "type": "uses", "coupling": "loose" }`
**45+ examples** → [examples.md](./examples.md)
---
## Common Mistakes
1. **Wrong level types** - Use C1 types at C1, C3 types at C3
2. **Using direction for C2/C3** - `direction` is C1 ONLY, never use for containers or components
3. **Wrong access type** - Use `cache-read` for read-only, not `cache-read-write`
4. **Missing direction/coupling** - Required for C1/C3 respectively
5. **Passive voice** - Always use active voice descriptions
6. **Generic types** - Use `http-rest` not `http`
7. **Invalid targets** - Ensure target entity exists
---
## Integration
**Commands:** `/melly-c1-systems`, `/melly-c2-containers`, `/melly-c3-components`
**Output:** `systems[].relations[]`, `containers[].relations[]`, `components[].relations[]`
**Validation:** `python ${CLAUDE_PLUGIN_ROOT}/validation/scripts/validate-c{1,2,3}-*.py`
---
## Detailed Documentation
- [types.md](./types.md) - Complete type definitions
- [reference.md](./reference.md) - Methodology and best practices
- [examples.md](./examples.md) - 45+ real-world examples

View File

@@ -0,0 +1,870 @@
# C4 Model Relations - Comprehensive Examples
## Overview
This document provides comprehensive examples of relations across all three C4 Model levels, covering all major relation types.
**Usage:** Reference these examples when documenting your own architecture relations.
---
## Table of Contents
1. [C1 System Context Examples](#c1-system-context-examples)
2. [C2 Container Examples](#c2-container-examples)
3. [C3 Component Examples](#c3-component-examples)
4. [Cross-Level Examples](#cross-level-examples)
---
## C1 System Context Examples
### Example 1: REST API Communication
```json
{
"id": "rel-webapp-to-api",
"target": "backend-api",
"type": "http-rest",
"description": "Sends HTTP requests to fetch and update customer data",
"protocol": "HTTP/REST",
"direction": "outbound",
"isAsync": true,
"tags": ["api", "rest", "critical"]
}
```
**Context:** Web application calls backend API for all data operations
**Direction:** Outbound (web app initiates requests)
**Protocol:** RESTful HTTP
---
### Example 2: External Payment Gateway
```json
{
"id": "rel-api-to-payment",
"target": "stripe-payment-gateway",
"type": "external-api",
"description": "Processes payments via Stripe API for customer transactions",
"protocol": "HTTPS/REST",
"direction": "bidirectional",
"isAsync": true,
"tags": ["payment", "external", "stripe", "critical"]
}
```
**Context:** E-commerce system integrates with Stripe for payments
**Direction:** Bidirectional (API calls Stripe, Stripe sends webhooks)
**Protocol:** HTTPS with REST and webhook callbacks
---
### Example 3: Message Queue Processing
```json
{
"id": "rel-worker-to-queue",
"target": "rabbitmq",
"type": "message-queue",
"description": "Consumes background job messages for email notifications and data processing",
"protocol": "AMQP",
"direction": "inbound",
"isAsync": true,
"tags": ["async", "queue", "rabbitmq", "worker"]
}
```
**Context:** Worker service consumes messages from queue
**Direction:** Inbound (queue pushes messages to worker)
**Protocol:** AMQP (RabbitMQ)
---
### Example 4: OAuth Authentication
```json
{
"id": "rel-app-to-auth",
"target": "auth0",
"type": "authentication",
"description": "Authenticates users via OAuth 2.0 with social login support",
"protocol": "OAuth 2.0",
"direction": "outbound",
"isAsync": false,
"tags": ["auth", "oauth", "security", "auth0"]
}
```
**Context:** Application uses Auth0 for user authentication
**Direction:** Outbound (app redirects to Auth0)
**Protocol:** OAuth 2.0
---
### Example 5: GraphQL API
```json
{
"id": "rel-mobile-to-graphql",
"target": "graphql-api",
"type": "http-graphql",
"description": "Queries GraphQL API for flexible data fetching with nested relations",
"protocol": "HTTP/GraphQL",
"direction": "outbound",
"isAsync": true,
"tags": ["graphql", "api", "mobile"]
}
```
**Context:** Mobile app uses GraphQL for efficient data queries
**Direction:** Outbound (mobile queries API)
**Protocol:** GraphQL over HTTP
---
### Example 6: WebSocket Real-Time Communication
```json
{
"id": "rel-chat-to-websocket",
"target": "websocket-server",
"type": "websocket",
"description": "Maintains persistent WebSocket connection for real-time chat messages",
"protocol": "WebSocket (RFC 6455)",
"direction": "bidirectional",
"isAsync": true,
"tags": ["websocket", "realtime", "chat"]
}
```
**Context:** Chat application uses WebSocket for real-time messaging
**Direction:** Bidirectional (messages flow both ways)
**Protocol:** WebSocket
---
### Example 7: gRPC Microservices
```json
{
"id": "rel-gateway-to-services",
"target": "microservices-cluster",
"type": "grpc",
"description": "Communicates with microservices via gRPC for high-performance RPC calls",
"protocol": "HTTP/2 gRPC",
"direction": "outbound",
"isAsync": false,
"tags": ["grpc", "microservices", "rpc"]
}
```
**Context:** API gateway calls microservices via gRPC
**Direction:** Outbound (gateway calls services)
**Protocol:** gRPC over HTTP/2
---
### Example 8: Event Stream Processing
```json
{
"id": "rel-analytics-to-kafka",
"target": "kafka-cluster",
"type": "event-stream",
"description": "Consumes real-time clickstream events for analytics processing",
"protocol": "Kafka Protocol",
"direction": "inbound",
"isAsync": true,
"tags": ["kafka", "streaming", "analytics"]
}
```
**Context:** Analytics system processes events from Kafka
**Direction:** Inbound (Kafka streams events to analytics)
**Protocol:** Kafka streaming protocol
---
### Example 9: Database Connection
```json
{
"id": "rel-app-to-database",
"target": "postgres-cluster",
"type": "database-connection",
"description": "Connects to PostgreSQL cluster for persistent data storage",
"protocol": "PostgreSQL Wire Protocol",
"direction": "outbound",
"isAsync": false,
"tags": ["database", "postgres", "storage"]
}
```
**Context:** Application system connects to database system
**Direction:** Outbound (app queries database)
**Protocol:** PostgreSQL protocol
---
### Example 10: Email Service Integration
```json
{
"id": "rel-notif-to-sendgrid",
"target": "sendgrid",
"type": "external-api",
"description": "Sends transactional emails via SendGrid API",
"protocol": "HTTPS/REST",
"direction": "outbound",
"isAsync": true,
"tags": ["email", "sendgrid", "notifications"]
}
```
**Context:** Notification system sends emails via SendGrid
**Direction:** Outbound (system calls SendGrid API)
**Protocol:** HTTPS REST API
---
### Example 11: File Transfer
```json
{
"id": "rel-backup-to-s3",
"target": "aws-s3",
"type": "file-transfer",
"description": "Transfers backup files to S3 for long-term storage",
"protocol": "HTTPS S3 API",
"direction": "outbound",
"isAsync": true,
"tags": ["backup", "s3", "storage"]
}
```
**Context:** Backup system uploads files to S3
**Direction:** Outbound (backup pushes to S3)
**Protocol:** S3 API over HTTPS
---
### Example 12: Read Replica Access
```json
{
"id": "rel-reporting-to-replica",
"target": "postgres-read-replica",
"type": "database-query",
"description": "Queries read replica for reporting without impacting primary database",
"protocol": "PostgreSQL Wire Protocol",
"direction": "outbound",
"isAsync": false,
"tags": ["database", "reporting", "read-replica"]
}
```
**Context:** Reporting system queries read-only replica
**Direction:** Outbound (reporting queries replica)
**Protocol:** PostgreSQL (read-only)
---
## C2 Container Examples
### Example 1: SPA to API
```json
{
"id": "rel-spa-to-api",
"target": "express-api",
"type": "http-rest",
"description": "Fetches user data and submits forms via REST API endpoints",
"protocol": "HTTP/REST",
"isAsync": true,
"tags": ["rest", "ajax", "fetch", "spa"]
}
```
**Context:** React SPA calls Express backend
**Container Flow:** Browser (SPA) → Server (API)
**Operations:** GET, POST, PUT, DELETE
---
### Example 2: API to PostgreSQL
```json
{
"id": "rel-api-to-postgres",
"target": "postgres-container",
"type": "database-read-write",
"description": "Reads and writes application data using Sequelize ORM",
"protocol": "PostgreSQL Wire Protocol",
"isAsync": false,
"tags": ["database", "postgres", "sql", "sequelize"]
}
```
**Context:** Express API accesses PostgreSQL database
**Container Flow:** API Server → Database Container
**Operations:** Full CRUD via ORM
---
### Example 3: API to Redis Cache
```json
{
"id": "rel-api-to-redis",
"target": "redis-container",
"type": "cache-read-write",
"description": "Caches frequently accessed data to improve response times",
"protocol": "Redis Protocol (RESP)",
"isAsync": false,
"tags": ["cache", "redis", "performance"]
}
```
**Context:** API caches query results in Redis
**Container Flow:** API Server → Cache Container
**Operations:** GET, SET, DEL
---
### Example 4: Worker to Message Queue
```json
{
"id": "rel-worker-to-queue",
"target": "rabbitmq-container",
"type": "message-subscribe",
"description": "Consumes email notification jobs from RabbitMQ queue",
"protocol": "AMQP",
"isAsync": true,
"tags": ["queue", "worker", "email", "rabbitmq"]
}
```
**Context:** Worker consumes messages from RabbitMQ
**Container Flow:** Worker Container ← Message Queue Container
**Pattern:** Consumer (pull model)
---
### Example 5: API to Message Queue
```json
{
"id": "rel-api-to-queue",
"target": "rabbitmq-container",
"type": "message-publish",
"description": "Publishes order completion events for async processing",
"protocol": "AMQP",
"isAsync": true,
"tags": ["queue", "publisher", "async"]
}
```
**Context:** API publishes events to queue
**Container Flow:** API Server → Message Queue Container
**Pattern:** Publisher (push model)
---
### Example 6: Frontend to GraphQL
```json
{
"id": "rel-frontend-to-graphql",
"target": "graphql-server",
"type": "http-graphql",
"description": "Queries GraphQL API with Apollo Client for nested data fetching",
"protocol": "HTTP/GraphQL",
"isAsync": true,
"tags": ["graphql", "apollo", "queries"]
}
```
**Context:** Next.js frontend uses GraphQL API
**Container Flow:** Frontend Container → GraphQL Server Container
**Operations:** Query, Mutation
---
### Example 7: API to S3 Storage
```json
{
"id": "rel-api-to-s3",
"target": "aws-s3",
"type": "file-write",
"description": "Uploads user-generated images to S3 bucket",
"protocol": "HTTPS S3 API",
"isAsync": true,
"tags": ["s3", "upload", "images"]
}
```
**Context:** API uploads files to S3
**Container Flow:** API Server → S3 Storage
**Operations:** PutObject, DeleteObject
---
### Example 8: Worker Reading Files
```json
{
"id": "rel-worker-to-s3",
"target": "aws-s3",
"type": "file-read",
"description": "Reads CSV files from S3 for batch processing",
"protocol": "HTTPS S3 API",
"isAsync": true,
"tags": ["s3", "batch", "csv"]
}
```
**Context:** Background worker processes files from S3
**Container Flow:** Worker Container → S3 Storage
**Operations:** GetObject, ListObjects
---
### Example 9: Browser to CDN
```json
{
"id": "rel-browser-to-cdn",
"target": "cloudfront-cdn",
"type": "cdn-fetch",
"description": "Fetches static assets (JS, CSS, images) from CDN",
"protocol": "HTTPS",
"isAsync": true,
"tags": ["cdn", "static", "assets"]
}
```
**Context:** Browser loads assets from CloudFront
**Container Flow:** Browser → CDN
**Operations:** GET (cached assets)
---
### Example 10: WebSocket Server
```json
{
"id": "rel-client-to-websocket",
"target": "websocket-server",
"type": "websocket",
"description": "Maintains WebSocket connection for real-time notifications",
"protocol": "WebSocket Protocol",
"isAsync": true,
"tags": ["websocket", "realtime", "notifications"]
}
```
**Context:** Web client connects to WebSocket server
**Container Flow:** Browser ↔ WebSocket Server (bidirectional)
**Operations:** Send, Receive messages
---
### Example 11: Service to MySQL
```json
{
"id": "rel-service-to-mysql",
"target": "mysql-container",
"type": "database-connection",
"description": "Connects to MySQL database for general data operations",
"protocol": "MySQL Wire Protocol",
"isAsync": false,
"tags": ["database", "mysql", "generic"]
}
```
**Context:** Service container accesses MySQL
**Container Flow:** Service Container → MySQL Container
**Operations:** Mixed read/write
---
### Example 12: Auth Service to Session Cache
```json
{
"id": "rel-auth-to-cache",
"target": "redis-container",
"type": "cache-access",
"description": "Accesses session cache for user authentication state",
"protocol": "Redis Protocol",
"isAsync": false,
"tags": ["cache", "session", "auth"]
}
```
**Context:** Auth service stores sessions in Redis
**Container Flow:** Auth Container → Redis Container
**Operations:** Session management
---
## C3 Component Examples
### Example 1: Controller Uses Service
```json
{
"id": "rel-controller-to-service",
"target": "user-service",
"type": "uses",
"description": "Delegates business logic operations to UserService",
"coupling": "loose",
"tags": ["service-layer", "delegation"]
}
```
**Context:** Layered architecture pattern
**Component Flow:** UserController → UserService
**Pattern:** Service layer delegation
---
### Example 2: Service Injects Repository
```json
{
"id": "rel-service-to-repo",
"target": "user-repository",
"type": "injects",
"description": "Injects UserRepository via dependency injection for data access",
"coupling": "loose",
"tags": ["di", "repository-pattern"]
}
```
**Context:** Dependency injection pattern
**Component Flow:** UserService ← UserRepository (injected)
**Pattern:** Constructor injection
---
### Example 3: Auth Provides Context
```json
{
"id": "rel-auth-to-user",
"target": "user-component",
"type": "provides",
"description": "Provides authenticated user information to consuming components",
"coupling": "loose",
"tags": ["auth", "context", "provider"]
}
```
**Context:** React context provider pattern
**Component Flow:** AuthProvider → Consumers
**Pattern:** Provider/Consumer
---
### Example 4: Validator Extends Base
```json
{
"id": "rel-validator-extends-base",
"target": "base-validator",
"type": "inherits",
"description": "Extends base validation logic with custom rules",
"coupling": "tight",
"tags": ["inheritance", "validation"]
}
```
**Context:** OOP inheritance hierarchy
**Component Flow:** CustomValidator extends BaseValidator
**Pattern:** Classical inheritance
---
### Example 5: Payment Observes Order Events
```json
{
"id": "rel-payment-observes-order",
"target": "order-component",
"type": "observes",
"description": "Listens to order completion events to trigger payment processing",
"coupling": "loose",
"tags": ["event", "observer-pattern", "payment"]
}
```
**Context:** Observer/subscriber pattern
**Component Flow:** PaymentService ← OrderService (events)
**Pattern:** Event-driven
---
### Example 6: Order Notifies Subscribers
```json
{
"id": "rel-order-notifies-payment",
"target": "payment-component",
"type": "notifies",
"description": "Emits order completion events to registered subscribers",
"coupling": "loose",
"tags": ["event", "publisher", "orders"]
}
```
**Context:** Publisher pattern
**Component Flow:** OrderService → Subscribers
**Pattern:** Event emitter
---
### Example 7: Service Implements Interface
```json
{
"id": "rel-service-implements-interface",
"target": "repository-interface",
"type": "implements",
"description": "Implements IUserRepository contract for data access abstraction",
"coupling": "loose",
"tags": ["interface", "contract", "di"]
}
```
**Context:** Interface-based programming
**Component Flow:** UserRepository implements IUserRepository
**Pattern:** Dependency inversion
---
### Example 8: Logger Subscribes to Errors
```json
{
"id": "rel-logger-subscribes-errors",
"target": "error-handler",
"type": "event-subscriber",
"description": "Subscribes to error events for centralized logging",
"coupling": "loose",
"tags": ["event", "logging", "observer"]
}
```
**Context:** Error handling with observers
**Component Flow:** Logger ← ErrorHandler (events)
**Pattern:** Event subscription
---
### Example 9: Controller Calls Service Methods
```json
{
"id": "rel-controller-calls-service",
"target": "order-service",
"type": "calls",
"description": "Invokes createOrder and getOrderById methods directly",
"coupling": "tight",
"tags": ["method-call", "direct-call"]
}
```
**Context:** Direct method invocation
**Component Flow:** OrderController → OrderService.createOrder()
**Pattern:** Direct coupling
---
### Example 10: Component Composes Others
```json
{
"id": "rel-order-composes-items",
"target": "order-item",
"type": "composes",
"description": "Composes OrderItem instances as integral parts of Order",
"coupling": "tight",
"tags": ["composition", "has-a"]
}
```
**Context:** Object composition
**Component Flow:** Order has OrderItem[]
**Pattern:** Composition (strong has-a)
---
### Example 11: Component Aggregates References
```json
{
"id": "rel-cart-aggregates-products",
"target": "product",
"type": "aggregates",
"description": "Aggregates Product references without owning them",
"coupling": "moderate",
"tags": ["aggregation", "reference"]
}
```
**Context:** Object aggregation
**Component Flow:** ShoppingCart has Product[] (references)
**Pattern:** Aggregation (weak has-a)
---
### Example 12: Component Imports Utilities
```json
{
"id": "rel-service-imports-utils",
"target": "date-utils",
"type": "imports",
"description": "Imports date formatting utilities via ES6 import",
"coupling": "tight",
"tags": ["import", "utilities"]
}
```
**Context:** Module imports
**Component Flow:** OrderService imports { formatDate } from './utils'
**Pattern:** ES6 modules
---
### Example 13: Facade Delegates to Subsystems
```json
{
"id": "rel-facade-delegates",
"target": "subsystems",
"type": "delegates",
"description": "Delegates complex operations to multiple subsystems",
"coupling": "moderate",
"tags": ["facade", "delegation"]
}
```
**Context:** Facade pattern
**Component Flow:** OrderFacade → [PaymentService, InventoryService, ShippingService]
**Pattern:** Facade
---
### Example 14: Component Extends Functionality
```json
{
"id": "rel-advanced-extends-basic",
"target": "basic-search",
"type": "extends",
"description": "Extends basic search with advanced filtering and sorting",
"coupling": "tight",
"tags": ["inheritance", "extension"]
}
```
**Context:** Feature extension via inheritance
**Component Flow:** AdvancedSearch extends BasicSearch
**Pattern:** Extension
---
### Example 15: Consumer Uses Context
```json
{
"id": "rel-profile-consumes-auth",
"target": "auth-context",
"type": "consumes",
"description": "Consumes authenticated user data from AuthContext",
"coupling": "loose",
"tags": ["context", "react", "consumer"]
}
```
**Context:** React context consumer
**Component Flow:** UserProfile consumes AuthContext
**Pattern:** Context API
---
## Cross-Level Examples
### Example: Full Stack Feature
**C1 Level:**
```json
{
"source": "mobile-app",
"target": "backend-api",
"type": "http-rest",
"direction": "outbound"
}
```
**C2 Level:**
```json
{
"source": "react-native-app",
"target": "express-api",
"type": "http-rest"
},
{
"source": "express-api",
"target": "postgres-db",
"type": "database-read-write"
}
```
**C3 Level:**
```json
{
"source": "user-controller",
"target": "user-service",
"type": "uses",
"coupling": "loose"
},
{
"source": "user-service",
"target": "user-repository",
"type": "injects",
"coupling": "loose"
}
```
---
## Summary
These examples demonstrate:
- **C1 Relations:** System-to-system communication patterns
- **C2 Relations:** Container-to-container interactions
- **C3 Relations:** Component-level dependencies and design patterns
Each example includes:
- Unique ID
- Target entity
- Relation type
- Clear description
- Appropriate metadata (direction, protocol, coupling)
- Tags for categorization
Use these as templates for documenting your own architecture relations.
---
**Version:** 1.0.0
**Last Updated:** 2025-11-17

View File

@@ -0,0 +1,421 @@
# C4 Model Relations - Detailed Reference
## Table of Contents
1. [Protocol Documentation Guidelines](#protocol-documentation-guidelines)
2. [Direction vs Coupling](#direction-vs-coupling)
3. [Best Practices per Level](#best-practices-per-level)
4. [Graph Validity Rules](#graph-validity-rules)
5. [Common Patterns](#common-patterns)
---
## Relation Type Definitions
For complete type definitions for all C4 levels, see [types.md](./types.md).
---
## Protocol Documentation Guidelines
### When to Document Protocol
**Always include protocol for:**
- C1 system-to-system communication
- C2 container-to-container communication
- External integrations
- Any network communication
**Optional for:**
- C3 code-level dependencies (unless calling external APIs)
- In-process method calls
### Protocol Format
Use standard protocol names:
**Good:**
- `HTTP/REST`
- `HTTP/2 gRPC`
- `PostgreSQL Wire Protocol`
- `AMQP`
- `OAuth 2.0`
**Bad:**
- `rest` (too vague)
- `http` (specify REST, GraphQL, etc.)
- `database` (specify PostgreSQL, MySQL, etc.)
### Protocol Details to Include
For **HTTP-based protocols:**
- HTTP version (HTTP/1.1, HTTP/2)
- API style (REST, GraphQL, RPC)
- Authentication method
- Content type (JSON, XML, etc.)
For **Database protocols:**
- Database type (PostgreSQL, MySQL, MongoDB)
- Connection method (wire protocol, ORM)
- Authentication method
For **Messaging protocols:**
- Broker type (RabbitMQ, Kafka, SQS)
- Protocol (AMQP, Kafka Protocol)
- Pattern (pub-sub, work queue)
---
## Direction vs Coupling
### Direction (C1 Level)
**Purpose:** Describes the flow of communication between systems
#### outbound
**Definition:** Source system initiates communication
**Example:** Frontend makes HTTP requests to API
**Use when:** Source actively calls, queries, or requests from target
#### inbound
**Definition:** Target system initiates communication
**Example:** External webhook calls your API
**Use when:** Target pushes data, calls back, or triggers source
#### bidirectional
**Definition:** Communication flows both ways
**Example:** WebSocket connection with messages in both directions
**Use when:** True two-way communication (avoid overusing)
**Best Practice:** Prefer outbound/inbound over bidirectional for clarity. Create two separate relations if needed.
### Coupling (C3 Level)
**Purpose:** Describes strength of dependency between components
#### loose
**Definition:** Minimal dependency, easily replaceable
**Characteristics:**
- Components interact through interfaces or abstractions
- Easy to test (can use mocks)
- Easy to swap implementations
- Changes in one component don't force changes in another
**Examples:**
- Dependency injection
- Interface-based dependencies
- Event-driven communication
- Plugin architectures
#### tight
**Definition:** Strong dependency, hard to replace
**Characteristics:**
- Direct class references
- Hard to test without real implementation
- Hard to swap implementations
- Changes cascade between components
**Examples:**
- Direct class instantiation
- Class inheritance
- Static method calls
- Global state dependencies
**Best Practice:** Prefer loose coupling. Document tight coupling as potential refactoring opportunity.
---
## Best Practices per Level
### C1 System Context Best Practices
1. **Focus on protocols**
- Always specify communication protocol
- Include authentication method for external relations
- Document sync vs async nature
2. **Specify direction**
- Use outbound for active calls (API requests, queries)
- Use inbound for passive receives (webhooks, callbacks)
- Avoid bidirectional unless truly necessary
3. **Document external integrations**
- Mark external services clearly
- Include vendor name (Stripe, SendGrid, etc.)
- Note criticality for business operations
4. **Group similar relations**
- One relation for "Frontend → API" covering all endpoints
- Don't create separate relations for each API endpoint
### C2 Container Best Practices
1. **Be specific about API style**
- Use `http-rest` not just `http`
- Use `http-graphql` for GraphQL
- Distinguish between REST and RPC
2. **Differentiate read vs write**
- Use `database-query` for read-only
- Use `database-write` for write-only
- Use `database-read-write` for both
3. **Document cache patterns**
- Specify cache operations (read, write, both)
- Include eviction strategy if relevant
- Note cache hit/miss criticality
4. **Show message patterns**
- Use `message-publish` for producers
- Use `message-subscribe` for consumers
- Document topic/queue names in description
### C3 Component Best Practices
1. **Assess coupling**
- Always include coupling field
- Prefer loose coupling
- Document tight coupling as technical debt
2. **Document design patterns**
- Use `injects` for DI
- Use `observes`/`notifies` for Observer pattern
- Use `implements` for Strategy/Interface patterns
3. **Show dependency direction**
- High-level → low-level (Controller → Service → Repository)
- Abstract → concrete (Interface ← Implementation)
- Stable → volatile
4. **Highlight circular dependencies**
- Flag as warning in observations
- Consider refactoring
- Document workaround if intentional
---
## Graph Validity Rules
### Referential Integrity
**Rule:** All relation targets must reference valid entity IDs
**Validation:**
```python
# Pseudo-code
for relation in entity.relations:
if relation.target not in valid_entity_ids:
raise ValidationError(f"Invalid target: {relation.target}")
```
**Examples:**
✅ Valid:
```json
{
"id": "rel-api-to-db",
"target": "postgres-db", // postgres-db exists in containers list
"type": "database-read-write"
}
```
❌ Invalid:
```json
{
"id": "rel-api-to-db",
"target": "mysql-db", // mysql-db doesn't exist
"type": "database-read-write"
}
```
### No Self-References
**Rule:** Source cannot equal target
✅ Valid:
```json
{ "source": "api-service", "target": "database" }
```
❌ Invalid:
```json
{ "source": "api-service", "target": "api-service" }
```
### Cross-Level References
**Rule:** Relations can reference entities at same or different levels
**C1 → C1:** System to system ✅
**C2 → C2:** Container to container within same system ✅
**C2 → C1:** Container to external system ✅
**C3 → C3:** Component to component within same container ✅
**C3 → C2:** Component to external container ✅
### Bidirectional Relations
**Rule:** If bidirectional, both entities should document the relation
**Best Practice:** Prefer two unidirectional relations over one bidirectional
✅ Preferred:
```json
// In entity A
{ "target": "B", "type": "http-rest", "direction": "outbound" }
// In entity B
{ "target": "A", "type": "websocket", "direction": "inbound" }
```
❌ Less clear:
```json
// In entity A
{ "target": "B", "type": "http-rest", "direction": "bidirectional" }
// No corresponding relation in B
```
### Dangling References
**Rule:** All targets should eventually resolve to a documented entity
**Exceptions:**
- External systems not in your control
- Mark these clearly in description
- Use `external-api` or similar type
---
## Common Patterns
### Frontend-Backend Pattern
**C1 Level:**
```json
{
"source": "web-application",
"target": "backend-api",
"type": "http-rest",
"direction": "outbound",
"protocol": "HTTP/REST"
}
```
**C2 Level:**
```json
{
"source": "react-spa",
"target": "express-api",
"type": "http-rest",
"protocol": "HTTP/REST",
"isAsync": true
}
```
### API-Database Pattern
**C2 Level:**
```json
{
"source": "express-api",
"target": "postgres-db",
"type": "database-read-write",
"protocol": "PostgreSQL Wire Protocol",
"isAsync": false
}
```
### Event-Driven Pattern
**C1 Level:**
```json
{
"source": "order-service",
"target": "message-queue",
"type": "message-queue",
"direction": "outbound",
"protocol": "AMQP",
"isAsync": true
}
```
**C2 Level:**
```json
{
"source": "order-container",
"target": "rabbitmq",
"type": "message-publish",
"protocol": "AMQP"
},
{
"source": "notification-worker",
"target": "rabbitmq",
"type": "message-subscribe",
"protocol": "AMQP"
}
```
### Layered Architecture Pattern (C3)
```json
{
"source": "user-controller",
"target": "user-service",
"type": "uses",
"coupling": "loose"
},
{
"source": "user-service",
"target": "user-repository",
"type": "injects",
"coupling": "loose"
}
```
### Observer Pattern (C3)
```json
{
"source": "order-service",
"target": "order-events",
"type": "notifies",
"coupling": "loose"
},
{
"source": "payment-service",
"target": "order-events",
"type": "observes",
"coupling": "loose"
}
```
---
## Validation Checklist
Before finalizing relations documentation:
- [ ] All relation IDs are unique
- [ ] All targets reference valid entity IDs
- [ ] No self-references (source ≠ target)
- [ ] Direction specified for C1 relations
- [ ] Coupling specified for C3 relations
- [ ] Protocol documented for network communication
- [ ] Descriptions in active voice
- [ ] Types match C4 level (C1 types at C1, etc.)
- [ ] isAsync set appropriately
- [ ] Tags use lowercase kebab-case
- [ ] Critical relations tagged appropriately
---
## References
- **Type Definitions:** [types.md](./types.md)
- **Examples:** [examples.md](./examples.md)
- **Main Skill:** [SKILL.md](./SKILL.md)
- **Validation Scripts:** `${CLAUDE_PLUGIN_ROOT}/validation/scripts/`
- **Schema Documentation:** `/docs/observations-relations-schema.md`
---
**Version:** 1.0.0
**Last Updated:** 2025-11-17

View File

@@ -0,0 +1,498 @@
# C4 Model Relation Types - Complete Reference
## Overview
This document provides comprehensive definitions for all relation types across C1, C2, and C3 levels of the C4 Model.
**Usage:** Reference this document when choosing the appropriate relation type for your architecture documentation.
---
## Table of Contents
1. [C1 System Context Relation Types](#c1-system-context-relation-types)
2. [C2 Container Relation Types](#c2-container-relation-types)
3. [C3 Component Relation Types](#c3-component-relation-types)
4. [Type Selection Guidelines](#type-selection-guidelines)
---
## C1 System Context Relation Types
### Network Communication Types
#### http / https / http-rest
**Description:** HTTP/HTTPS communication, typically RESTful APIs
**When to use:** REST APIs, web requests, standard HTTP communication
**Protocols:** HTTP/1.1, HTTP/2, HTTP/3
**Direction:** Usually outbound (client calls server)
**Example:** Web application calls backend REST API for data
#### http-graphql
**Description:** GraphQL API communication over HTTP
**When to use:** GraphQL queries and mutations
**Protocols:** HTTP with GraphQL
**Direction:** Usually outbound (client queries server)
**Example:** Frontend queries GraphQL API for flexible data fetching
#### grpc
**Description:** gRPC remote procedure calls
**When to use:** High-performance RPC, microservice communication
**Protocols:** HTTP/2 with Protocol Buffers
**Direction:** Usually outbound (client calls service)
**Example:** Microservices communicate via gRPC for low latency
#### graphql
**Description:** GraphQL protocol (alternative to http-graphql)
**When to use:** When emphasizing GraphQL over HTTP transport
**Example:** Same as http-graphql
#### websocket
**Description:** Bidirectional real-time communication
**When to use:** Live updates, chat, real-time notifications
**Protocols:** WebSocket Protocol (RFC 6455)
**Direction:** Bidirectional
**Example:** Chat application maintains persistent WebSocket connection
#### rpc
**Description:** Generic remote procedure call
**When to use:** Custom RPC protocols, legacy RPC systems
**Example:** XML-RPC, JSON-RPC communication
#### soap
**Description:** SOAP web services
**When to use:** Enterprise integrations, legacy systems
**Protocols:** SOAP over HTTP
**Example:** Integration with enterprise ERP system
### Messaging Types
#### message-queue
**Description:** Asynchronous messaging via message broker
**When to use:** Event-driven architectures, async processing, decoupled systems
**Protocols:** AMQP, Kafka Protocol, SQS API
**Direction:** Outbound (publish) or Inbound (consume)
**Example:** Order service publishes events to RabbitMQ for async processing
#### event-stream
**Description:** Event streaming platforms
**When to use:** Real-time data pipelines, event sourcing, log aggregation
**Protocols:** Kafka, Amazon Kinesis, Azure Event Hubs
**Example:** Analytics system consumes clickstream events from Kafka
### Data Access Types
#### database-connection
**Description:** Direct database access at system level
**When to use:** System-to-database communication, primary database
**Protocols:** PostgreSQL, MySQL, MongoDB protocols
**Direction:** Outbound (system queries database)
**Example:** Application system connects to PostgreSQL database
#### database-query
**Description:** Read-only database access
**When to use:** Read replicas, reporting systems, analytics
**Protocols:** SQL protocols (SELECT only)
**Direction:** Outbound
**Example:** Analytics dashboard queries PostgreSQL read replica
### Integration Types
#### authentication
**Description:** Authentication and authorization flows
**When to use:** Login flows, SSO, OAuth integrations
**Protocols:** OAuth 2.0, SAML, OpenID Connect
**Direction:** Outbound (system authenticates with provider)
**Example:** Web application authenticates users via Auth0
#### external-api
**Description:** Third-party API integration
**When to use:** Payment gateways, SaaS services, external data providers
**Protocols:** REST, SOAP, GraphQL, proprietary
**Direction:** Outbound (your system calls external API)
**Example:** E-commerce system processes payments via Stripe API
### Other Types
#### file-transfer
**Description:** File transfer protocols
**When to use:** File uploads, downloads, FTP, SFTP
**Protocols:** FTP, SFTP, SCP, HTTP multipart
**Example:** Backup system transfers files to remote storage via SFTP
#### smtp
**Description:** Email protocol
**When to use:** Email sending
**Protocols:** SMTP
**Example:** System sends transactional emails via SMTP
---
## C2 Container Relation Types
### API Communication Types
#### http-rest
**Description:** RESTful HTTP API calls between containers
**When to use:** Frontend to backend, service-to-service REST communication
**Methods:** GET, POST, PUT, DELETE, PATCH
**Typical containers:** SPA → API, API → Microservice
**Example:** React SPA calls Express API endpoints
#### http-graphql
**Description:** GraphQL queries between containers
**When to use:** Frontend GraphQL queries, flexible data fetching
**Methods:** Query, Mutation, Subscription
**Typical containers:** Apollo Client → GraphQL Server
**Example:** Next.js app queries GraphQL API
#### grpc
**Description:** gRPC calls between containers
**When to use:** High-performance inter-service communication
**Typical containers:** Microservice → Microservice
**Example:** Order service calls Inventory service via gRPC
#### websocket
**Description:** Real-time bidirectional communication
**When to use:** Live updates, real-time collaboration, push notifications
**Typical containers:** Browser → WebSocket Server
**Example:** Chat client maintains WebSocket connection to server
### Database Access Types
#### database-query
**Description:** Read-only database operations
**When to use:** SELECT queries, read replicas, reporting
**Operations:** SELECT
**Typical containers:** API → Read Replica, Analytics → Database
**Example:** API container reads user data from PostgreSQL read replica
#### database-write
**Description:** Write-only database operations
**When to use:** INSERT, UPDATE, DELETE operations, write-specific workers
**Operations:** INSERT, UPDATE, DELETE
**Typical containers:** Worker → Database
**Example:** Log aggregator writes logs to database
#### database-read-write
**Description:** Full database access (read and write)
**When to use:** Primary API servers, application logic containers
**Operations:** SELECT, INSERT, UPDATE, DELETE
**Typical containers:** API → Primary Database
**Example:** Express API reads and writes to PostgreSQL primary
#### database-connection
**Description:** Generic database connection (use specific types above when possible)
**When to use:** When access pattern is unclear or mixed
**Example:** General database connectivity
### Cache Access Types
#### cache-read
**Description:** Read-only cache access
**When to use:** Cache lookups, GET operations
**Operations:** GET, EXISTS, TTL
**Typical containers:** API → Cache
**Example:** API reads session data from Redis
#### cache-write
**Description:** Write-only cache operations
**When to use:** Cache updates, background cache warmers
**Operations:** SET, SETEX, DEL
**Typical containers:** Worker → Cache
**Example:** Cache warmer updates frequently accessed data in Redis
#### cache-read-write
**Description:** Full cache access
**When to use:** Typical caching patterns, read-through/write-through
**Operations:** GET, SET, DEL, INCR, DECR
**Typical containers:** API → Redis
**Example:** API caches database query results in Redis
#### cache-access
**Description:** Generic cache access (use specific types above when possible)
**When to use:** When access pattern is unclear
**Example:** General cache connectivity
### Message Queue Types
#### message-publish
**Description:** Publishes messages to queue or topic
**When to use:** Event producers, async job creators
**Patterns:** Pub-sub, work queue
**Typical containers:** API → Queue, Service → Event Bus
**Example:** Order API publishes order-created events to RabbitMQ
#### message-subscribe / message-consumer
**Description:** Consumes messages from queue or topic
**When to use:** Event consumers, background workers
**Patterns:** Pub-sub, work queue
**Typical containers:** Worker → Queue
**Example:** Email worker consumes notification jobs from SQS
**Note:** `message-consumer` is an alias for `message-subscribe`
### Storage Types
#### file-read
**Description:** Reads files from storage system
**When to use:** File processing, data import, asset loading
**Typical containers:** Worker → S3, API → File Storage
**Example:** Image processor reads uploaded files from S3
#### file-write
**Description:** Writes files to storage system
**When to use:** File uploads, data export, log writing
**Typical containers:** API → S3, Worker → File Storage
**Example:** API uploads user profile images to S3
#### cdn-fetch
**Description:** Fetches static assets from CDN
**When to use:** Asset delivery, static resource loading
**Typical containers:** Browser → CDN
**Example:** Web app fetches CSS/JS/images from CloudFront
### Other Types
#### stream
**Description:** Streaming data transfer
**When to use:** Video/audio streaming, large file transfers
**Example:** Video player streams content from media server
---
## C3 Component Relation Types
### Dependency Types
#### dependency
**Description:** General dependency relationship
**When to use:** Component depends on another for functionality
**Coupling:** Varies (document as loose or tight)
**Typical usage:** Any component dependency
**Example:** Controller depends on Service for business logic
#### uses
**Description:** Uses another component's functionality
**When to use:** Component actively uses another's methods or features
**Coupling:** Loose to moderate
**Typical usage:** Service uses Repository, Controller uses Service
**Example:** UserController uses UserService for user operations
#### calls
**Description:** Directly invokes methods on another component
**When to use:** Direct method calls, function invocation
**Coupling:** Tight
**Typical usage:** Any direct method invocation
**Example:** Service calls specific repository methods
### Object-Oriented Types
#### inherits / extends
**Description:** Class inheritance (is-a relationship)
**When to use:** OOP inheritance hierarchies
**Coupling:** Tight
**Typical usage:** Class extends base class
**Example:** UserController extends BaseController
**Note:** Both `inherits` and `extends` are valid
#### implements / interface-implementation
**Description:** Implements an interface or contract
**When to use:** Interface implementation, polymorphism
**Coupling:** Loose
**Typical usage:** Class implements interface
**Example:** UserRepository implements IUserRepository
**Note:** Both `implements` and `interface-implementation` are valid
#### composes
**Description:** Composition relationship (has-a, strong)
**When to use:** Component contains another as integral part
**Coupling:** Tight
**Typical usage:** Object composition
**Example:** Order composes OrderItem instances
#### aggregates
**Description:** Aggregation relationship (has-a, weak)
**When to use:** Component references another but doesn't own it
**Coupling:** Moderate
**Typical usage:** Object aggregation
**Example:** ShoppingCart aggregates Product references
### Dependency Injection Types
#### injects
**Description:** Dependency injection
**When to use:** DI frameworks, constructor/setter injection
**Coupling:** Loose
**Typical usage:** Service receives dependencies via DI container
**Example:** UserService receives UserRepository via constructor injection
#### provides
**Description:** Provides data or functionality to consumers
**When to use:** Provider pattern, dependency providers
**Coupling:** Loose
**Typical usage:** DI providers, context providers
**Example:** AuthProvider provides authenticated user context
#### consumes
**Description:** Consumes data or functionality from provider
**When to use:** Consumer pattern, dependency consumers
**Coupling:** Loose
**Typical usage:** Component consumes from provider
**Example:** UserProfile consumes auth context from AuthProvider
### Event-Driven Types
#### observes / event-subscriber
**Description:** Observer pattern - listens to events
**When to use:** Event listeners, subscribers, reactive patterns
**Coupling:** Loose
**Typical usage:** Event-driven architectures
**Example:** Logger observes error events from ErrorHandler
**Note:** Both `observes` and `event-subscriber` are valid
#### notifies / event-publisher
**Description:** Publishes events or notifications
**When to use:** Event emitters, publishers, observable patterns
**Coupling:** Loose
**Typical usage:** Event-driven architectures
**Example:** OrderService notifies subscribers when order is placed
**Note:** Both `notifies` and `event-publisher` are valid
### Other Types
#### imports
**Description:** Direct ES6/CommonJS module import
**When to use:** JavaScript/TypeScript module imports
**Coupling:** Tight
**Typical usage:** Any module import
**Example:** Component imports utility functions
#### delegates
**Description:** Delegates operations to another component
**When to use:** Delegation pattern, facades
**Coupling:** Moderate
**Typical usage:** Facade pattern, delegation
**Example:** UserFacade delegates operations to multiple subsystems
---
## Type Selection Guidelines
### Choosing Between Similar Types
#### http vs http-rest vs http-graphql
- Use **`http-rest`** for RESTful APIs (preferred)
- Use **`http-graphql`** for GraphQL APIs (preferred)
- Use **`http`** only when protocol is unclear (avoid if possible)
#### database-connection vs database-query vs database-read-write
- Use **`database-query`** for read-only access (SELECT)
- Use **`database-write`** for write-only access (INSERT/UPDATE/DELETE)
- Use **`database-read-write`** for full access (most common)
- Use **`database-connection`** only as fallback
#### cache-access vs cache-read vs cache-write
- Use **`cache-read`** for read-only (GET operations)
- Use **`cache-write`** for write-only (SET operations)
- Use **`cache-read-write`** for both (most common)
- Use **`cache-access`** only as fallback
#### message-subscribe vs message-consumer
- Both are valid (aliases)
- Use **`message-subscribe`** for clarity (preferred)
- Use **`message-consumer`** if it reads better in your context
#### implements vs interface-implementation
- Both are valid
- Use **`implements`** for brevity (preferred)
- Use **`interface-implementation`** if you need to be explicit
#### observes vs event-subscriber
- Both are valid
- Use **`observes`** for brevity (preferred)
- Use **`event-subscriber`** if you need to be explicit
#### notifies vs event-publisher
- Both are valid
- Use **`notifies`** for brevity (preferred)
- Use **`event-publisher`** if you need to be explicit
### Level-Specific Guidelines
#### C1 System Context
**Focus:** Communication protocols between systems
**Prefer:** Specific types (`http-rest` over `http`)
**Always include:** `direction` and `protocol` fields
#### C2 Container
**Focus:** Container-to-container interactions
**Prefer:** Access-specific types (`database-read-write` over `database-connection`)
**Always include:** `protocol` and `isAsync` fields
#### C3 Component
**Focus:** Code-level dependencies and patterns
**Prefer:** Pattern-specific types (`injects` over `dependency`)
**Always include:** `coupling` field
---
## Examples by Level
### C1 Examples
```json
{ "type": "http-rest", "description": "Fetches data via REST API" }
{ "type": "grpc", "description": "High-performance RPC calls" }
{ "type": "message-queue", "description": "Publishes events to AMQP queue" }
{ "type": "authentication", "description": "Authenticates via OAuth 2.0" }
```
### C2 Examples
```json
{ "type": "http-rest", "description": "REST API calls from SPA to backend" }
{ "type": "database-read-write", "description": "Full database access via ORM" }
{ "type": "cache-read-write", "description": "Caches query results in Redis" }
{ "type": "message-publish", "description": "Publishes order events to queue" }
```
### C3 Examples
```json
{ "type": "uses", "description": "Uses service for business logic" }
{ "type": "injects", "description": "Injects repository via DI" }
{ "type": "implements", "description": "Implements repository interface" }
{ "type": "observes", "description": "Listens to order completion events" }
```
---
## Validation Rules
### All Levels
- Type must be from the appropriate level enum
- Description must be in active voice
- ID must match pattern: `^rel-[a-z0-9-]+$`
### C1 Specific
- Must include `direction` field
- Should include `protocol` for network communication
### C2 Specific
- Should include `protocol` for network communication
- Should include `isAsync` for messaging/async operations
### C3 Specific
- Must include `coupling` field
- Focus on code-level patterns
---
## References
- **Detailed Reference:** [reference.md](./reference.md)
- **Examples:** [examples.md](./examples.md)
- **Main Skill:** [SKILL.md](./SKILL.md)
- **Type Schema:** `${CLAUDE_PLUGIN_ROOT}/validation/templates/types-relations.json`
---
**Version:** 1.0.0
**Last Updated:** 2025-11-17