grepai-trace-graph

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GrepAI Trace Graph

GrepAI Trace 调用图

This skill covers using
grepai trace graph
to build complete call graphs showing all dependencies recursively.
本技能介绍如何使用
grepai trace graph
构建完整的调用图,递归展示所有依赖关系。

When to Use This Skill

适用场景

  • Mapping complete function dependencies
  • Understanding complex code flows
  • Impact analysis for major refactoring
  • Visualizing application architecture
  • 映射完整的函数依赖关系
  • 理解复杂的代码流程
  • 重大重构的影响分析
  • 可视化应用架构

What is Trace Graph?

什么是Trace Graph?

grepai trace graph
builds a recursive dependency tree:
main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB
grepai trace graph
会构建递归依赖树:
main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB

Basic Usage

基础用法

bash
grepai trace graph "FunctionName"
bash
grepai trace graph "FunctionName"

Example

示例

bash
grepai trace graph "main"
Output:
🔍 Call Graph for "main"

main
├── initialize
│   ├── loadConfig
│   └── connectDB
├── startServer
│   ├── registerRoutes
│   └── listen
└── gracefulShutdown
    └── closeDB

Nodes: 9
Max depth: 3
bash
grepai trace graph "main"
输出:
🔍 Call Graph for "main"

main
├── initialize
│   ├── loadConfig
│   └── connectDB
├── startServer
│   ├── registerRoutes
│   └── listen
└── gracefulShutdown
    └── closeDB

Nodes: 9
Max depth: 3

Depth Control

深度控制

Limit recursion depth with
--depth
:
bash
undefined
使用
--depth
参数限制递归深度:
bash
undefined

Default depth (2 levels)

默认深度(2层)

grepai trace graph "main"
grepai trace graph "main"

Deeper analysis (3 levels)

更深入的分析(3层)

grepai trace graph "main" --depth 3
grepai trace graph "main" --depth 3

Shallow (1 level, same as callees)

浅层分析(1层,与直接调用者相同)

grepai trace graph "main" --depth 1
grepai trace graph "main" --depth 1

Very deep (5 levels)

极深分析(5层)

grepai trace graph "main" --depth 5
undefined
grepai trace graph "main" --depth 5
undefined

Depth Examples

深度示例

--depth 1 (same as callees):
main
├── initialize
├── startServer
└── gracefulShutdown
--depth 2 (default):
main
├── initialize
│   ├── loadConfig
│   └── connectDB
├── startServer
│   ├── registerRoutes
│   └── listen
└── gracefulShutdown
    └── closeDB
--depth 3:
main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB
--depth 1(与直接调用者相同):
main
├── initialize
├── startServer
└── gracefulShutdown
--depth 2(默认):
main
├── initialize
│   ├── loadConfig
│   └── connectDB
├── startServer
│   ├── registerRoutes
│   └── listen
└── gracefulShutdown
    └── closeDB
--depth 3
main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB

JSON Output

JSON输出

bash
grepai trace graph "main" --depth 2 --json
Output:
json
{
  "query": "main",
  "mode": "graph",
  "depth": 2,
  "root": {
    "name": "main",
    "file": "cmd/main.go",
    "line": 10,
    "children": [
      {
        "name": "initialize",
        "file": "cmd/main.go",
        "line": 15,
        "children": [
          {
            "name": "loadConfig",
            "file": "config/config.go",
            "line": 20,
            "children": []
          },
          {
            "name": "connectDB",
            "file": "db/db.go",
            "line": 30,
            "children": []
          }
        ]
      },
      {
        "name": "startServer",
        "file": "server/server.go",
        "line": 25,
        "children": [
          {
            "name": "registerRoutes",
            "file": "server/routes.go",
            "line": 10,
            "children": []
          }
        ]
      }
    ]
  },
  "stats": {
    "nodes": 6,
    "max_depth": 2
  }
}
bash
grepai trace graph "main" --depth 2 --json
输出:
json
{
  "query": "main",
  "mode": "graph",
  "depth": 2,
  "root": {
    "name": "main",
    "file": "cmd/main.go",
    "line": 10,
    "children": [
      {
        "name": "initialize",
        "file": "cmd/main.go",
        "line": 15,
        "children": [
          {
            "name": "loadConfig",
            "file": "config/config.go",
            "line": 20,
            "children": []
          },
          {
            "name": "connectDB",
            "file": "db/db.go",
            "line": 30,
            "children": []
          }
        ]
      },
      {
        "name": "startServer",
        "file": "server/server.go",
        "line": 25,
        "children": [
          {
            "name": "registerRoutes",
            "file": "server/routes.go",
            "line": 10,
            "children": []
          }
        ]
      }
    ]
  },
  "stats": {
    "nodes": 6,
    "max_depth": 2
  }
}

Compact JSON

紧凑JSON格式

