techdebt

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tech Debt Scanner

技术债务扫描器

Automated technical debt detection using parallel subagents. Designed to run at session end to catch issues while context is fresh.
使用并行子Agent实现自动化技术债务检测。专为会话结束时运行设计,以便在上下文清晰时发现问题。

Quick Start

快速开始

bash
undefined
bash
undefined

Session end - scan changes since last commit (default)

会话结束 - 扫描上次提交后的变更(默认模式)

/techdebt
/techdebt

Deep scan - analyze entire codebase

深度扫描 - 分析整个代码库

/techdebt --deep
/techdebt --deep

Specific categories

指定分类扫描

/techdebt --duplicates # Only duplication /techdebt --security # Only security issues /techdebt --complexity # Only complexity hotspots /techdebt --deadcode # Only dead code
/techdebt --duplicates # 仅检测重复代码 /techdebt --security # 仅检测安全问题 /techdebt --complexity # 仅检测复杂度热点 /techdebt --deadcode # 仅检测死代码

Auto-fix mode (interactive)

自动修复模式(交互式)

/techdebt --fix
undefined
/techdebt --fix
undefined

Architecture

架构设计

Always uses parallel subagents for fast analysis:
Main Agent (orchestrator)
    ├─> Subagent 1: Duplication Scanner
    ├─> Subagent 2: Security Scanner
    ├─> Subagent 3: Complexity Scanner
    └─> Subagent 4: Dead Code Scanner

    ↓ All run in parallel (2-15s depending on scope)

Main Agent: Consolidate findings → Rank by severity → Generate report
Benefits:
  • 🚀 Parallel execution - all scans run simultaneously
  • 🧹 Clean main context - no pollution from analysis work
  • 💪 Scalable - handles large codebases efficiently
  • 🎯 Fast - even small diffs benefit from parallelization
始终使用并行子Agent以实现快速分析:
Main Agent(编排器)
    ├─> Subagent 1: 重复代码扫描器
    ├─> Subagent 2: 安全扫描器
    ├─> Subagent 3: 复杂度扫描器
    └─> Subagent 4: 死代码扫描器

    ↓ 所有扫描并行运行(根据范围耗时2-15秒)

Main Agent: 整合结果 → 按严重程度排序 → 生成报告
核心优势:
  • 🚀 并行执行 - 所有扫描任务同时运行
  • 🧹 保持主上下文清洁 - 分析工作不会污染主会话
  • 💪 可扩展 - 高效处理大型代码库
  • 🎯 速度快 - 即使是小范围差异也能从并行化中受益

Workflow

工作流程

Step 1: Determine Scope

步骤1:确定扫描范围

Default (no flags):
  • Scan files changed since last commit:
    git diff --name-only HEAD
  • Fast session-end workflow (~2-3 seconds)
  • Perfect for "wrap up" scenarios
Deep scan (
--deep
flag):
  • Scan entire codebase
  • Comprehensive analysis (~10-15 seconds for medium projects)
  • Use when refactoring or preparing major releases
Specific category (e.g.,
--duplicates
):
  • Run only specified scanner
  • Fastest option for targeted analysis
默认模式(无参数):
  • 扫描上次提交后变更的文件:
    git diff --name-only HEAD
  • 快速会话结束工作流(约2-3秒)
  • 非常适合"收尾"场景
深度扫描(
--deep
参数):
  • 扫描整个代码库
  • 全面分析(中型项目约10-15秒)
  • 重构或准备重大版本发布时使用
指定分类扫描(例如
--duplicates
):
  • 仅运行指定的扫描器
  • 针对特定分析的最快选项

Step 2: Spawn Parallel Subagents

步骤2:启动并行子Agent

Launch 4 subagents simultaneously (or subset if category specified):
Subagent 1: Duplication Scanner
  • Task: Find duplicated code blocks using AST similarity
  • Tools:
    ast-grep
    , structural search, token analysis
  • Output: List of duplicate code blocks with similarity scores
Subagent 2: Security Scanner
  • Task: Detect security vulnerabilities and anti-patterns
  • Checks: Hardcoded secrets, SQL injection, XSS, insecure crypto
  • Output: Security findings with severity and remediation guidance
Subagent 3: Complexity Scanner
  • Task: Identify overly complex functions and methods
  • Metrics: Cyclomatic complexity, nested depth, function length
  • Output: Complexity hotspots with refactoring suggestions
