explain

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Explain - Deep Code Explanation

Explain - 深度代码解析

Get a comprehensive explanation of code, files, directories, or architectural concepts. Automatically routes to the most relevant expert agent and uses modern CLI tools for analysis.
获取代码、文件、目录或架构概念的全面解析。自动路由至最相关的专家Agent,并使用现代CLI工具进行分析。

Arguments

参数

$ARGUMENTS
  • <target>
    - File path, function name, class name, directory, or concept
  • --depth <shallow|normal|deep|trace>
    - Level of detail (default: normal)
  • --focus <arch|flow|deps|api|perf>
    - Specific focus area
$ARGUMENTS
  • <target>
    - 文件路径、函数名、类名、目录或概念
  • --depth <shallow|normal|deep|trace>
    - 详细程度(默认:normal)
  • --focus <arch|flow|deps|api|perf>
    - 特定聚焦领域

Architecture

架构

/explain <target> [--depth] [--focus]
    |
    +-> Step 1: Detect & Classify Target
    |     +- File exists? -> Read it
    |     +- Function/class? -> ast-grep to find definition
    |     +- Directory? -> tokei for overview
    |     +- Concept? -> rg search codebase
    |
    +-> Step 2: Gather Context (parallel)
    |     +- structural-search skill -> find usages
    |     +- code-stats skill -> assess scope
    |     +- Find related: tests, types, docs
    |     +- Load: AGENTS.md, CLAUDE.md conventions
    |
    +-> Step 3: Route to Expert Agent
    |     +- .ts/.tsx -> typescript-expert or react-expert
    |     +- .py -> python-expert
    |     +- .vue -> vue-expert
    |     +- .sql/migrations -> postgres-expert
    |     +- agents/skills/commands -> claude-architect
    |     +- Default -> general-purpose
    |
    +-> Step 4: Generate Explanation
    |     +- Structured markdown with sections
    |     +- Mermaid diagrams (flowchart/sequence/class)
    |     +- Related code paths as file:line refs
    |     +- Design decisions and rationale
    |
    +-> Step 5: Integrate
          +- Offer to save to ARCHITECTURE.md (if significant)
          +- Link to /save if working on related task
/explain <target> [--depth] [--focus]
    |
    +-> 步骤1:检测并分类目标
    |     +- 文件是否存在?→ 读取文件
    |     +- 函数/类?→ 使用ast-grep查找定义
    |     +- 目录?→ 使用tokei生成概览
    |     +- 概念?→ 使用rg搜索代码库
    |
    +-> 步骤2:收集上下文(并行执行)
    |     +- structural-search skill → 查找用法
    |     +- code-stats skill → 评估范围
    |     +- 查找相关内容:测试、类型定义、文档
    |     +- 加载:AGENTS.md、CLAUDE.md约定
    |
    +-> 步骤3:路由至专家Agent
    |     +- .ts/.tsx → typescript-expert 或 react-expert
    |     +- .py → python-expert
    |     +- .vue → vue-expert
    |     +- .sql/migrations → postgres-expert
    |     +- agents/skills/commands → claude-architect
    |     +- 默认 → general-purpose
    |
    +-> 步骤4:生成解析内容
    |     +- 带章节的结构化Markdown
    |     +- Mermaid图表(流程图/序列图/类图)
    |     +- 关联代码路径(文件:行号格式)
    |     +- 设计决策及理由
    |
    +-> 步骤5:整合
          +- 若内容重要,可选择保存至ARCHITECTURE.md
          +- 若处理相关任务,可链接至/save

Execution Steps

执行步骤

Step 1: Detect Target Type

步骤1:检测目标类型

bash
undefined
bash
undefined

Check if target is a file

检查目标是否为文件

test -f "$TARGET" && echo "FILE" && exit
test -f "$TARGET" && echo "FILE" && exit

Check if target is a directory

检查目标是否为目录

test -d "$TARGET" && echo "DIRECTORY" && exit
test -d "$TARGET" && echo "DIRECTORY" && exit

Otherwise, search for it as a symbol

