Files
gh-cubical6-melly/skills/c4model-c4/SKILL.md
2025-11-29 18:17:07 +08:00

12 KiB
Raw Blame History

name, description
name description
c4model-c4 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:

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.


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.


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.


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.


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.


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:

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

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+