Subagent 4: Dead Code Scanner
  • Task: Find unused imports, variables, and unreachable code
  • Checks: Unused imports, dead branches, orphaned functions
  • Output: Dead code list with safe removal instructions
Subagent instructions template:
Scan {scope} for {category} issues.

Scope: {file_list or "entire codebase"}
Language: {detected from file extensions}
Focus: {category-specific patterns}

Output format:
- File path + line number
- Issue description
- Severity (P0-P3)
- Suggested fix (if available)

Use appropriate tools:
- Duplication: ast-grep for structural similarity
- Security: pattern matching + known vulnerability patterns
- Complexity: cyclomatic complexity calculation
- Dead Code: static analysis for unused symbols
同时启动4个子Agent(如果指定分类则启动对应子集):
Subagent 1: 重复代码扫描器
  • 任务:使用AST相似度查找重复代码块
  • 工具:
    ast-grep
    、结构化搜索、令牌分析
  • 输出:带相似度评分的重复代码块列表
Subagent 2: 安全扫描器
  • 任务:检测安全漏洞和反模式
  • 检查项:硬编码密钥、SQL注入、XSS、不安全加密
  • 输出:带严重程度和修复指南的安全问题列表
Subagent 3: 复杂度扫描器
  • 任务:识别过度复杂的函数和方法
  • 指标:圈复杂度、嵌套深度、函数长度
  • 输出:带重构建议的复杂度热点
Subagent 4: 死代码扫描器
  • 任务:查找未使用的导入、变量和不可达代码
  • 检查项:未使用的导入、死分支、孤立函数
  • 输出:带安全移除说明的死代码列表
Subagent指令模板:
扫描{scope}中的{category}问题。

范围:{file_list或"整个代码库"}
语言:{从文件扩展名自动检测}
重点:{分类特定模式}

输出格式:
- 文件路径 + 行号
- 问题描述
- 严重程度(P0-P3)
- 建议修复方案(如有)

使用合适的工具:
- 重复代码:使用ast-grep进行结构相似度检测
- 安全:模式匹配 + 已知漏洞模式
- 复杂度:圈复杂度计算
- 死代码:静态分析未使用的符号

Step 3: Consolidate Findings

步骤3:整合扫描结果

Main agent collects results from all subagents and:
  1. Deduplicate - Remove duplicate findings across categories
  2. Rank by severity:
    • P0 (Critical): Security vulnerabilities, blocking issues
    • P1 (High): Major duplication, high complexity
    • P2 (Medium): Minor duplication, moderate complexity
    • P3 (Low): Dead code, style issues
  3. Group by file - Organize findings by affected file
  4. Calculate debt score - Overall technical debt metric
主Agent收集所有子Agent的结果并执行以下操作:
  1. 去重 - 移除跨分类的重复发现
  2. 按严重程度排序:
    • P0(关键): 安全漏洞、阻塞性问题
    • P1(高优先级): 大量重复代码、高复杂度
    • P2(中优先级): 少量重复代码、中等复杂度
    • P3(低优先级): 死代码、风格问题
  3. 按文件分组 - 按受影响的文件组织发现的问题
  4. 计算债务分数 - 整体技术债务指标

Step 4: Generate Report

步骤4:生成报告

Create actionable report with:
markdown
undefined
创建可执行的报告,格式如下:
markdown
undefined

Tech Debt Report

技术债务报告

Scope: {X files changed | Entire codebase} Scan Time: {duration} Debt Score: {0-100, lower is better}
扫描范围: {X个变更文件 | 整个代码库} 扫描时间: {耗时} 债务分数: {0-100,分数越低越好}

Summary

摘要

CategoryFindingsP0P1P2P3
DuplicationX-XX-
SecurityXX---
ComplexityX-XX-
Dead CodeX--XX
分类发现问题数P0P1P2P3
重复代码X-XX-
安全XX---
复杂度X-XX-
死代码X--XX

Critical Issues (P0)

关键问题(P0)

{file_path}:{line}

{file_path}:{line}

Category: {Security} Issue: Hardcoded API key detected Impact: Credential exposure risk Fix: Move to environment variable
分类: {安全} 问题: 检测到硬编码API密钥 影响: 存在凭证泄露风险 修复: 迁移到环境变量

High Priority (P1)

高优先级问题(P1)

{file_path}:{line}

{file_path}:{line}

