quality-detect-orphaned-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Detect Orphaned Code

检测孤立代码

Quick Start

快速开始

Run orphan detection before marking any feature complete:
bash
undefined
在标记任何功能完成前执行孤立代码检测:
bash
undefined

Quick check for a specific module

快速检查特定模块

grep -r "from.*your_module import|import.your_module" src/ --include=".py" | grep -v test
grep -r "from.*your_module import|import.your_module" src/ --include=".py" | grep -v test

If output is EMPTY → Module is orphaned (not imported in production)

如果输出为空 → 模块是孤立的(未在生产环境中被导入)

Comprehensive orphan detection (if script exists)

全面孤立代码检测(若脚本已存在)

./scripts/verify_integration.sh
./scripts/verify_integration.sh

Check specific function usage

检查特定函数的使用情况

grep -r "your_function_name" src/ --include=".py" | grep -v test | grep -v "^[^:]:.*def "
grep -r "your_function_name" src/ --include=".py" | grep -v test | grep -v "^[^:]:.*def "

If output is EMPTY → Function is orphaned (never called)

如果输出为空 → 函数是孤立的(从未被调用)

undefined
undefined

Table of Contents

目录

  1. When to Use This Skill
  2. What This Skill Does
  3. Types of Orphaned Code
  4. Detection Methods
  5. Step-by-Step Detection Process
  6. Automated Detection Scripts
  7. Integration with Quality Gates
  8. Supporting Files
  9. Expected Outcomes
  10. Requirements
  11. Red Flags to Avoid
  1. 使用场景
  2. 功能说明
  3. 孤立代码的类型
  4. 检测方法
  5. 分步检测流程
  6. 自动化检测脚本
  7. 与质量门禁集成
  8. 支持文件
  9. 预期结果
  10. 要求
  11. 注意事项

When to Use This Skill

使用场景

Explicit Triggers

明确触发场景

  • "Detect orphaned code"
  • "Find dead code in the project"
  • "Check for unused modules"
  • "Verify no orphaned files exist"
  • "Find code that's never imported"
  • "Check for integration gaps"
  • “检测孤立代码”
  • “查找项目中的死代码”
  • “检查未使用的模块”
  • “验证无孤立文件存在”
  • “查找从未被导入的代码”
  • “检查集成缺口”

Implicit Triggers (PROACTIVE)

主动触发场景

  • Before marking any feature complete
  • Before moving ADR from in_progress to completed
  • After creating new Python modules
  • After major refactoring
  • As part of pre-commit quality gates
  • During code review
  • 标记任何功能完成前
  • 将ADR从进行中移至已完成状态前
  • 创建新Python模块后
  • 重大重构后
  • 作为提交前质量门禁的一部分
  • 代码评审期间

Debugging Triggers

调试触发场景

  • "Tests pass but feature doesn't work" (often orphaned code)
  • "File exists but nothing happens when I run it"
  • "Why isn't my new module being used?"
  • "Code review found unused imports"
  • “测试通过但功能无法正常工作”(通常是孤立代码导致)
  • “文件存在但运行后无任何反应”
  • “为什么我的新模块未被使用?”
  • “代码评审发现未使用的导入”

What This Skill Does

功能说明

This skill detects code that exists but is never used, preventing the ADR-013 failure mode:
What it detects:
  1. Orphaned modules - Python files never imported in production code
  2. Orphaned functions - Functions defined but never called
  3. Orphaned classes - Classes defined but never instantiated
  4. Orphaned nodes - LangGraph nodes never added to graph
  5. Dead code paths - Code wired but conditionals never trigger
What it prevents:
  • Marking incomplete features as "done"
  • Moving ADRs to completed when code isn't integrated
  • Accumulating technical debt (unused code)
  • Confusion for future developers (why does this exist?)
Why existing tools miss this:
  • vulture - Can be fooled by unit tests that import modules
  • mypy - Only checks types, not usage
  • pytest - Can pass 100% coverage on orphaned modules
  • ruff - Checks style, not integration
This skill complements those tools by checking integration explicitly.
该技能可检测存在但从未被使用的代码,避免ADR-013故障模式:
检测范围:
  1. 孤立模块 - 从未在生产代码中被导入的Python文件
  2. 孤立函数 - 已定义但从未被调用的函数
  3. 孤立类 - 已定义但从未被实例化的类
  4. 孤立LangGraph节点 - 已创建但从未添加到图中的LangGraph节点
  5. 死代码路径 - 已集成但条件分支从未触发的代码
预防的问题:
  • 将未完成的功能标记为“已完成”
  • 代码未集成时就将ADR移至已完成状态
  • 积累技术债务(未使用的代码)
  • 给后续开发者造成困惑(这段代码存在的意义是什么?)
现有工具的局限性:
  • vulture - 会被导入模块的单元测试误导
  • mypy - 仅检查类型,不检查使用情况
  • pytest - 孤立模块也能获得100%的测试覆盖率
  • ruff - 仅检查代码风格,不检查集成情况