bash
grepai trace graph "main" --depth 2 --json --compact
Output:
json
{
  "q": "main",
  "d": 2,
  "r": {
    "n": "main",
    "c": [
      {"n": "initialize", "c": [{"n": "loadConfig"}, {"n": "connectDB"}]},
      {"n": "startServer", "c": [{"n": "registerRoutes"}]}
    ]
  },
  "s": {"nodes": 6, "depth": 2}
}
bash
grepai trace graph "main" --depth 2 --json --compact
输出:
json
{
  "q": "main",
  "d": 2,
  "r": {
    "n": "main",
    "c": [
      {"n": "initialize", "c": [{"n": "loadConfig"}, {"n": "connectDB"}]},
      {"n": "startServer", "c": [{"n": "registerRoutes"}]}
    ]
  },
  "s": {"nodes": 6, "depth": 2}
}

TOON Output (v0.26.0+)

TOON输出(v0.26.0+)

TOON format offers ~50% fewer tokens than JSON:
bash
grepai trace graph "main" --depth 2 --toon
Note:
--json
and
--toon
are mutually exclusive.
TOON格式的 token 数量比JSON少约50%:
bash
grepai trace graph "main" --depth 2 --toon
注意:
--json
--toon
参数互斥。

Extraction Modes

提取模式

bash
undefined
bash
undefined

Fast mode (regex-based)

快速模式(基于正则表达式)

grepai trace graph "main" --mode fast
grepai trace graph "main" --mode fast

Precise mode (tree-sitter AST)

精确模式(基于tree-sitter抽象语法树)

grepai trace graph "main" --mode precise
undefined
grepai trace graph "main" --mode precise
undefined

Use Cases

使用场景示例

Understanding Application Flow

理解应用流程

bash
undefined
bash
undefined

Map entire application startup

映射整个应用启动流程

grepai trace graph "main" --depth 4
undefined
grepai trace graph "main" --depth 4
undefined

Impact Analysis

影响分析

bash
undefined
bash
undefined

What depends on this utility function?

哪些功能依赖这个工具函数?

grepai trace graph "validateInput" --depth 3
grepai trace graph "validateInput" --depth 3

Full impact of changing database layer

修改数据库层的全面影响

grepai trace graph "executeQuery" --depth 2
undefined
grepai trace graph "executeQuery" --depth 2
undefined

Code Review

代码审查

bash
undefined
bash
undefined

Is this function too complex?

这个函数是否过于复杂?

grepai trace graph "processOrder" --depth 5
grepai trace graph "processOrder" --depth 5

Many nodes = high complexity

节点数量多 = 复杂度高

undefined
undefined

Documentation

文档生成

bash
undefined
bash
undefined

Generate architecture diagram data

生成架构图数据

grepai trace graph "main" --depth 3 --json > architecture.json
undefined
grepai trace graph "main" --depth 3 --json > architecture.json
undefined

Refactoring Planning

重构规划

bash
undefined
bash
undefined

What would break if we change this?

如果修改这个函数会影响哪些部分?

grepai trace graph "legacyAuth" --depth 3
undefined
grepai trace graph "legacyAuth" --depth 3
undefined

Handling Cycles

处理循环依赖

GrepAI detects and marks circular dependencies:
main
├── processA
│   └── processB
│       └── processA [CYCLE]
In JSON:
json
{
  "name": "processA",
  "cycle": true
}
GrepAI会检测并标记循环依赖:
main
├── processA
│   └── processB
│       └── processA [CYCLE]
在JSON中:
json
{
  "name": "processA",
  "cycle": true
}

Large Graphs

大型调用图

For very large codebases, graphs can be overwhelming:
对于非常大的代码库,调用图可能会过于复杂:

Limit Depth

限制深度

bash
undefined
bash
undefined

Start shallow

从浅层开始分析

grepai trace graph "main" --depth 2
undefined
grepai trace graph "main" --depth 2
undefined

Focus on Specific Areas

聚焦特定领域

bash
undefined
bash
undefined

Instead of main, trace specific subsystem

不要分析main,而是追踪特定子系统

grepai trace graph "authMiddleware" --depth 3
undefined
grepai trace graph "authMiddleware" --depth 3
undefined

Filter in Post-Processing

后处理过滤

bash
undefined
bash
undefined

Get JSON and filter

获取JSON结果并进行过滤

grepai trace graph "main" --depth 3 --json | jq '...'
undefined
grepai trace graph "main" --depth 3 --json | jq '...'
undefined

Visualizing Graphs

可视化调用图

Export to DOT Format (Graphviz)

导出为DOT格式(Graphviz)

bash
undefined
bash
undefined

Convert JSON to DOT

将JSON转换为DOT格式

grepai trace graph "main" --depth 3 --json | python3 << 'EOF' import json import sys
data = json.load(sys.stdin)
print("digraph G {") print(" rankdir=TB;")
def traverse(node, parent=None): name = node.get('name') or node.get('n') if parent: print(f' "{parent}" -> "{name}";') children = node.get('children') or node.get('c') or [] for child in children: traverse(child, name)
traverse(data.get('root') or data.get('r')) print("}") EOF