否则,作为符号进行搜索


**For files:** Read directly with bat (syntax highlighted) or Read tool.

**For directories:** Get overview with tokei (if available):
```bash
command -v tokei >/dev/null 2>&1 && tokei "$TARGET" --compact || echo "tokei unavailable"
For symbols (function/class): Find definition with ast-grep:
bash
undefined

**针对文件:** 直接使用bat(带语法高亮)或Read工具读取。

**针对目录:** 使用tokei生成概览(若可用):
```bash
command -v tokei >/dev/null 2>&1 && tokei "$TARGET" --compact || echo "tokei unavailable"
针对符号(函数/类): 使用ast-grep查找定义:
bash
undefined

Try ast-grep first (structural)

优先使用ast-grep(结构化搜索)

command -v ast-grep >/dev/null 2>&1 && ast-grep -p "function $TARGET" -p "class $TARGET" -p "def $TARGET"
command -v ast-grep >/dev/null 2>&1 && ast-grep -p "function $TARGET" -p "class $TARGET" -p "def $TARGET"

Fallback to ripgrep

备选方案:ripgrep

rg "(?:function|class|def|const|let|var)\s+$TARGET" --type-add 'code:*.{ts,tsx,js,jsx,py,vue}' -t code
undefined
rg "(?:function|class|def|const|let|var)\s+$TARGET" --type-add 'code:*.{ts,tsx,js,jsx,py,vue}' -t code
undefined

Step 2: Gather Context

步骤2:收集上下文

Run these in parallel where possible:
Find usages (structural-search skill):
bash
undefined
尽可能并行执行以下操作:
查找用法(structural-search skill):
bash
undefined

With ast-grep

使用ast-grep

ast-grep -p "$TARGET($_)" --json 2>/dev/null | head -20
ast-grep -p "$TARGET($_)" --json 2>/dev/null | head -20

Fallback

备选方案

rg "$TARGET" --type-add 'code:*.{ts,tsx,js,jsx,py,vue}' -t code -l

**Find related files:**
```bash
rg "$TARGET" --type-add 'code:*.{ts,tsx,js,jsx,py,vue}' -t code -l

**查找相关文件:**
```bash

Tests

测试文件

fd -e test.ts -e spec.ts -e test.py -e spec.py | xargs rg -l "$TARGET" 2>/dev/null
fd -e test.ts -e spec.ts -e test.py -e spec.py | xargs rg -l "$TARGET" 2>/dev/null

Types/interfaces

类型/接口定义

fd -e d.ts -e types.ts | xargs rg -l "$TARGET" 2>/dev/null

**Load project conventions:**
- Read AGENTS.md if exists
- Read CLAUDE.md if exists
- Check for framework-specific patterns
fd -e d.ts -e types.ts | xargs rg -l "$TARGET" 2>/dev/null

**加载项目约定:**
- 若存在则读取AGENTS.md
- 若存在则读取CLAUDE.md
- 检查框架特定模式

Step 3: Route to Expert Agent

步骤3:路由至专家Agent