Category: {Duplication} Issue: 45-line block duplicated across 3 files Impact: Maintenance burden, inconsistency risk Fix: Extract to shared utility function
[... continue for all findings ...]
分类: {重复代码} 问题: 45行代码块在3个文件中重复 影响: 维护负担、不一致风险 修复: 提取为共享工具函数
[... 所有问题依次列出 ...]

Recommendations

建议

  1. Address all P0 issues before merge
  2. Consider refactoring high-complexity functions
  3. Remove dead code to reduce maintenance burden
  1. 合并前解决所有P0问题
  2. 考虑重构高复杂度函数
  3. 移除死代码以降低维护负担

Auto-Fix Available

自动修复可用

Run
/techdebt --fix
to interactively apply safe automated fixes.
undefined
运行
/techdebt --fix
以交互式应用安全的自动修复。
undefined

Step 5: Auto-Fix Mode (Optional)

步骤5:自动修复模式(可选)

If
--fix
flag provided:
  1. Identify safe fixes:
    • Dead import removal (safe)
    • Simple duplication extraction (review required)
    • Formatting fixes (safe)
  2. Interactive prompts:
    Fix: Remove unused import 'requests' from utils.py:5
    [Y]es / [N]o / [A]ll / [Q]uit
  3. Apply changes:
    • Edit files with confirmed fixes
    • Show git diff of changes
    • Prompt for commit
Safety rules:
  • Never auto-fix security issues (require manual review)
  • Never auto-fix complexity (requires design decisions)
  • Only auto-fix with explicit user confirmation
如果提供
--fix
参数:
  1. 识别安全修复项:
    • 移除未使用的导入(安全)
    • 简单重复代码提取(需要审核)
    • 格式修复(安全)
  2. 交互式提示:
    修复:移除utils.py第5行未使用的导入'requests'
    [Y]确认 / [N]跳过 / [A]全部确认 / [Q]退出
  3. 应用变更:
    • 编辑文件应用已确认的修复
    • 显示变更的git diff
    • 提示提交变更
安全规则:
  • 绝不自动修复安全问题(需要人工审核)
  • 绝不自动修复复杂度问题(需要设计决策)
  • 仅在用户明确确认后应用自动修复

Detection Patterns

检测模式

Duplication

重复代码

AST Similarity Detection:
  • Use
    ast-grep
    for structural pattern matching
  • Detect code blocks with >80% structural similarity
  • Ignore trivial differences (variable names, whitespace)
Token-based Analysis:
  • Compare token sequences for exact duplicates
  • Minimum threshold: 6 consecutive lines
  • Group similar duplicates across files
Thresholds:
  • P1: 30+ lines duplicated in 3+ locations
  • P2: 15+ lines duplicated in 2+ locations
  • P3: 6+ lines duplicated in 2 locations
AST相似度检测:
  • 使用
    ast-grep
    进行结构模式匹配
  • 检测结构相似度>80%的代码块
  • 忽略微小差异(变量名、空白符)
令牌分析:
  • 比较令牌序列查找完全重复
  • 最小阈值:6行连续重复
  • 跨文件分组相似重复项
阈值:
  • P1:30+行代码在3+位置重复
  • P2:15+行代码在2+位置重复
  • P3:6+行代码在2个位置重复

Security

安全

Pattern Detection:
PatternSeverityExample
Hardcoded secretsP0
API_KEY = "sk-..."
SQL injection riskP0
f"SELECT * FROM users WHERE id={user_id}"
Insecure cryptoP0
hashlib.md5()
,
random.random()
for tokens
Path traversalP0
open(user_input)
without validation
XSS vulnerabilityP0Unescaped user input in HTML
Eval/exec usageP1
eval(user_input)
Weak passwordsP2Hardcoded default passwords
Language-specific checks:
  • Python:
    pickle
    usage,
    yaml.load()
    without SafeLoader
  • JavaScript:
    eval()
    ,
    innerHTML
    with user data
  • SQL: String concatenation in queries
模式检测:
模式严重程度示例
硬编码密钥P0
API_KEY = "sk-..."
SQL注入风险P0
f"SELECT * FROM users WHERE id={user_id}"
不安全加密P0
hashlib.md5()
,
random.random()
用于生成令牌
路径遍历P0
open(user_input)
未做验证
XSS漏洞P0HTML中使用未转义的用户输入
使用eval/execP1
eval(user_input)
弱密码P2硬编码默认密码
语言特定检查:
  • Python:
    pickle
    使用、
    yaml.load()
    未使用SafeLoader
  • JavaScript:
    eval()
    、使用用户数据的
    innerHTML
  • SQL:查询中使用字符串拼接