Then render:
```bash
dot -Tpng graph.dot -o graph.png
grepai trace graph "main" --depth 3 --json | python3 << 'EOF' import json import sys
data = json.load(sys.stdin)
print("digraph G {") print(" rankdir=TB;")
def traverse(node, parent=None): name = node.get('name') or node.get('n') if parent: print(f' "{parent}" -> "{name}";') children = node.get('children') or node.get('c') or [] for child in children: traverse(child, name)
traverse(data.get('root') or data.get('r')) print("}") EOF

然后渲染:
```bash
dot -Tpng graph.dot -o graph.png

Mermaid Diagram

Mermaid图表

bash
grepai trace graph "main" --depth 2 --json | python3 << 'EOF'
import json
import sys

data = json.load(sys.stdin)

print("```mermaid")
print("graph TD")

def traverse(node, parent=None):
    name = node.get('name') or node.get('n')
    if parent:
        print(f"  {parent} --> {name}")
    children = node.get('children') or node.get('c') or []
    for child in children:
        traverse(child, name)

traverse(data.get('root') or data.get('r'))
print("```")
EOF
bash
grepai trace graph "main" --depth 2 --json | python3 << 'EOF'
import json
import sys

data = json.load(sys.stdin)

print("```mermaid")
print("graph TD")

def traverse(node, parent=None):
    name = node.get('name') or node.get('n')
    if parent:
        print(f"  {parent} --> {name}")
    children = node.get('children') or node.get('c') or []
    for child in children:
        traverse(child, name)

traverse(data.get('root') or data.get('r'))
print("```")
EOF

Comparing Graph Sizes

比较调用图大小

Track complexity over time:
bash
undefined
跟踪复杂度随时间的变化:
bash
undefined

Get node count

获取节点数量

grepai trace graph "main" --depth 3 --json | jq '.stats.nodes'
grepai trace graph "main" --depth 3 --json | jq '.stats.nodes'

Compare before/after refactoring

重构前后对比

echo "Before: $(grepai trace graph 'main' --depth 3 --json | jq '.stats.nodes') nodes"
echo "Before: $(grepai trace graph 'main' --depth 3 --json | jq '.stats.nodes') nodes"

... refactoring ...

... 执行重构 ...

echo "After: $(grepai trace graph 'main' --depth 3 --json | jq '.stats.nodes') nodes"
undefined
echo "After: $(grepai trace graph 'main' --depth 3 --json | jq '.stats.nodes') nodes"
undefined

Common Issues

常见问题

Problem: Graph too large / timeout ✅ Solutions:
  • Reduce depth:
    --depth 2
  • Trace specific function instead of
    main
  • Use
    --mode fast
Problem: Many cycles detected ✅ Solution: This indicates circular dependencies in code. Consider refactoring.
Problem: Missing branches ✅ Solutions:
  • Try
    --mode precise
  • Check if files are indexed
  • Verify language is enabled
❌ **问题:**调用图过大 / 超时 ✅ 解决方案:
  • 减少深度:
    --depth 2
  • 追踪特定函数而非
    main
  • 使用
    --mode fast
    模式
❌ **问题:**检测到大量循环依赖 ✅ **解决方案:**这表明代码中存在循环依赖,考虑进行重构。
❌ **问题:**缺少分支 ✅ 解决方案:
  • 尝试使用
    --mode precise
    模式
  • 检查文件是否已被索引
  • 验证语言是否已启用

Best Practices

最佳实践

  1. Start shallow: Begin with
    --depth 2
    , increase as needed
  2. Focus analysis: Trace specific functions, not always
    main
  3. Export for docs: Use JSON for generating diagrams
  4. Track over time: Monitor node count as complexity metric
  5. Investigate cycles: Circular dependencies are code smells
  1. **从浅层开始:**先使用
    --depth 2
    ,根据需要逐步增加深度
  2. **聚焦分析:**追踪特定函数,而非总是分析
    main
  3. **导出用于文档:**使用JSON格式生成图表
  4. **随时间跟踪:**将节点数量作为复杂度指标进行监控
  5. **调查循环依赖:**循环依赖是代码坏味道

Output Format

输出格式

Trace graph result:
🔍 Call Graph for "main"

Depth: 3
Mode: fast

main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB

Statistics:
- Total nodes: 12
- Maximum depth reached: 3
- Cycles detected: 0

Tip: Use --json for machine-readable output
     Use --depth N to control recursion depth
Trace graph结果示例:
🔍 Call Graph for "main"

Depth: 3
Mode: fast

main
├── initialize
│   ├── loadConfig
│   │   └── parseYAML
│   └── connectDB
│       ├── createPool
│       └── ping
├── startServer
│   ├── registerRoutes
│   │   ├── authMiddleware
│   │   └── loggingMiddleware
│   └── listen
└── gracefulShutdown
    └── closeDB

Statistics:
- Total nodes: 12
- Maximum depth reached: 3
- Cycles detected: 0

Tip: Use --json for machine-readable output
     Use --depth N to control recursion depth