Determine the best expert based on file extension and content:
PatternPrimary AgentCondition
.ts
typescript-expertNo JSX/React imports
.tsx
react-expertJSX present
.js
,
.jsx
javascript-expert-
.py
python-expert-
.vue
vue-expert-
.sql
,
migrations/*
postgres-expert-
agents/*.md
,
skills/*
,
commands/*
claude-architectClaude extensions
*.test.*
,
*.spec.*
(framework expert)Route by file type
Othergeneral-purposeFallback
Invoke via Task tool:
Task tool with subagent_type: "[detected]-expert"
Prompt includes:
  - File content
  - Related files found
  - Project conventions
  - Requested depth and focus
根据文件扩展名和内容确定最合适的专家Agent:
匹配模式首选Agent条件
.ts
typescript-expert无JSX/React导入
.tsx
react-expert包含JSX
.js
,
.jsx
javascript-expert-
.py
python-expert-
.vue
vue-expert-
.sql
,
migrations/*
postgres-expert-
agents/*.md
,
skills/*
,
commands/*
claude-architectClaude扩展内容
*.test.*
,
*.spec.*
(对应框架专家)根据文件类型路由
其他general-purpose备选方案
通过Task工具调用:
Task tool with subagent_type: "[detected]-expert"
Prompt includes:
  - 文件内容
  - 找到的相关文件
  - 项目约定
  - 请求的详细程度和聚焦领域

Step 4: Generate Explanation

步骤4:生成解析内容

The expert agent produces a structured explanation:
markdown
undefined
专家Agent会生成结构化的解析内容:
markdown
undefined

Explanation: [target]

解析:[target]

Overview

概览

[1-2 sentence summary of purpose and role in the system]
[1-2句话总结目标的用途及在系统中的角色]

Architecture

架构

[Mermaid diagram - choose appropriate type]
[Mermaid图表 - 选择合适的类型]

Flowchart (for control flow)

流程图(用于控制流)

 
mermaid flowchart TD     A[Input] --> B{Validate}     B -->|Valid| C[Process]     B -->|Invalid| D[Error]     C --> E[Output] 
 
 
mermaid flowchart TD     A[输入] --> B{验证}     B -->|有效| C[处理]     B -->|无效| D[错误]     C --> E[输出] 
 

Sequence (for interactions)

序列图(用于交互流程)

 
mermaid sequenceDiagram     participant Client     participant Server     participant Database     Client->>Server: Request     Server->>Database: Query     Database-->>Server: Result     Server-->>Client: Response 
 
 
mermaid sequenceDiagram     participant Client     participant Server     participant Database     Client->>Server: 请求     Server->>Database: 查询     Database-->>Server: 结果     Server-->>Client: 响应 
 

Class (for structures)

类图(用于结构)

 
mermaid classDiagram     class Component {         +props: Props         +state: State         +render(): JSX     } 
 
 
mermaid classDiagram     class Component {         +props: Props         +state: State         +render(): JSX     } 
 

How It Works

工作原理

Step 1: [Phase Name]

步骤1:[阶段名称]

[Explanation with code references]
See:
src/module.ts:42
[带代码引用的解析]
参考:
src/module.ts:42

Step 2: [Phase Name]

步骤2:[阶段名称]

[Explanation]
[解析内容]

Key Concepts

核心概念

[Concept 1]

[概念1]

[Explanation]
[解析内容]

[Concept 2]

[概念2]

[Explanation]
[解析内容]

Dependencies

依赖关系

ImportPurpose
package
[why it's used]
导入包用途
package
[使用原因]

Design Decisions

设计决策

Why [decision]?

为何选择[决策]?

[Rationale and tradeoffs considered]
[理由及考虑的权衡因素]

Related Code

关联代码

FileRelationship
path/to/file.ts:123
[how it relates]
文件关联关系
path/to/file.ts:123
[关联说明]

See Also

参考链接

  • /explain path/to/related
    - [description]
  • [External docs link] - [description]
undefined
  • /explain path/to/related
    - [描述]
  • [外部文档链接] - [描述]
undefined

Depth Modes

详细程度模式

ModeOutput
--shallow
Overview paragraph, key exports, no diagram
--normal
Full explanation with 1 diagram, main concepts (default)
--deep
Exhaustive: all internals, edge cases, history, multiple diagrams
--trace
Data flow tracing through entire system, sequence diagrams
模式输出内容
--shallow
概览段落、核心导出、无图表
--normal
完整解析+1张图表、核心概念(默认)
--deep
详尽解析:所有内部实现、边界情况、历史变更、多张图表
--trace
全系统数据流追踪、序列图

Shallow Example

浅度示例

bash
/explain src/auth/token.ts --shallow
Output: Single paragraph + exports list.
bash
/explain src/auth/token.ts --shallow
输出:单个段落+导出列表。

Deep Example

深度示例

bash
/explain src/core/engine.ts --deep
Output: Full internals, algorithm analysis, performance notes, edge cases.
bash
/explain src/core/engine.ts --deep
输出:完整内部实现、算法分析、性能说明、边界情况。

Trace Example

追踪示例

bash
/explain handleLogin --trace
Output: Traces data flow from entry to database to response.
bash
/explain handleLogin --trace
输出:追踪从入口到数据库再到响应的数据流。

Focus Modes

聚焦模式

ModeWhat It Analyzes
--focus arch
Module boundaries, layer separation, dependencies
--focus flow
Data flow, control flow, state changes
--focus deps
Imports, external dependencies, integrations
--focus api
Public interface, inputs/outputs, contracts
--focus perf
Complexity, bottlenecks, optimization opportunities
模式分析内容
--focus arch
模块边界、分层、依赖关系
--focus flow
数据流、控制流、状态变更
--focus deps
导入、外部依赖、集成关系
--focus api
公共接口、输入/输出、契约
--focus perf
复杂度、瓶颈、优化方向

CLI Tool Integration

CLI工具集成

Commands use modern CLI tools with graceful fallbacks:
ToolPurposeFallback
tokei
Code statisticsSkip stats
ast-grep
Structural search
rg
with patterns
bat
Syntax highlightingRead tool
rg
Content searchGrep tool
fd
File findingGlob tool
Check availability:
bash
command -v tokei >/dev/null 2>&1 || echo "tokei not installed - skipping stats"
命令使用现代CLI工具,并提供优雅的降级方案:
工具用途备选方案
tokei
代码统计跳过统计
ast-grep
结构化搜索使用带模式的
rg
bat
语法高亮Read工具
rg
内容搜索Grep工具
fd
文件查找Glob工具
检查可用性:
bash
command -v tokei >/dev/null 2>&1 || echo "tokei not installed - skipping stats"

Usage Examples

使用示例

bash
undefined
bash
undefined

Explain a file

解析单个文件

/explain src/auth/oauth.ts
/explain src/auth/oauth.ts

Explain a function (finds it automatically)

解析函数(自动查找)

/explain validateToken
/explain validateToken

Explain a directory

解析目录

/explain src/services/
/explain src/services/

Deep dive with architecture focus

深度剖析并聚焦架构

/explain src/core/engine.ts --deep --focus arch
/explain src/core/engine.ts --deep --focus arch

Trace data flow

追踪数据流

/explain handleUserLogin --trace
/explain handleUserLogin --trace

Quick overview

快速概览

/explain src/utils/helpers.ts --shallow
/explain src/utils/helpers.ts --shallow

Focus on dependencies

聚焦依赖关系

/explain package.json --focus deps
undefined
/explain package.json --focus deps
undefined

Integration

集成能力

Skill/CommandRelationship
/review
Review after understanding
/testgen
Generate tests for explained code
/save
Save progress if working on related task
Skill/命令关联关系
/review
理解代码后进行评审
/testgen
为解析的代码生成测试用例
/save
若处理相关任务,可保存进度

Persistence

持久化

After significant explanations, you may be offered:
Would you like to save this explanation?
  1. Append to ARCHITECTURE.md
  2. Append to AGENTS.md (if conventions-related)
  3. Don't save (output only)
This keeps valuable architectural knowledge in git-tracked documentation.
完成重要的解析内容后,会提供以下选项:
是否保存此解析内容?
  1. 追加至ARCHITECTURE.md
  2. 追加至AGENTS.md(若与约定相关)
  3. 不保存(仅输出)
这将把有价值的架构知识保存在Git追踪的文档中。

Notes

注意事项

  • Explanations are based on code analysis, not documentation
  • Complex systems may need multiple
    /explain
    calls
  • Use
    --deep
    for unfamiliar codebases
  • Mermaid diagrams render in GitHub, GitLab, VSCode, and most markdown viewers
  • Expert agents provide framework-specific insights
  • 解析内容基于代码分析,而非文档
  • 复杂系统可能需要多次调用
    /explain
  • 对于不熟悉的代码库,使用
    --deep
    模式
  • Mermaid图表可在GitHub、GitLab、VSCode及大多数Markdown查看器中渲染
  • 专家Agent可提供框架特定的见解