Complexity

复杂度

Metrics:
MetricP1 ThresholdP2 Threshold
Cyclomatic Complexity>15>10
Function Length>100 lines>50 lines
Nested Depth>5 levels>4 levels
Number of Parameters>7>5
Refactoring suggestions:
  • Extract method for long functions
  • Introduce parameter object for many parameters
  • Simplify conditionals with guard clauses
  • Break up deeply nested logic
指标:
指标P1阈值P2阈值
圈复杂度>15>10
函数长度>100行>50行
嵌套深度>5层>4层
参数数量>7个>5个
重构建议:
  • 长函数提取为方法
  • 多参数使用参数对象
  • 使用卫语句简化条件判断
  • 拆分深度嵌套逻辑

Dead Code

死代码

Detection methods:
  • Unused imports (language-specific linters)
  • Unreachable code (after return/break/continue)
  • Unused variables (written but never read)
  • Orphaned functions (never called in codebase)
Safe removal criteria:
  • No external references found
  • Not part of public API
  • Not dynamically imported/called
检测方法:
  • 未使用的导入(语言特定的lint工具)
  • 不可达代码(在return/break/continue之后)
  • 未使用的变量(已定义但从未读取)
  • 孤立函数(代码库中从未被调用)
安全移除标准:
  • 未发现外部引用
  • 不属于公共API
  • 未被动态导入/调用

Language Support

语言支持

Tier 1 (Full support):
  • Python:
    ast-grep
    ,
    radon
    ,
    pylint
  • JavaScript/TypeScript:
    ast-grep
    ,
    eslint
    ,
    jscpd
  • Go:
    gocyclo
    ,
    golangci-lint
  • Rust:
    clippy
    ,
    cargo-audit
Tier 2 (Basic support):
  • Java, C#, Ruby, PHP: Pattern-based detection only
Language detection:
  • Auto-detect from file extensions
  • Use appropriate tools per language
  • Fallback to universal patterns if specific tools unavailable
一级支持(完整功能):
  • Python:
    ast-grep
    ,
    radon
    ,
    pylint
  • JavaScript/TypeScript:
    ast-grep
    ,
    eslint
    ,
    jscpd
  • Go:
    gocyclo
    ,
    golangci-lint
  • Rust:
    clippy
    ,
    cargo-audit
二级支持(基础功能):
  • Java, C#, Ruby, PHP:仅支持基于模式的检测
语言检测:
  • 从文件扩展名自动检测
  • 针对不同语言使用合适的工具
  • 如果特定工具不可用, fallback到通用模式

Integration Patterns

集成模式

Session End Automation

会话结束自动化

Add to your workflow:
markdown
undefined
添加到你的工作流:
markdown
undefined

Session Wrap-Up Checklist

会话收尾检查清单

  • Run
    /techdebt
    to scan changes
  • Address any P0 issues found
  • Create tasks for P1/P2 items
  • Commit clean code
undefined
  • 运行
    /techdebt
    扫描变更
  • 解决所有发现的P0问题
  • 为P1/P2问题创建任务
  • 提交干净代码
undefined

Pre-Commit Hook

提交前钩子

Create
.claude/hooks/pre-commit.sh
:
bash
#!/bin/bash
创建
.claude/hooks/pre-commit.sh
bash
#!/bin/bash

Auto-run tech debt scan before commits

提交前自动运行技术债务扫描

echo "🔍 Scanning for tech debt..." claude skill techdebt --quiet
if [ $? -eq 1 ]; then echo "❌ P0 issues detected. Fix before committing." exit 1 fi
echo "✅ No critical issues found"
undefined
echo "🔍 正在扫描技术债务..." claude skill techdebt --quiet
if [ $? -eq 1 ]; then echo "❌ 检测到P0问题。修复后再提交。" exit 1 fi
echo "✅ 未发现关键问题"
undefined

CI/CD Integration

CI/CD集成

Run deep scan on pull requests:
yaml
undefined
在拉取请求上运行深度扫描:
yaml
undefined

.github/workflows/techdebt.yml

.github/workflows/techdebt.yml

name: Tech Debt Check on: [pull_request] jobs: scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Run tech debt scan run: claude skill techdebt --deep --ci
undefined
name: 技术债务检查 on: [pull_request] jobs: scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: 运行技术债务扫描 run: claude skill techdebt --deep --ci
undefined

Advanced Usage

高级用法

