code-visualizer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Visualizer Skill
代码可视化Skill
Purpose
用途
Automatically generate and maintain visual code flow diagrams. This skill analyzes Python module structure, detects import relationships, and generates mermaid diagrams. It also monitors for staleness when code changes but diagrams don't.
自动生成并维护可视化代码流程图。本Skill分析Python模块结构,检测导入关系,并生成mermaid图。它还会监控代码更改但图未更新时的过期状态。
Philosophy Alignment
理念契合
This skill embodies amplihack's core philosophy:
本Skill体现了amplihack的核心理念:
Ruthless Simplicity
极致简洁
- Single responsibility: Visualize code structure - nothing more
- Minimal dependencies: Uses only Python AST for analysis, delegates diagram syntax to mermaid-diagram-generator
- No over-engineering: Timestamp-based staleness is simple and "good enough" for 90% of cases
- 单一职责:仅可视化代码结构,别无其他
- 最小依赖:仅使用Python AST进行分析,将图语法生成委托给mermaid-diagram-generator
- 不做过度设计:基于时间戳的过期检测简单且对90%的场景来说“足够好用”
Zero-BS Implementation
零冗余实现
- Real analysis: Actually parses Python AST to extract imports - no mock data
- Honest limitations: Staleness detection is timestamp-based, not semantic (see Limitations section)
- Working code: All algorithms shown are functional, not pseudocode
- 真实分析:实际解析Python AST来提取导入语句,无模拟数据
- 坦诚局限:过期检测基于时间戳,而非语义分析(详见局限部分)
- 可运行代码:展示的所有算法均为可运行代码,而非伪代码
Modular Design (Bricks & Studs)
模块化设计(积木与凸点)
- This skill is one brick: Code analysis and staleness detection
- Delegates to other bricks: mermaid-diagram-generator for syntax, visualization-architect for complex diagrams
- Clear studs (public contract): Analyze modules, generate diagrams, check freshness
- 本Skill是一块积木:代码分析与过期检测
- 委托给其他积木:mermaid-diagram-generator负责语法,visualization-architect负责复杂图
- 清晰的凸点(公开契约):分析模块、生成图、检查新鲜度
Skill Delegation Architecture
Skill委托架构
code-visualizer (this skill)
├── Responsibilities:
│ ├── Python module analysis (AST parsing)
│ ├── Import relationship extraction
│ ├── Staleness detection (timestamp-based)
│ └── Orchestration of diagram generation
│
└── Delegates to:
├── mermaid-diagram-generator skill
│ ├── Mermaid syntax generation
│ ├── Diagram formatting and styling
│ └── Markdown embedding
│
└── visualization-architect agent
├── Complex multi-level architecture
├── ASCII art alternatives
└── Cross-module dependency graphsInvocation Pattern:
python
undefinedcode-visualizer (this skill)
├── Responsibilities:
│ ├── Python module analysis (AST parsing)
│ ├── Import relationship extraction
│ ├── Staleness detection (timestamp-based)
│ └── Orchestration of diagram generation
│
└── Delegates to:
├── mermaid-diagram-generator skill
│ ├── Mermaid syntax generation
│ ├── Diagram formatting and styling
│ └── Markdown embedding
│
└── visualization-architect agent
├── Complex multi-level architecture
├── ASCII art alternatives
└── Cross-module dependency graphs调用模式:
python
undefinedcode-visualizer analyzes code structure
code-visualizer分析代码结构
modules = analyze_python_modules("src/")
relationships = extract_import_relationships(modules)
modules = analyze_python_modules("src/")
relationships = extract_import_relationships(modules)
Then delegates to mermaid-diagram-generator for syntax
然后委托给mermaid-diagram-generator生成语法
Skill(skill="mermaid-diagram-generator")
Skill(skill="mermaid-diagram-generator")
Provide: Module relationships, diagram type (flowchart/class), styling preferences
提供:模块关系、图类型(流程图/类图)、样式偏好
Receive: Valid mermaid syntax ready for embedding
获得:可直接嵌入的有效mermaid语法
For complex architectures, delegates to visualization-architect
对于复杂架构,委托给visualization-architect
Task(subagent_type="visualization-architect", prompt="Create multi-level diagram for...")
undefinedTask(subagent_type="visualization-architect", prompt="Create multi-level diagram for...")
undefinedWhen to Use This Skill
适用场景
- New Module Creation: Auto-generate architecture diagram for new modules
- PR Reviews: Show architecture impact of proposed changes
- Staleness Detection: Check if existing diagrams reflect current code
- Dependency Analysis: Visualize import relationships
- Refactoring: Understand module dependencies before changes
- 新模块创建:为新模块自动生成架构图
- PR评审:展示提议更改的架构影响
- 过期检测:检查现有架构图是否反映当前代码
- 依赖分析:可视化导入关系
- 重构:在更改前理解模块依赖
Quick Start
快速开始
Generate Diagram for Module
为模块生成图
User: Generate a code flow diagram for the authentication module用户:为认证模块生成代码流程图Check Diagram Freshness
检查图的新鲜度
User: Are my architecture diagrams up to date?用户:我的架构图是否是最新的?Show PR Impact
展示PR影响
User: What architecture changes does this PR introduce?用户:这个PR引入了哪些架构更改?Core Capabilities
核心能力
1. Module Analysis
1. 模块分析
Analyzes Python files to extract:
- Import statements (internal and external)
- Class definitions and inheritance
- Function exports ()
__all__ - Module dependencies
分析Python文件以提取:
- 导入语句(内部和外部)
- 类定义与继承关系
- 函数导出()
__all__ - 模块依赖
2. Diagram Generation
2. 图生成
Creates mermaid diagrams showing:
- Module relationships (flowchart)
- Class hierarchies (class diagram)
- Data flow between components
- Dependency graphs
创建展示以下内容的mermaid图:
- 模块关系(流程图)
- 类层次结构(类图)
- 组件间的数据流
- 依赖图
3. Staleness Detection
3. 过期检测
Compares:
- File modification timestamps
- Git history for changes
- Diagram content vs actual code structure
- Missing modules in diagrams
对比:
- 文件修改时间戳
- Git历史记录中的更改
- 图内容与实际代码结构
- 图中缺失的模块
Analysis Process
分析流程
Step 1: Discover Modules
步骤1:发现模块
python
undefinedpython
undefinedScan target directory for Python modules
扫描目标目录中的Python模块
modules = glob("**/*.py")
packages = identify_packages(modules)
undefinedmodules = glob("**/*.py")
packages = identify_packages(modules)
undefinedStep 2: Extract Relationships
步骤2:提取关系
For each module:
- Parse import statements
- Identify local vs external imports
- Build dependency graph
- Detect circular dependencies
对每个模块:
- 解析导入语句
- 识别本地与外部导入
- 构建依赖图
- 检测循环依赖
Step 3: Generate Diagram
步骤3:生成图
mermaid
flowchart TD
subgraph core["Core Modules"]
auth[auth.py]
users[users.py]
api[api.py]
end
subgraph utils["Utilities"]
helpers[helpers.py]
validators[validators.py]
end
api --> auth
api --> users
auth --> helpers
users --> validatorsmermaid
flowchart TD
subgraph core["Core Modules"]
auth[auth.py]
users[users.py]
api[api.py]
end
subgraph utils["Utilities"]
helpers[helpers.py]
validators[validators.py]
end
api --> auth
api --> users
auth --> helpers
users --> validatorsStep 4: Check Freshness
步骤4:检查新鲜度
Compare diagram timestamps with source files:
- Diagram older than sources = STALE
- Missing modules in diagram = INCOMPLETE
- Extra modules in diagram = OUTDATED
对比图的时间戳与源文件:
- 图比源文件旧 = 过期
- 图中缺失模块 = 不完整
- 图中有多余模块 = 过时
Diagram Types
图类型
Module Dependency Graph
模块依赖图
Best for: Showing import relationships between files
mermaid
flowchart LR
main[main.py] --> auth[auth/]
main --> api[api/]
auth --> models[models.py]
api --> auth最佳用途:展示文件间的导入关系
mermaid
flowchart LR
main[main.py] --> auth[auth/]
main --> api[api/]
auth --> models[models.py]
api --> authClass Hierarchy
类层次结构
Best for: Showing inheritance and composition
mermaid
classDiagram
class BaseService {
+process()
}
class AuthService {
+login()
+logout()
}
BaseService <|-- AuthService最佳用途:展示继承与组合关系
mermaid
classDiagram
class BaseService {
+process()
}
class AuthService {
+login()
+logout()
}
BaseService <|-- AuthServiceData Flow
数据流
Best for: Showing how data moves through system
mermaid
flowchart TD
Request[HTTP Request] --> Validate{Validate}
Validate -->|Valid| Process[Process]
Validate -->|Invalid| Error[Return Error]
Process --> Response[HTTP Response]最佳用途:展示系统内的数据流动
mermaid
flowchart TD
Request[HTTP Request] --> Validate{Validate}
Validate -->|Valid| Process[Process]
Validate -->|Invalid| Error[Return Error]
Process --> Response[HTTP Response]Staleness Detection
过期检测
How It Works
工作原理
- Find Diagrams: Locate mermaid diagrams in README.md, ARCHITECTURE.md
- Extract Modules: Parse diagram for referenced modules
- Compare: Check if all current modules are represented
- Report: Generate freshness report
- 查找图:在README.md、ARCHITECTURE.md中定位mermaid图
- 提取模块:解析图以获取引用的模块
- 对比:检查所有当前模块是否都已在图中体现
- 报告:生成新鲜度报告
Freshness Report Format
新鲜度报告格式
markdown
undefinedmarkdown
undefinedDiagram Freshness Report
图新鲜度报告
Status: STALE
状态:过期
Diagrams Checked: 3
Fresh: 1
Stale: 2
已检查图数量:3
新鲜:1
过期:2
Details
详情
| File | Last Updated | Code Changed | Status |
|---|---|---|---|
| README.md | 2025-01-01 | 2025-01-15 | STALE |
| docs/ARCH.md | 2025-01-10 | 2025-01-10 | FRESH |
| 文件 | 最后更新时间 | 代码更改时间 | 状态 |
|---|---|---|---|
| README.md | 2025-01-01 | 2025-01-15 | 过期 |
| docs/ARCH.md | 2025-01-10 | 2025-01-10 | 新鲜 |
Missing from Diagrams
图中缺失的模块
- (added 2025-01-12)
new_module.py - (added 2025-01-14)
api/v2.py
- (添加于2025-01-12)
new_module.py - (添加于2025-01-14)
api/v2.py
Recommended Actions
建议操作
- Update README.md architecture diagram
- Add new_module.py to dependency graph
undefined- 更新README.md中的架构图
- 将new_module.py添加到依赖图
undefinedPR Architecture Impact
PR架构影响
What It Shows
展示内容
For a given PR or set of changes:
- New modules/files added
- Changed import relationships
- Deleted dependencies
- Modified class hierarchies
对于给定的PR或一组更改:
- 新增的模块/文件
- 更改的导入关系
- 删除的依赖
- 修改的类层次结构
Impact Diagram
影响图
mermaid
flowchart TD
subgraph added["New"]
style added fill:#90EE90
new_api[api/v2.py]
end
subgraph modified["Modified"]
style modified fill:#FFE4B5
auth[auth.py]
end
subgraph existing["Unchanged"]
users[users.py]
models[models.py]
end
new_api --> auth
auth --> models
users --> modelsmermaid
flowchart TD
subgraph added["New"]
style added fill:#90EE90
new_api[api/v2.py]
end
subgraph modified["Modified"]
style modified fill:#FFE4B5
auth[auth.py]
end
subgraph existing["Unchanged"]
users[users.py]
models[models.py]
end
new_api --> auth
auth --> models
users --> modelsIntegration with Other Skills
与其他Skill的集成
Mermaid Diagram Generator
Mermaid图生成器
This skill uses for:
mermaid-diagram-generator- Syntax generation
- Diagram formatting
- Embedding in markdown
本Skill使用来实现:
mermaid-diagram-generator- 语法生成
- 图格式化
- 嵌入Markdown
Visualization Architect Agent
Visualization Architect Agent
Delegates to for:
visualization-architect- Complex architecture visualization
- ASCII art alternatives
- Multi-level diagrams
将以下工作委托给:
visualization-architect- 复杂架构可视化
- ASCII图替代方案
- 多层级图
Usage Examples
使用示例
Example 1: New Module Diagram
示例1:新模块图
User: I just created a new payment module. Generate an architecture diagram.
Claude:
1. Analyzes payment/ directory
2. Extracts imports and dependencies
3. Generates mermaid flowchart
4. Suggests where to embed (README.md)用户:我刚创建了一个新的支付模块。生成一张架构图。
Claude:
1. 分析payment/目录
2. 提取导入和依赖关系
3. 生成mermaid流程图
4. 建议嵌入位置(README.md)Example 2: Check Staleness
示例2:检查过期状态
User: Are my diagrams up to date?
Claude:
1. Finds all mermaid diagrams in docs
2. Compares with current codebase
3. Reports stale diagrams
4. Lists missing modules
5. Suggests updates用户:我的图是最新的吗?
Claude:
1. 查找docs目录下的所有mermaid图
2. 与当前代码库对比
3. 报告过期的图
4. 列出缺失的模块
5. 建议更新Example 3: PR Impact
示例3:PR影响
User: Show architecture impact of this PR
Claude:
1. Gets changed files from PR
2. Identifies new/modified/deleted modules
3. Generates impact diagram
4. Highlights dependency changes用户:展示这个PR的架构影响
Claude:
1. 获取PR中的更改文件
2. 识别新增/修改/删除的模块
3. 生成影响图
4. 突出显示依赖更改Detection Algorithms
检测算法
Import Analysis
导入分析
python
undefinedpython
undefinedExtract imports from Python file
Extract imports from Python file
import ast
def extract_imports(file_path):
"""Extract import statements from Python file."""
tree = ast.parse(Path(file_path).read_text())
imports = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imports.append(alias.name)
elif isinstance(node, ast.ImportFrom):
if node.module:
imports.append(node.module)
return imports
undefinedimport ast
def extract_imports(file_path):
"""Extract import statements from Python file."""
tree = ast.parse(Path(file_path).read_text())
imports = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imports.append(alias.name)
elif isinstance(node, ast.ImportFrom):
if node.module:
imports.append(node.module)
return imports
undefinedStaleness Check
过期检查
python
def check_staleness(diagram_file, source_dir):
"""Check if diagram is stale compared to source."""
diagram_mtime = Path(diagram_file).stat().st_mtime
for source in Path(source_dir).rglob("*.py"):
if source.stat().st_mtime > diagram_mtime:
return True, source # Stale
return False, None # Freshpython
def check_staleness(diagram_file, source_dir):
"""Check if diagram is stale compared to source."""
diagram_mtime = Path(diagram_file).stat().st_mtime
for source in Path(source_dir).rglob("*.py"):
if source.stat().st_mtime > diagram_mtime:
return True, source # Stale
return False, None # FreshBest Practices
最佳实践
When to Update Diagrams
何时更新图
- New modules: Add to dependency graph
- Changed imports: Update relationships
- Deleted files: Remove from diagrams
- Architectural changes: Regenerate completely
- 新增模块:添加到依赖图
- 导入更改:更新关系
- 删除文件:从图中移除
- 架构更改:完全重新生成
Diagram Placement
图的放置位置
| Diagram Type | Recommended Location |
|---|---|
| Module overview | README.md |
| Detailed architecture | docs/ARCHITECTURE.md |
| Package structure | package/README.md |
| API flow | api/README.md |
| 图类型 | 推荐位置 |
|---|---|
| 模块概览 | README.md |
| 详细架构 | docs/ARCHITECTURE.md |
| 包结构 | package/README.md |
| API流 | api/README.md |
Naming Conventions
命名规范
markdown
undefinedmarkdown
undefinedArchitecture
架构
<!-- code-visualizer:auto-generated -->
<!-- last-updated: 2025-01-15 -->
<!-- source-hash: abc123 -->
mermaid
flowchart TD
...undefined<!-- code-visualizer:auto-generated -->
<!-- last-updated: 2025-01-15 -->
<!-- source-hash: abc123 -->
mermaid
flowchart TD
...undefinedSuccess Criteria
成功标准
A good visualization:
- Shows all current modules
- Reflects actual import relationships
- Uses appropriate diagram type
- Placed in discoverable location
- Includes freshness metadata
- Clear and not overcrowded
优质的可视化应满足:
- 展示所有当前模块
- 反映实际导入关系
- 使用合适的图类型
- 放置在易查找的位置
- 包含新鲜度元数据
- 清晰且不过于拥挤
Limitations
局限
IMPORTANT: Understand these limitations before relying on this skill:
重要提示:在依赖本Skill前请了解这些局限:
Staleness Detection Limitations
过期检测局限
-
Timestamp-based, not semantic: Detection compares file modification times, not actual code changes
- A file touched but not meaningfully changed will trigger "stale"
- Reformatting code triggers false positives
- Git operations that update mtime trigger false positives
-
Cannot detect logic changes: Adding a function that doesn't change imports won't be detected
- Internal refactoring within a module is invisible
- Changes to function signatures not reflected
- New class methods added without import changes won't show
-
Import-centric view: Only tracks import relationships
- Runtime dependencies (dependency injection) not detected
- Configuration-based connections invisible
- Duck typing relationships not captured
-
基于时间戳而非语义:检测仅对比文件修改时间,而非实际代码更改
- 仅被触碰但未实质更改的文件会触发“过期”
- 代码格式化会触发误报
- 更新mtime的Git操作会触发误报
-
无法检测逻辑更改:添加不更改导入的函数不会被检测到
- 模块内部的重构不可见
- 函数签名的更改不会体现
- 添加不涉及导入更改的新类方法不会被显示
-
以导入为中心的视角:仅跟踪导入关系
- 运行时依赖(依赖注入)无法被检测
- 基于配置的连接不可见
- 鸭子类型的关系无法被捕获
Scope Limitations
范围局限
-
Python-only: Currently only analyzes Python files
- No TypeScript, JavaScript, Rust, Go support
- Multi-language projects partially covered
-
Static analysis only: No runtime information
- Dynamic imports (,
__import__) not detectedimportlib - Conditional imports may be missed
- Plugin architectures not fully represented
- Dynamic imports (
-
Single-project scope: Cannot analyze cross-repository dependencies
- External package internals not shown
- Monorepo relationships require manual configuration
-
仅支持Python:目前仅分析Python文件
- 不支持TypeScript、JavaScript、Rust、Go
- 多语言项目仅能部分覆盖
-
仅静态分析:无运行时信息
- 动态导入(、
__import__)无法被检测importlib - 条件导入可能被遗漏
- 插件架构无法完整呈现
- 动态导入(
-
单项目范围:无法分析跨仓库依赖
- 外部包的内部实现不会显示
- 单体仓库的关系需要手动配置
Accuracy Expectations
准确性预期
| Scenario | Accuracy | Notes |
|---|---|---|
| New module detection | 95%+ | Reliable for Python modules |
| Import relationship mapping | 90%+ | Misses dynamic imports |
| Staleness detection | 70-80% | False positives common |
| Circular dependency detection | 85%+ | May miss complex cycles |
| Class hierarchy extraction | 85%+ | Mixins can be tricky |
| 场景 | 准确率 | 说明 |
|---|---|---|
| 新模块检测 | 95%+ | 对Python模块可靠 |
| 导入关系映射 | 90%+ | 会遗漏动态导入 |
| 过期检测 | 70-80% | 常见误报 |
| 循环依赖检测 | 85%+ | 可能遗漏复杂循环 |
| 类层次结构提取 | 85%+ | 混入类(Mixin)可能有难度 |
When NOT to Use This Skill
不适用场景
- Security-critical dependency audits: Use proper security scanning tools
- Runtime dependency analysis: Use profilers or dynamic analysis tools
- Cross-language projects: Manual analysis may be more accurate
- Heavily dynamic codebases: Plugin architectures, metaprogramming
- 安全关键依赖审计:使用专业的安全扫描工具
- 运行时依赖分析:使用性能分析器或动态分析工具
- 多语言项目:手动分析可能更准确
- 高度动态的代码库:插件架构、元编程
Dependencies
依赖
This skill requires:
- mermaid-diagram-generator skill: Must be available for diagram syntax generation
- Python 3.8+: For AST parsing features used
- Git (optional): For enhanced staleness detection using git history
If mermaid-diagram-generator is unavailable, this skill will provide raw relationship data but cannot generate embedded diagrams.
本Skill需要:
- mermaid-diagram-generator skill:必须可用以生成图语法
- Python 3.8+:使用所需的AST解析功能
- Git(可选):使用Git历史记录增强过期检测
如果mermaid-diagram-generator不可用,本Skill将提供原始关系数据,但无法生成可嵌入的图。
PR Review Integration
PR评审集成
How Diagrams Appear in PRs
图在PR中的展示方式
When reviewing PRs, this skill generates impact diagrams that can be added to PR descriptions:
PR Description Template:
markdown
undefined评审PR时,本Skill会生成影响图,可添加到PR描述中:
PR描述模板:
markdown
undefinedArchitecture Impact
架构影响
<!-- Generated by code-visualizer -->
<!-- Generated by code-visualizer -->
Changed Dependencies
更改的依赖
mermaid
flowchart LR
subgraph changed["Modified Modules"]
style changed fill:#FFE4B5
auth[auth/service.py]
api[api/routes.py]
end
subgraph added["New Modules"]
style added fill:#90EE90
oauth[auth/oauth.py]
end
subgraph unchanged["Existing"]
models[models/user.py]
db[db/connection.py]
end
oauth --> auth
auth --> models
api --> auth
api --> dbmermaid
flowchart LR
subgraph changed["Modified Modules"]
style changed fill:#FFE4B5
auth[auth/service.py]
api[api/routes.py]
end
subgraph added["New Modules"]
style added fill:#90EE90
oauth[auth/oauth.py]
end
subgraph unchanged["Existing"]
models[models/user.py]
db[db/connection.py]
end
oauth --> auth
auth --> models
api --> auth
api --> dbImpact Summary
影响摘要
- New modules: 1 (oauth.py)
- Modified modules: 2 (auth/service.py, api/routes.py)
- New dependencies: oauth.py -> auth/service.py
- Diagrams to update: README.md (STALE)
undefined- 新增模块:1个(oauth.py)
- 修改模块:2个(auth/service.py、api/routes.py)
- 新增依赖:oauth.py -> auth/service.py
- 需更新的图:README.md(已过期)
undefinedCI Integration Example
CI集成示例
Add to :
.github/workflows/pr-review.ymlyaml
- name: Check Diagram Staleness
run: |
# Claude Code analyzes and reports
# Outputs: STALE diagrams that need updating
# Generates: Suggested diagram updates添加到:
.github/workflows/pr-review.ymlyaml
- name: Check Diagram Staleness
run: |
# Claude Code analyzes and reports
# Outputs: STALE diagrams that need updating
# Generates: Suggested diagram updatesReviewer Workflow
评审者工作流
- PR opened -> code-visualizer generates impact diagram
- Reviewer sees -> Visual diff of architecture changes
- Staleness check -> Warns if existing diagrams need updates
- Action items -> Lists diagrams requiring manual update
- PR创建 -> code-visualizer生成影响图
- 评审者查看 -> 架构更改的可视化差异
- 过期检查 -> 警告现有图是否需要更新
- 行动项 -> 列出需要手动更新的图
Remember
注意事项
This skill automates what developers often forget:
- Keeping diagrams in sync with code
- Documenting architecture changes
- Understanding dependency impacts
The goal is diagrams that stay fresh automatically.
But remember the limitations: Staleness detection is approximate. When accuracy matters, verify manually.
本Skill自动化了开发者常忽略的工作:
- 保持图与代码同步
- 记录架构更改
- 理解依赖影响
目标是让图自动保持新鲜。
但请记住局限:过期检测是近似的。当准确性至关重要时,请手动验证。