本技能可作为这些工具的补充,明确检查代码的集成状态。

Types of Orphaned Code

孤立代码的类型

Type 1: Orphaned Module (File Never Imported)

类型1:孤立模块(文件从未被导入)

Symptom: Python file exists, has tests, but is never imported in production code
Example:
python
undefined
症状: Python文件存在且有测试用例,但从未在生产代码中被导入
示例:
python
undefined

File: src/myapp/features/new_feature.py (175 lines)

文件: src/myapp/features/new_feature.py (175行)

def process_data(data: dict) -> Result: """Process data and return result.""" # ... implementation ...

**Detection:**
```bash
$ grep -r "from.*new_feature import\|import.*new_feature" src/ --include="*.py" | grep -v test
(empty) ❌
Root cause: File created but never imported in integration point
Fix: Import in the consuming module
def process_data(data: dict) -> Result: """处理数据并返回结果。""" # ... 实现代码 ...

**检测命令:**
```bash
$ grep -r "from.*new_feature import\|import.*new_feature" src/ --include="*.py" | grep -v test
(空输出) ❌
根本原因: 文件已创建但从未在集成点被导入
修复方案: 在消费模块中导入该文件

Type 2: Orphaned Function (Defined But Never Called)

类型2:孤立函数(已定义但从未被调用)

Symptom: Function exists in imported module but is never called
Example:
python
undefined
症状: 函数存在于已导入的模块中,但从未被调用
示例:
python
undefined

File: src/myapp/services/utils.py

文件: src/myapp/services/utils.py

def helper_function(x: int) -> int: # Orphaned return x * 2
def another_function(x: int) -> int: # Used return x + 1

**Detection:**
```bash
$ grep -r "helper_function" src/ --include="*.py" | grep -v test | grep -v "def helper_function"
(empty) ❌  # Only definition, no call-sites

$ grep -r "another_function" src/ --include="*.py" | grep -v test | grep -v "def another_function"
src/myapp/main.py:45:    result = another_function(5)  ✅  # Has call-site
Root cause: Function created but never invoked
Fix: Call the function where needed, or remove it
def helper_function(x: int) -> int: # 孤立函数 return x * 2
def another_function(x: int) -> int: # 已使用 return x + 1

**检测命令:**
```bash
$ grep -r "helper_function" src/ --include="*.py" | grep -v test | grep -v "def helper_function"
(空输出) ❌  # 仅存在定义,无调用位置

$ grep -r "another_function" src/ --include="*.py" | grep -v test | grep -v "def another_function"
src/myapp/main.py:45:    result = another_function(5)  ✅  # 存在调用位置
根本原因: 函数已创建但从未被调用
修复方案: 在需要的位置调用该函数,或删除它

Type 3: Orphaned Class (Defined But Never Instantiated)

类型3:孤立类(已定义但从未被实例化)

Symptom: Class exists but is never instantiated or subclassed
Example:
python
undefined
症状: 类已存在但从未被实例化或继承
示例:
python
undefined

File: src/myapp/models/new_model.py

文件: src/myapp/models/new_model.py

class NewModel: def init(self, data: dict) -> None: self.data = data

**Detection:**
```bash
$ grep -r "NewModel" src/ --include="*.py" | grep -v test | grep -v "class NewModel"
(empty) ❌  # Only definition, no instantiation
Root cause: Class created but never used
Fix: Instantiate where needed, or remove
class NewModel: def init(self, data: dict) -> None: self.data = data

**检测命令:**
```bash
$ grep -r "NewModel" src/ --include="*.py" | grep -v test | grep -v "class NewModel"
(空输出) ❌  # 仅存在定义,无实例化操作
根本原因: 类已创建但从未被使用
修复方案: 在需要的位置实例化该类,或删除它

Type 4: Orphaned LangGraph Node (Node File Exists But Not in Graph)

类型4:孤立LangGraph节点(节点文件存在但未加入图)

Symptom: Node factory function exists but is never added to graph
Example:
python
undefined
症状: 节点工厂函数存在但从未被添加到图中
示例:
python
undefined

File: src/myapp/graph/architecture_nodes.py

文件: src/myapp/graph/architecture_nodes.py

async def create_architecture_review_node(agent): """Create architecture review node.""" # ... implementation ...

**Detection:**
```bash
$ grep "architecture_nodes" src/myapp/graph/builder.py
(empty) ❌  # Not imported in builder

$ grep "add_node.*architecture_review" src/myapp/graph/builder.py
(empty) ❌  # Not added to graph
Root cause: Node created but never wired into graph
Fix: Import and add to graph in builder.py
async def create_architecture_review_node(agent): """创建架构评审节点。""" # ... 实现代码 ...

**检测命令:**
```bash
$ grep "architecture_nodes" src/myapp/graph/builder.py
(空输出) ❌  # 未在构建器中被导入