Baseline Tracking

基线跟踪

Track debt over time:
bash
undefined
随时间跟踪债务变化:
bash
undefined

Initial baseline

初始化基线

/techdebt --deep --save-baseline
/techdebt --deep --save-baseline

Compare against baseline

与基线比较

/techdebt --compare-baseline
/techdebt --compare-baseline

Output: "Debt increased by 15% since baseline"

输出:"自基线以来债务增加了15%"


Baseline stored in `.claude/techdebt-baseline.json`:

```json
{
  "timestamp": "2026-02-03T10:00:00Z",
  "commit": "a28f0fb",
  "score": 42,
  "findings": {
    "duplication": 8,
    "security": 0,
    "complexity": 12,
    "deadcode": 5
  }
}

基线存储在`.claude/techdebt-baseline.json`:

```json
{
  "timestamp": "2026-02-03T10:00:00Z",
  "commit": "a28f0fb",
  "score": 42,
  "findings": {
    "duplication": 8,
    "security": 0,
    "complexity": 12,
    "deadcode": 5
  }
}

Custom Patterns

自定义模式

Add project-specific patterns in
.claude/techdebt-rules.json
:
json
{
  "security": [
    {
      "pattern": "TODO.*security",
      "severity": "P0",
      "message": "Security TODO must be resolved"
    }
  ],
  "complexity": {
    "cyclomatic_threshold": 12,
    "function_length_threshold": 80
  }
}
.claude/techdebt-rules.json
中添加项目特定模式:
json
{
  "security": [
    {
      "pattern": "TODO.*security",
      "severity": "P0",
      "message": "必须解决安全相关的TODO"
    }
  ],
  "complexity": {
    "cyclomatic_threshold": 12,
    "function_length_threshold": 80
  }
}

Report Formats

报告格式

bash
/techdebt --format=json     # JSON output for tooling
/techdebt --format=markdown # Markdown report (default)
/techdebt --format=sarif    # SARIF for IDE integration
bash
/techdebt --format=json     # 工具友好的JSON输出
/techdebt --format=markdown # Markdown报告(默认)
/techdebt --format=sarif    # SARIF格式用于IDE集成

Troubleshooting

故障排除

Issue: Scan times out
  • Solution: Use
    --deep
    only on smaller modules, or increase timeout
  • Consider: Break large codebases into smaller scan chunks
Issue: Too many false positives
  • Solution: Adjust thresholds in
    .claude/techdebt-rules.json
  • Consider: Use
    --ignore-patterns
    flag to exclude test files
Issue: Missing dependencies (ast-grep, etc.)
  • Solution: Install tools via
    npm install -g @ast-grep/cli
    or skip category
  • Fallback: Pattern-based detection still works without specialized tools
问题:扫描超时
  • 解决方案:仅对较小模块使用
    --deep
    ,或增加超时时间
  • 建议:将大型代码库拆分为较小的扫描块
问题:误报过多
  • 解决方案:在
    .claude/techdebt-rules.json
    中调整阈值
  • 建议:使用
    --ignore-patterns
    参数排除测试文件
问题:缺少依赖(如ast-grep)
  • 解决方案:通过
    npm install -g @ast-grep/cli
    安装工具,或跳过对应分类
  • Fallback:即使没有专用工具,基于模式的检测仍然有效

Best Practices

最佳实践

  1. Run at every session end - Catch debt while context is fresh
  2. Address P0 immediately - Don't commit critical issues
  3. Create tasks for P1/P2 - Track technical debt in backlog
  4. Use baselines for trends - Monitor debt accumulation over time
  5. Automate in CI/CD - Prevent debt from merging
  6. Educate team - Share findings, discuss refactoring strategies
  1. 每次会话结束都运行 - 在上下文清晰时发现债务
  2. 立即解决P0问题 - 不要提交关键问题
  3. 为P1/P2创建任务 - 在待办事项中跟踪技术债务
  4. 使用基线跟踪趋势 - 随时间监控债务累积
  5. 在CI/CD中自动化 - 防止债务被合并
  6. 团队培训 - 共享发现,讨论重构策略

References

参考资料

See also:
  • Anthropic's Agent Skills - Subagent patterns
  • references/patterns.md - Language-specific debt patterns
  • references/severity-guide.md - How to rank findings
另请参阅:
  • Anthropic's Agent Skills - 子Agent模式
  • references/patterns.md - 语言特定债务模式
  • references/severity-guide.md - 问题严重程度排名指南