$ grep "add_node.*architecture_review" src/myapp/graph/builder.py
(空输出) ❌  # 未被添加到图中
根本原因: 节点已创建但从未接入图中
修复方案: 在builder.py中导入并添加该节点到图中

Type 5: Dead Code Path (Code Wired But Conditional Never Triggers)

类型5:死代码路径(已集成但条件从未触发)

Symptom: Code is integrated but the path to reach it never executes
Example:
python
undefined
症状: 代码已集成但对应的执行路径从未被触发
示例:
python
undefined

In builder.py

在builder.py中

if settings.enable_experimental_features: # Never True in production graph.add_node("experimental", experimental_node)

**Detection:**
```bash
if settings.enable_experimental_features: # 生产环境中始终为False graph.add_node("experimental", experimental_node)

**检测方法:**
```bash

Check configuration

检查配置

$ grep "enable_experimental_features" .env
$ grep "enable_experimental_features" .env

Not set (defaults to False)

未设置(默认值为False)

Check logs for execution

检查执行日志

$ grep "experimental" logs/*.log (empty) ❌ # Never executes

**Root cause:** Conditional never true in practice

**Fix:** Enable the condition or remove the dead path
$ grep "experimental" logs/*.log (空输出) ❌ # 从未执行

**根本原因:** 条件在实际环境中始终不成立

**修复方案:** 启用该条件或删除该死代码路径

Detection Methods

检测方法

Method 1: Manual Grep (Quick Check)

方法1:手动Grep(快速检查)

For a specific module:
bash
undefined
针对特定模块:
bash
undefined

Check if module is imported

检查模块是否被导入

grep -r "from.*MODULE_NAME import|import.MODULE_NAME" src/ --include=".py" | grep -v test
grep -r "from.*MODULE_NAME import|import.MODULE_NAME" src/ --include=".py" | grep -v test

Expected: At least one import line from production code

预期结果:至少有一行来自生产代码的导入

If empty: Module is orphaned

如果输出为空:模块是孤立的


**For a specific function:**
```bash

**针对特定函数:**
```bash

Check if function is called

检查函数是否被调用

grep -r "FUNCTION_NAME" src/ --include="*.py" | grep -v test | grep -v "def FUNCTION_NAME"
grep -r "FUNCTION_NAME" src/ --include="*.py" | grep -v test | grep -v "def FUNCTION_NAME"

Expected: At least one call-site

预期结果:至少有一个调用位置

If empty: Function is orphaned

如果输出为空:函数是孤立的


**For a specific class:**
```bash

**针对特定类:**
```bash

Check if class is instantiated

检查类是否被实例化

grep -r "CLASS_NAME(" src/ --include="*.py" | grep -v test | grep -v "class CLASS_NAME"
grep -r "CLASS_NAME(" src/ --include="*.py" | grep -v test | grep -v "class CLASS_NAME"

Expected: At least one instantiation

预期结果:至少有一个实例化操作

If empty: Class is orphaned

如果输出为空:类是孤立的

undefined
undefined

Method 2: Comprehensive Script (Automated)

方法2:全面脚本检测(自动化)

Script:
scripts/verify_integration.sh
bash
#!/bin/bash
脚本:
scripts/verify_integration.sh
bash
#!/bin/bash

Detects orphaned modules (created but never imported in production)

检测孤立模块(已创建但从未在生产环境中被导入)

set -e
echo "=== Orphan Detection ==="
RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m'
orphaned=0 checked=0
for file in $(find src/ -name "*.py" -type f | sort); do module=$(basename "$file" .py) dir=$(dirname "$file")
# Skip special files
[[ "$module" == "__init__" ]] && continue
[[ "$module" == "__main__" ]] && continue
[[ "$module" == "main" ]] && continue
[[ "$module" == *"test"* ]] && continue

checked=$((checked + 1))

# Check if module is imported (excluding self and tests)
imports=$(grep -r -E "import\s+.*\b${module}\b|from\s+.*\b${module}\b\s+import" src/ \
          --include="*.py" 2>/dev/null | \
          grep -v "$file" | \
          grep -v "test_" | \
          grep -v "__pycache__" | \
          wc -l | tr -d ' ')

if [ "$imports" -eq 0 ]; then
    # Check if exported via __init__.py
    init_file="$dir/__init__.py"
    init_export=0
    if [ -f "$init_file" ]; then
        init_export=$(grep -c "\b$module\b" "$init_file" 2>/dev/null || echo "0")
    fi

    if [ "$init_export" -eq 0 ]; then
        echo -e "${YELLOW}⚠️  ORPHANED:${NC} $file"
        echo "   No production imports found"
        orphaned=$((orphaned + 1))
    fi
fi
done
echo "" echo "=== Results ===" echo "Modules checked: $checked"
if [ $orphaned -gt 0 ]; then echo -e "${RED}❌ ERROR: $orphaned orphaned module(s) found${NC}" echo "" echo "These files exist but are never imported in production code." echo "Either wire them up or remove them." exit 1 fi
echo -e "${GREEN}✅ All modules are integrated${NC}" exit 0
undefined
set -e
echo "=== 孤立代码检测 ==="
RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m'
orphaned=0 checked=0
for file in $(find src/ -name "*.py" -type f | sort); do module=$(basename "$file" .py) dir=$(dirname "$file")
# 跳过特殊文件
[[ "$module" == "__init__" ]] && continue
[[ "$module" == "__main__" ]] && continue
[[ "$module" == "main" ]] && continue
[[ "$module" == *"test"* ]] && continue

checked=$((checked + 1))

# 检查模块是否被导入(排除自身和测试文件)
imports=$(grep -r -E "import\s+.*\b${module}\b|from\s+.*\b${module}\b\s+import" src/ \
          --include="*.py" 2>/dev/null | \
          grep -v "$file" | \
          grep -v "test_" | \
          grep -v "__pycache__" | \
          wc -l | tr -d ' ')

if [ "$imports" -eq 0 ]; then
    # 检查是否通过__init__.py导出
    init_file="$dir/__init__.py"
    init_export=0
    if [ -f "$init_file" ]; then
        init_export=$(grep -c "\b$module\b" "$init_file" 2>/dev/null || echo "0")
    fi

    if [ "$init_export" -eq 0 ]; then
        echo -e "${YELLOW}⚠️  孤立模块:${NC} $file"
        echo "   未找到生产环境中的导入"
        orphaned=$((orphaned + 1))
    fi
fi
done
echo "" echo "=== 检测结果 ===" echo "已检查模块数量: $checked"
if [ $orphaned -gt 0 ]; then echo -e "${RED}❌ 错误: 发现$orphaned个孤立模块${NC}" echo "" echo "这些文件存在但从未在生产代码中被导入。" echo "请将它们接入系统或删除。" exit 1 fi
echo -e "${GREEN}✅ 所有模块均已集成${NC}" exit 0
undefined

Method 3: Integration Test (LangGraph-Specific)

方法3:集成测试(LangGraph专属)

Test:
tests/integration/test_graph_completeness.py
python
"""Verify all expected nodes are in the compiled graph."""

import pytest
from langgraph.checkpoint.memory import MemorySaver

from myapp.graph.builder import create_coordination_graph
测试文件:
tests/integration/test_graph_completeness.py
python
"""验证所有预期节点均已加入编译后的图中。"""

import pytest
from langgraph.checkpoint.memory import MemorySaver

from myapp.graph.builder import create_coordination_graph

List ALL nodes that should be in the graph

列出所有应在图中的节点

EXPECTED_NODES: list[str] = [ "query_claude", "analyze_task", "architecture_review", # Add new nodes here # ... other nodes ]
@pytest.mark.asyncio async def test_all_expected_nodes_in_graph() -> None: """Verify all expected nodes are wired into the graph.""" graph = await create_coordination_graph(MemorySaver()) actual_nodes = list(graph.get_graph().nodes.keys())
# Filter internal nodes
actual_nodes = [n for n in actual_nodes if not n.startswith("__")]

missing = [n for n in EXPECTED_NODES if n not in actual_nodes]

assert not missing, (
    f"Nodes in EXPECTED_NODES but not in graph: {missing}. "
    f"Either wire these nodes into builder.py or remove from EXPECTED_NODES."
)
undefined
EXPECTED_NODES: list[str] = [ "query_claude", "analyze_task", "architecture_review", # 在此处添加新节点 # ... 其他节点 ]
@pytest.mark.asyncio async def test_all_expected_nodes_in_graph() -> None: """验证所有预期节点均已接入图中。""" graph = await create_coordination_graph(MemorySaver()) actual_nodes = list(graph.get_graph().nodes.keys())
# 过滤内部节点
actual_nodes = [n for n in actual_nodes if not n.startswith("__")]

missing = [n for n in EXPECTED_NODES if n not in actual_nodes]

assert not missing, (
    f"预期节点中存在但未在图中的节点: {missing}. "
    f"请将这些节点接入builder.py或从EXPECTED_NODES中移除。"
)
undefined

Step-by-Step Detection Process

分步检测流程

Step 1: Identify Candidates

步骤1:识别候选文件

List all Python files that could be orphaned:
bash
undefined
列出所有可能是孤立代码的Python文件:
bash
undefined

Find all .py files (excluding tests and special files)

查找所有.py文件(排除测试文件和特殊文件)

find src/ -name "*.py" -type f |
grep -v pycache |
grep -v test_ |
grep -v init.py |
sort

**Output:** List of candidate files to check
find src/ -name "*.py" -type f |
grep -v pycache |
grep -v test_ |
grep -v init.py |
sort

**输出:** 待检查的候选文件列表

Step 2: Check Each Candidate

步骤2:检查每个候选文件

For each file from Step 1:
bash
undefined
针对步骤1中的每个文件:
bash
undefined

Extract module name

提取模块名称

MODULE=$(basename "$file" .py)
MODULE=$(basename "$file" .py)

Check for imports

检查导入情况

echo "Checking: $MODULE" grep -r "from.$MODULE import|import.$MODULE" src/ --include="*.py" | grep -v test
echo "正在检查: $MODULE" grep -r "from.$MODULE import|import.$MODULE" src/ --include="*.py" | grep -v test

If empty → ORPHANED

如果输出为空 → 孤立模块

If has lines → Check if they're from production code

如果有输出 → 检查是否来自生产代码

undefined
undefined

Step 3: Categorize Results

步骤3:分类结果

Category A: Clearly Integrated
  • Multiple imports from production code
  • Functions called in multiple places
  • Part of critical paths
Category B: Suspicious (Needs Review)
  • Only one import (fragile)
  • Imported but functions never called
  • Only imported in edge cases
Category C: Orphaned
  • No imports at all
  • Only imported in tests
  • Imported but conditional never triggers
类别A:已明确集成
  • 存在多处来自生产代码的导入
  • 函数在多个位置被调用
  • 属于关键路径的一部分
类别B:可疑(需要评审)
  • 仅存在一处导入(脆弱)
  • 已被导入但函数从未被调用
  • 仅在边缘场景中被导入
类别C:孤立
  • 无任何导入
  • 仅在测试文件中被导入
  • 已被导入但条件分支从未触发

Step 4: Generate Report

步骤4:生成报告

bash
undefined
bash
undefined

Example report

报告示例

echo "=== Orphan Detection Report ===" echo "" echo "ORPHANED (Category C):" echo " - src/features/architecture_nodes.py (CRITICAL)" echo " - src/utils/old_helper.py" echo "" echo "SUSPICIOUS (Category B):" echo " - src/features/experimental.py (only 1 import, in disabled code)" echo "" echo "INTEGRATED (Category A):" echo " - src/core/main.py" echo " - src/services/coordinator.py"
undefined
echo "=== 孤立代码检测报告 ===" echo "" echo "孤立模块(类别C):" echo " - src/features/architecture_nodes.py(严重)" echo " - src/utils/old_helper.py" echo "" echo "可疑模块(类别B):" echo " - src/features/experimental.py(仅1处导入,位于禁用代码中)" echo "" echo "已集成模块(类别A):" echo " - src/core/main.py" echo " - src/services/coordinator.py"
undefined

Step 5: Take Action

步骤5:采取行动

For Category C (Orphaned):
  1. If needed: Wire into system (import + call)
  2. If not needed: Remove file
  3. Update tests if removed
For Category B (Suspicious):
  1. Review import locations
  2. Check if code is actually used
  3. Consider making integration more robust
For Category A (Integrated):
  1. No action needed
  2. Consider adding to integration test
针对类别C(孤立模块):
  1. 若需要:接入系统(导入+调用)
  2. 若不需要:删除该文件
  3. 若删除文件,需同步更新测试用例
针对类别B(可疑模块):
  1. 评审导入位置
  2. 检查代码是否实际被使用
  3. 考虑提升集成的健壮性
针对类别A(已集成模块):
  1. 无需操作
  2. 可考虑将其加入集成测试

Automated Detection Scripts

自动化检测脚本

Script 1: verify_integration.sh (Complete)

脚本1:verify_integration.sh(全面检测)

Location:
scripts/verify_integration.sh
Usage:
bash
undefined
位置:
scripts/verify_integration.sh
使用方法:
bash
undefined

Check entire project

检查整个项目

./scripts/verify_integration.sh
./scripts/verify_integration.sh

Expected output:

预期输出:

=== Orphan Detection ===

=== 孤立代码检测 ===

⚠️ ORPHANED: src/features/architecture_nodes.py

⚠️ 孤立模块: src/features/architecture_nodes.py

No production imports found

未找到生产环境中的导入

=== Results ===

=== 检测结果 ===

Modules checked: 45

已检查模块数量: 45

❌ ERROR: 1 orphaned module(s) found

❌ 错误: 发现1个孤立模块


**Exit codes:**
- `0` - All modules integrated
- `1` - Orphaned modules found

**See:** Full script in Method 2 above

**退出码:**
- `0` - 所有模块均已集成
- `1` - 发现孤立模块

**参考:** 完整脚本见上方方法2

Script 2: check_imports.sh (Focused)

脚本2:check_imports.sh(模块专属)

Location:
scripts/check_imports.sh
Usage:
bash
undefined
位置:
scripts/check_imports.sh
使用方法:
bash
undefined

Check specific module

检查特定模块

./scripts/check_imports.sh architecture_nodes
./scripts/check_imports.sh architecture_nodes

Expected output:

预期输出:

Checking module: architecture_nodes

正在检查模块: architecture_nodes

Production imports: 0

生产环境导入次数: 0

Test imports: 2

测试环境导入次数: 2

Status: ❌ ORPHANED (only test imports)

状态: ❌ 孤立模块(仅在测试中被导入)


**Script:**
```bash
#!/bin/bash

**脚本内容:**
```bash
#!/bin/bash

Check if a specific module is imported in production code

检查特定模块是否在生产代码中被导入

MODULE=$1
if [ -z "$MODULE" ]; then echo "Usage: $0 <module_name>" exit 1 fi
echo "Checking module: $MODULE"
MODULE=$1
if [ -z "$MODULE" ]; then echo "使用方法: $0 <模块名称>" exit 1 fi
echo "正在检查模块: $MODULE"

Count production imports

统计生产环境导入次数

PROD=$(grep -r "from.$MODULE import|import.$MODULE" src/ --include="*.py" |
grep -v test | wc -l | tr -d ' ')
PROD=$(grep -r "from.$MODULE import|import.$MODULE" src/ --include="*.py" |
grep -v test | wc -l | tr -d ' ')

Count test imports

统计测试环境导入次数

TEST=$(grep -r "from.$MODULE import|import.$MODULE" tests/ --include="*.py" |
wc -l | tr -d ' ')
echo "Production imports: $PROD" echo "Test imports: $TEST"
if [ "$PROD" -eq 0 ]; then if [ "$TEST" -gt 0 ]; then echo "Status: ❌ ORPHANED (only test imports)" else echo "Status: ❌ ORPHANED (no imports at all)" fi exit 1 else echo "Status: ✅ INTEGRATED" exit 0 fi
undefined
TEST=$(grep -r "from.$MODULE import|import.$MODULE" tests/ --include="*.py" |
wc -l | tr -d ' ')
echo "生产环境导入次数: $PROD" echo "测试环境导入次数: $TEST"
if [ "$PROD" -eq 0 ]; then if [ "$TEST" -gt 0 ]; then echo "状态: ❌ 孤立模块(仅在测试中被导入)" else echo "状态: ❌ 孤立模块(无任何导入)" fi exit 1 else echo "状态: ✅ 已集成" exit 0 fi
undefined

Script 3: check_callsites.sh (Function-Level)

脚本3:check_callsites.sh(函数级别)

Location:
scripts/check_callsites.sh
Usage:
bash
undefined
位置:
scripts/check_callsites.sh
使用方法:
bash
undefined

Check if function is called

检查函数是否被调用

./scripts/check_callsites.sh create_architecture_review_node
./scripts/check_callsites.sh create_architecture_review_node

Expected output:

预期输出:

Checking function: create_architecture_review_node

正在检查函数: create_architecture_review_node

Definitions: 1

定义次数: 1

Call-sites: 0

调用次数: 0

Status: ❌ ORPHANED (defined but never called)

状态: ❌ 孤立函数(已定义但从未被调用)


**Script:**
```bash
#!/bin/bash

**脚本内容:**
```bash
#!/bin/bash

Check if a function is called in production code

检查函数是否在生产代码中被调用

FUNCTION=$1
if [ -z "$FUNCTION" ]; then echo "Usage: $0 <function_name>" exit 1 fi
echo "Checking function: $FUNCTION"
FUNCTION=$1
if [ -z "$FUNCTION" ]; then echo "使用方法: $0 <函数名称>" exit 1 fi
echo "正在检查函数: $FUNCTION"

Count definitions

统计定义次数

DEFS=$(grep -r "def $FUNCTION" src/ --include="*.py" | wc -l | tr -d ' ')
DEFS=$(grep -r "def $FUNCTION" src/ --include="*.py" | wc -l | tr -d ' ')

Count call-sites (excluding definitions and tests)

统计调用次数(排除定义和测试文件)

CALLS=$(grep -r "$FUNCTION" src/ --include="*.py" |
grep -v "def $FUNCTION" |
grep -v test |
wc -l | tr -d ' ')
echo "Definitions: $DEFS" echo "Call-sites: $CALLS"
if [ "$CALLS" -eq 0 ]; then echo "Status: ❌ ORPHANED (defined but never called)" exit 1 else echo "Status: ✅ CALLED ($CALLS call-sites)" exit 0 fi
undefined
CALLS=$(grep -r "$FUNCTION" src/ --include="*.py" |
grep -v "def $FUNCTION" |
grep -v test |
wc -l | tr -d ' ')
echo "定义次数: $DEFS" echo "调用次数: $CALLS"
if [ "$CALLS" -eq 0 ]; then echo "状态: ❌ 孤立函数(已定义但从未被调用)" exit 1 else echo "状态: ✅ 已调用(共$CALLS个调用位置)" exit 0 fi
undefined

Integration with Quality Gates

与质量门禁集成

Add to Pre-Commit Quality Gates

加入提交前质量门禁

In
quality-run-quality-gates
skill:
markdown
undefined
quality-run-quality-gates
技能中:
markdown
undefined

Gate 6: Integration Verification (MANDATORY for new modules)

门禁6:集成验证(新模块必填)

When the change involves new files or modules:
bash
undefined
当变更涉及新文件或模块时:
bash
undefined

Detect orphaned modules

检测孤立模块

./scripts/verify_integration.sh
./scripts/verify_integration.sh

For LangGraph changes

针对LangGraph变更

uv run pytest tests/integration/test_graph_completeness.py -v

**Mandatory when:**
- Creating new `.py` files
- Adding new features
- Modifying integration points (builder.py, main.py, etc.)

**Failure means:** Code exists but won't execute at runtime.
uv run pytest tests/integration/test_graph_completeness.py -v

**必填场景:**
- 创建新的`.py`文件
- 添加新功能
- 修改集成点(builder.py、main.py等)

**失败说明:** 代码存在但运行时无法执行。

Add to ADR Completion Checklist

加入ADR完成 checklist

In
create-adr-spike
skill:
markdown
undefined
create-adr-spike
技能中:
markdown
undefined

Phase 6: Integration Verification

阶段6:集成验证

Before moving ADR to completed:
  • Run:
    ./scripts/verify_integration.sh
    (passes)
  • No orphaned modules detected
  • All new modules imported in production code
  • All new functions have call-sites
undefined
将ADR移至已完成状态前:
  • 执行:
    ./scripts/verify_integration.sh
    (通过)
  • 未检测到孤立模块
  • 所有新模块均已在生产代码中被导入
  • 所有新函数均有调用位置
undefined

Add to CI/CD Pipeline

加入CI/CD流水线

In
.github/workflows/quality.yml
(or equivalent):
yaml
- name: Detect Orphaned Code
  run: |
    ./scripts/verify_integration.sh
Effect: Prevents merging PRs with orphaned code
.github/workflows/quality.yml
(或等效文件)中:
yaml
- name: 检测孤立代码
  run: |
    ./scripts/verify_integration.sh
效果: 阻止包含孤立代码的PR被合并

Supporting Files

支持文件

References

参考文档

  • references/orphan-detection-theory.md
    - Why orphaned code occurs
  • references/adr-013-orphan-analysis.md
    - Case study of ADR-013 orphaned code
  • references/vulture-vs-integration-check.md
    - Why vulture isn't enough
  • references/orphan-detection-theory.md
    - 孤立代码产生的原因
  • references/adr-013-orphan-analysis.md
    - ADR-013孤立代码案例分析
  • references/vulture-vs-integration-check.md
    - 为什么vulture不足以检测孤立代码

Examples

示例

  • examples/orphan-module-detection.md
    - Step-by-step module detection
  • examples/orphan-function-detection.md
    - Step-by-step function detection
  • examples/fixing-orphaned-code.md
    - How to fix orphaned code
  • examples/orphan-module-detection.md
    - 模块检测分步示例
  • examples/orphan-function-detection.md
    - 函数检测分步示例
  • examples/fixing-orphaned-code.md
    - 孤立代码修复方法

Scripts

脚本

  • scripts/verify_integration.sh
    - Comprehensive orphan detection
  • scripts/check_imports.sh
    - Module-specific import check
  • scripts/check_callsites.sh
    - Function-specific call-site check
  • scripts/verify_integration.sh
    - 全面孤立代码检测
  • scripts/check_imports.sh
    - 模块专属导入检查
  • scripts/check_callsites.sh
    - 函数专属调用检查

Templates

模板

  • templates/orphan-detection-report.md
    - Report format for findings
  • templates/orphan-detection-report.md
    - 检测结果报告模板

Expected Outcomes

预期结果

Successful Detection (No Orphans)

检测成功(无孤立代码)

bash
$ ./scripts/verify_integration.sh

=== Orphan Detection ===

Checking for orphaned modules in src/...

=== Results ===
Modules checked: 45
✅ All modules are integrated
bash
$ ./scripts/verify_integration.sh

=== 孤立代码检测 ===

正在检查src/中的孤立模块...

=== 检测结果 ===
已检查模块数量: 45
✅ 所有模块均已集成

Failed Detection (Orphans Found)

检测失败(发现孤立代码)

bash
$ ./scripts/verify_integration.sh

=== Orphan Detection ===

Checking for orphaned modules in src/...

⚠️  ORPHANED: src/temet_run/coordination/graph/architecture_nodes.py
   No production imports found

⚠️  ORPHANED: src/temet_run/coordination/graph/task_provider_nodes.py
   No production imports found

=== Results ===
Modules checked: 45
❌ ERROR: 2 orphaned module(s) found

These files exist but are never imported in production code.

To fix, either:
  1. Wire them up (add imports and call-sites)
  2. Remove them if no longer needed
  3. Export via __init__.py if they're part of the public API
bash
$ ./scripts/verify_integration.sh

=== 孤立代码检测 ===

正在检查src/中的孤立模块...

⚠️  孤立模块: src/temet_run/coordination/graph/architecture_nodes.py
   未找到生产环境中的导入

⚠️  孤立模块: src/temet_run/coordination/graph/task_provider_nodes.py
   未找到生产环境中的导入

=== 检测结果 ===
已检查模块数量: 45
❌ 错误: 发现2个孤立模块

这些文件存在但从未在生产代码中被导入。

修复方案:
  1. 将它们接入系统(添加导入和调用位置)
  2. 若不再需要则删除
  3. 若属于公共API,可通过__init__.py导出

Integration Test Failure

集成测试失败

bash
$ uv run pytest tests/integration/test_graph_completeness.py -v

FAILED tests/integration/test_graph_completeness.py::test_all_expected_nodes_in_graph

AssertionError: Nodes in EXPECTED_NODES but not in graph: ['architecture_review', 'retrieve_tasks'].
Either wire these nodes into builder.py or remove from EXPECTED_NODES.
bash
$ uv run pytest tests/integration/test_graph_completeness.py -v

FAILED tests/integration/test_graph_completeness.py::test_all_expected_nodes_in_graph

AssertionError: 预期节点中存在但未在图中的节点: ['architecture_review', 'retrieve_tasks'].
请将这些节点接入builder.py或从EXPECTED_NODES中移除。

Requirements

要求

Tools Required

所需工具

  • Read (to examine source files)
  • Grep (to search for imports/calls)
  • Bash (to run detection scripts)
  • Glob (to find files)
  • 读取权限(用于查看源文件)
  • Grep(用于搜索导入/调用)
  • Bash(用于运行检测脚本)
  • Glob(用于查找文件)

Environment Required

环境要求

  • Project structure with
    src/
    directory
  • Standard Python project layout
  • Ability to execute bash scripts
  • 项目结构包含
    src/
    目录
  • 标准Python项目布局
  • 能够执行bash脚本

Knowledge Required

知识要求

  • Understanding of Python import system
  • Familiarity with project structure
  • Knowledge of integration points (main.py, builder.py, etc.)
  • 了解Python导入机制
  • 熟悉项目结构
  • 了解集成点(main.py、builder.py等)

Red Flags to Avoid

注意事项

Do Not

禁止操作

  • ❌ Trust unit tests alone (they can import orphaned code)
  • ❌ Assume code is integrated because it compiles
  • ❌ Skip orphan detection for "small" changes
  • ❌ Ignore orphan warnings as "false positives"
  • ❌ Rely on vulture alone (can miss test-imported code)
  • ❌ Mark features complete without running detection
  • ❌ Move ADRs to completed without checking orphans
  • ❌ 仅依赖单元测试(它们会导入孤立代码)
  • ❌ 假设代码可编译即已集成
  • ❌ 因“变更小”而跳过孤立代码检测
  • ❌ 将孤立代码警告视为“误报”忽略
  • ❌ 仅依赖vulture(它会遗漏被测试导入的代码)
  • ❌ 未执行检测就标记功能完成
  • ❌ 未检查孤立代码就将ADR移至已完成状态

Do

建议操作

  • ✅ Run orphan detection before marking work complete
  • ✅ Add new modules to integration tests immediately
  • ✅ Verify imports exist in production code (not just tests)
  • ✅ Check both module-level and function-level orphans
  • ✅ Fix orphans immediately (wire or remove)
  • ✅ Add orphan detection to quality gates
  • ✅ Update
    EXPECTED_NODES
    when adding nodes
  • ✅ Treat orphan warnings as failures, not suggestions
  • ✅ 标记工作完成前执行孤立代码检测
  • ✅ 添加新模块后立即将其加入集成测试
  • ✅ 验证导入是否存在于生产代码中(而非仅测试代码)
  • ✅ 同时检查模块级别和函数级别的孤立代码
  • ✅ 立即修复孤立代码(接入或删除)
  • ✅ 将孤立代码检测加入质量门禁
  • ✅ 添加节点时同步更新
    EXPECTED_NODES
  • ✅ 将孤立代码警告视为故障,而非建议

Notes

备注

  • This skill was created in response to ADR-013 (2025-12-07)
  • ADR-013: 313 lines of orphaned code passed all quality gates
  • Orphaned code can exist with 100% test coverage
  • Unit tests can make orphaned code appear "alive" to dead code tools
  • This skill complements vulture but checks integration explicitly
  • Pair with
    quality-verify-implementation-complete
    for full coverage
  • Integrate with
    util-manage-todo
    (Phase 2: Connection verification)
Remember: Code that exists but is never imported is technical debt. Detect and fix orphans before marking work complete.
  • 本技能是为响应ADR-013(2025-12-07)而创建
  • ADR-013案例中,313行孤立代码通过了所有质量门禁
  • 孤立代码可达到100%测试覆盖率
  • 单元测试会让死代码工具误以为孤立代码是“活跃”的
  • 本技能可补充vulture的不足,明确检查集成状态
  • 可与
    quality-verify-implementation-complete
    配合使用以实现全面覆盖
  • 可与
    util-manage-todo
    集成(阶段2:连接验证)
谨记: 存在但从未被导入的代码属于技术债务。请在标记工作完成前检测并修复孤立代码。