dead-code-check

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dead Code Detection

死代码检测

Overview

概述

Dead code detection identifies code that exists in your codebase but is never called, imported, or used. This is a critical signal for incomplete feature integration: if you've written a function but nothing calls it, the feature isn't wired up.
In loom plan verification, dead code checks serve two purposes:
  1. Wiring verification: Catch features that were implemented but never integrated
  2. Code quality: Identify cleanup opportunities and reduce maintenance burden
Dead code detection is especially valuable in integration-verify stages, where it acts as a final check that all implemented code is actually connected to the application.
死代码检测用于识别代码库中存在但从未被调用、导入或使用的代码。这是功能集成不完整的关键信号:如果你编写了一个函数但没有任何代码调用它,说明该功能未完成集成。
在Loom计划验证中,死代码检查有两个作用:
  1. 集成验证:捕获已实现但未集成的功能
  2. 代码质量:识别需要清理的代码,降低维护负担
死代码检测在集成验证阶段尤为重要,它可作为最终检查环节,确保所有已实现的代码都已接入应用。

When to Use

使用场景

  • integration-verify stages: Final quality gate to catch orphaned code from all implementation stages
  • Per-stage acceptance criteria: Immediate feedback during implementation
  • Code cleanup: After refactoring or feature removal
  • Wiring validation: Combine with wiring checks to verify feature integration
If dead code exists after implementation, it typically means:
  • Feature wasn't wired into the application (CLI command not registered, route not mounted, etc.)
  • Test code that isn't being run
  • Leftover code from refactoring
  • Incomplete implementation
  • 集成验证阶段:作为最终质量关卡,捕获所有实现阶段产生的孤立代码
  • 阶段验收标准:在实现过程中提供即时反馈
  • 代码清理:重构或移除功能后使用
  • 集成验证:结合集成检查,验证功能是否正确接入
如果实现后仍存在死代码,通常意味着:
  • 功能未接入应用(CLI命令未注册、路由未挂载等)
  • 测试代码未被执行
  • 重构遗留的代码
  • 未完成的实现

Language-Specific Configurations

各语言专属配置

Rust

Rust

Rust has built-in dead code detection via the compiler and clippy.
Recommended Approach: Use clippy with all warnings as errors
bash
cargo clippy -- -D warnings
This catches dead code plus many other issues (unused imports, variables, etc.).
Dead-Code-Specific Check:
bash
RUSTFLAGS="-D dead_code" cargo build 2>&1
Or target just dead code warnings:
bash
cargo clippy -- -D dead_code
Fail Patterns:
  • warning: unused
  • dead_code
  • unused import
  • unused variable
  • never used
  • never constructed
Ignore Patterns:
  • Code with
    #[allow(dead_code)]
    attribute (intentional)
  • Test modules (
    #[cfg(test)]
    )
  • Main entry points (
    fn main()
    )
  • Public API items intended for external consumers
  • Items behind feature gates that aren't enabled
YAML Template for Loom Plans:
yaml
undefined
Rust通过编译器和clippy内置了死代码检测功能。
推荐方案:使用clippy并将所有警告设为错误
bash
cargo clippy -- -D warnings
该命令可捕获死代码及其他诸多问题(未使用的导入、变量等)。
仅检查死代码的命令:
bash
RUSTFLAGS="-D dead_code" cargo build 2>&1
或者仅针对死代码警告:
bash
cargo clippy -- -D dead_code
失败匹配规则:
  • warning: unused
  • dead_code
  • unused import
  • unused variable
  • never used
  • never constructed
忽略规则:
  • 带有
    #[allow(dead_code)]
    属性的代码(有意保留)
  • 测试模块(
    #[cfg(test)]
  • 主入口函数(
    fn main()
  • 供外部消费者使用的公共API项
  • 未启用的功能门控后的代码
Loom计划的YAML模板:
yaml
undefined

In acceptance criteria (recommended - catches more than just dead code)

在验收标准中(推荐,可捕获除死代码外的更多问题)

acceptance:
  • "cargo clippy -- -D warnings"
acceptance:
  • "cargo clippy -- -D warnings"

In truths (more specific dead code check)

在truths中(更针对性的死代码检查)

truths:
  • "RUSTFLAGS="-D dead_code" cargo build 2>&1 | grep -v 'Compiling' | grep -v 'Finished' | grep -q '^$'"
truths:
  • "RUSTFLAGS="-D dead_code" cargo build 2>&1 | grep -v 'Compiling' | grep -v 'Finished' | grep -q '^$'"

Alternative: Check that clippy reports zero dead code warnings

替代方案:检查clippy是否未报告任何死代码警告

truths:
  • "! cargo clippy -- -D dead_code 2>&1 | grep -q 'warning:'"

**Working Directory Consideration:**

Rust checks must run where `Cargo.toml` exists. If your project structure is:

```text
.worktrees/my-stage/
└── loom/
    └── Cargo.toml
Set
working_dir: "loom"
in your stage configuration.

truths:
  • "! cargo clippy -- -D dead_code 2>&1 | grep -q 'warning:'"

**工作目录注意事项:**

Rust检查必须在存在`Cargo.toml`的目录下运行。如果你的项目结构如下:

```text
.worktrees/my-stage/
└── loom/
    └── Cargo.toml
请在阶段配置中设置
working_dir: "loom"

TypeScript

TypeScript

TypeScript dead code detection uses ts-prune, which finds unused exports.
Installation:
bash
npm install --save-dev ts-prune
TypeScript的死代码检测使用ts-prune,它可发现未使用的导出项。
安装:
bash
npm install --save-dev ts-prune

or

bun add --dev ts-prune

**Command:**

```bash
npx ts-prune --error
bun add --dev ts-prune

**命令:**

```bash
npx ts-prune --error

or

bunx ts-prune --error

The `--error` flag makes ts-prune exit with non-zero status if unused exports are found.

**Fail Patterns:**

- `used in module but not exported`
- `unused export`
- Files with unused exports reported

**Ignore Patterns:**

- `index.ts` files that re-export (barrel files)
- Type-only exports used for type checking
- Declaration files (`.d.ts`)
- Public API exports intended for library consumers
- Default exports in entry points

**Configuration File (`.tsprunerc`):**

```json
{
  "ignore": "index.ts|types.d.ts"
}
YAML Template for Loom Plans:
yaml
undefined
bunx ts-prune --error

`--error`参数会让ts-prune在发现未使用导出项时返回非零状态码。

**失败匹配规则:**

- `used in module but not exported`
- `unused export`
- 报告存在未使用导出项的文件

**忽略规则:**

- 用于重新导出的`index.ts`文件(桶文件)
- 仅用于类型检查的类型导出项
- 声明文件(`.d.ts`)
- 供库消费者使用的公共API导出项
- 入口文件中的默认导出

**配置文件(`.tsprunerc`):**

```json
{
  "ignore": "index.ts|types.d.ts"
}
Loom计划的YAML模板:
yaml
undefined

In acceptance criteria

在验收标准中

acceptance:
  • "bunx ts-prune --error"
acceptance:
  • "bunx ts-prune --error"

In truths (verify zero unused exports)

在truths中(验证无未使用导出项)

truths:
  • "bunx ts-prune | wc -l | grep -q '^0$'"
truths:
  • "bunx ts-prune | wc -l | grep -q '^0$'"

Alternative: Explicitly check for no unused exports

替代方案:检查是否存在特定问题

truths:
  • "! bunx ts-prune | grep -q 'used in module'"

**Working Directory:**

Run where `package.json` and `tsconfig.json` exist.

---
truths:
  • "! bunx ts-prune | grep -q 'used in module'"

**工作目录:**

在存在`package.json`和`tsconfig.json`的目录下运行。

---

Python

Python

Python dead code detection uses vulture, which finds unused code including functions, classes, variables, and imports.
Installation:
bash
pip install vulture
Python的死代码检测使用vulture,它可发现未使用的函数、类、变量和导入项。
安装:
bash
pip install vulture

or

uv add --dev vulture

**Command:**

```bash
vulture src/ --min-confidence 80
The
--min-confidence
flag (0-100) controls false positive rate. Higher values mean fewer false positives but might miss some dead code.
Fail Patterns:
  • unused function
  • unused class
  • unused variable
  • unused import
  • unreachable code
Ignore Patterns:
  • __init__.py
    files
  • __all__
    definitions (explicit public API)
  • Magic methods (
    __str__
    ,
    __repr__
    ,
    __eq__
    , etc.)
  • Test files and fixtures (often use dynamic discovery)
  • Setup.py and configuration files
Configuration File (
pyproject.toml
):
toml
[tool.vulture]
min_confidence = 80
paths = ["src", "tests"]
ignore_names = ["setUp", "tearDown", "test_*"]
YAML Template for Loom Plans:
yaml
undefined
uv add --dev vulture

**命令:**

```bash
vulture src/ --min-confidence 80
--min-confidence
参数(取值0-100)用于控制误报率。值越高,误报越少,但可能会遗漏部分死代码。
失败匹配规则:
  • unused function
  • unused class
  • unused variable
  • unused import
  • unreachable code
忽略规则:
  • __init__.py
    文件
  • __all__
    定义(显式声明的公共API)
  • 魔术方法(
    __str__
    __repr__
    __eq__
    等)
  • 测试文件和测试夹具(通常使用动态发现机制)
  • Setup.py及配置文件
配置文件(
pyproject.toml
):
toml
[tool.vulture]
min_confidence = 80
paths = ["src", "tests"]
ignore_names = ["setUp", "tearDown", "test_*"]
Loom计划的YAML模板:
yaml
undefined

In acceptance criteria

在验收标准中

acceptance:
  • "vulture src/ --min-confidence 80"
acceptance:
  • "vulture src/ --min-confidence 80"

In truths (verify zero issues)

在truths中(验证无问题)

truths:
  • "vulture src/ --min-confidence 80 | wc -l | grep -q '^0$'"
truths:
  • "vulture src/ --min-confidence 80 | wc -l | grep -q '^0$'"

Alternative: Check for specific patterns

替代方案:检查特定问题

truths:
  • "! vulture src/ --min-confidence 80 | grep -q 'unused function'"
  • "! vulture src/ --min-confidence 80 | grep -q 'unused import'"

**Working Directory:**

Run where your Python source code is (usually project root or where `pyproject.toml` exists).

---
truths:
  • "! vulture src/ --min-confidence 80 | grep -q 'unused function'"
  • "! vulture src/ --min-confidence 80 | grep -q 'unused import'"

**工作目录:**

在Python源代码所在目录运行(通常是项目根目录或`pyproject.toml`所在目录)。

---

Go

Go

Go dead code detection uses staticcheck, a comprehensive static analysis tool.
Installation:
bash
go install honnef.co/go/tools/cmd/staticcheck@latest
Command:
bash
staticcheck ./...
Relevant Checks:
  • U1000
    - unused code (function, type, const, var)
  • U1001
    - unused field
Fail Patterns:
  • is unused
  • field .* is unused
  • func .* is unused
  • U1000
    check code
  • U1001
    check code
Ignore Patterns:
  • Exported symbols in library packages (public API)
  • Interface method implementations (required by interface even if not directly called)
  • Functions assigned to variables for use via reflection
  • Code behind build tags not currently enabled
Configuration File (
.staticcheck.conf
):
text
checks = ["all", "-ST1000"]
YAML Template for Loom Plans:
yaml
undefined
Go的死代码检测使用staticcheck,一款全面的静态分析工具。
安装:
bash
go install honnef.co/go/tools/cmd/staticcheck@latest
命令:
bash
staticcheck ./...
相关检查项:
  • U1000
    - 未使用的代码(函数、类型、常量、变量)
  • U1001
    - 未使用的字段
失败匹配规则:
  • is unused
  • field .* is unused
  • func .* is unused
  • U1000
    检查码
  • U1001
    检查码
忽略规则:
  • 库包中的导出符号(公共API)
  • 接口方法实现(即使未直接调用,接口也要求必须实现)
  • 赋值给变量用于反射调用的函数
  • 当前未启用的构建标签后的代码
配置文件(
.staticcheck.conf
):
text
checks = ["all", "-ST1000"]
Loom计划的YAML模板:
yaml
undefined

In acceptance criteria

在验收标准中

acceptance:
  • "staticcheck ./..."
acceptance:
  • "staticcheck ./..."

In truths (verify no unused code)

在truths中(验证无未使用代码)

truths:
  • "! staticcheck ./... | grep -q 'U1000'"
  • "! staticcheck ./... | grep -q 'is unused'"
truths:
  • "! staticcheck ./... | grep -q 'U1000'"
  • "! staticcheck ./... | grep -q 'is unused'"

Alternative: Check exit code

替代方案:检查退出码

truths:
  • "staticcheck ./... 2>&1 | wc -l | grep -q '^0$'"

**Working Directory:**

Run where `go.mod` exists (usually project root).

---
truths:
  • "staticcheck ./... 2>&1 | wc -l | grep -q '^0$'"

**工作目录:**

在存在`go.mod`的目录下运行(通常是项目根目录)。

---

JavaScript

JavaScript

JavaScript dead code detection uses unimported, which finds unused files and unresolved imports.
Installation:
bash
npm install --save-dev unimported
JavaScript的死代码检测使用unimported,它可发现未使用的文件及未解析的导入项。
安装:
bash
npm install --save-dev unimported

or

bun add --dev unimported

**Command:**

```bash
npx unimported
bun add --dev unimported

**命令:**

```bash
npx unimported

or

bunx unimported

**Fail Patterns:**

- `unresolved import`
- `unused file`
- Files listed in output

**Ignore Patterns:**

- Config files (`.eslintrc.js`, `jest.config.js`, etc.)
- Entry points (`index.js`, `main.js`)
- Dynamic imports using variables
- Files imported via build tools (Webpack, Vite, etc.)

**Configuration File (`.unimportedrc.json`):**

```json
{
  "entry": ["src/index.js", "src/server.js"],
  "extensions": [".js", ".jsx"],
  "ignorePatterns": ["**/node_modules/**", "**/*.config.js"]
}
YAML Template for Loom Plans:
yaml
undefined
bunx unimported

**失败匹配规则:**

- `unresolved import`
- `unused file`
- 输出中列出的文件

**忽略规则:**

- 配置文件(`.eslintrc.js`、`jest.config.js`等)
- 入口文件(`index.js`、`main.js`)
- 使用变量的动态导入
- 通过构建工具(Webpack、Vite等)导入的文件

**配置文件(`.unimportedrc.json`):**

```json
{
  "entry": ["src/index.js", "src/server.js"],
  "extensions": [".js", ".jsx"],
  "ignorePatterns": ["**/node_modules/**", "**/*.config.js"]
}
Loom计划的YAML模板:
yaml
undefined

In acceptance criteria

在验收标准中

acceptance:
  • "bunx unimported"
acceptance:
  • "bunx unimported"

In truths (verify no unused files)

在truths中(验证无未使用文件)

truths:
  • "bunx unimported | wc -l | grep -q '^0$'"
truths:
  • "bunx unimported | wc -l | grep -q '^0$'"

Alternative: Check for specific issues

替代方案:检查特定问题

truths:
  • "! bunx unimported | grep -q 'unused file'"
  • "! bunx unimported | grep -q 'unresolved import'"

**Working Directory:**

Run where `package.json` exists.

---
truths:
  • "! bunx unimported | grep -q 'unused file'"
  • "! bunx unimported | grep -q 'unresolved import'"

**工作目录:**

在存在`package.json`的目录下运行。

---

Handling False Positives

处理误报

Dead code detection tools report false positives in these common scenarios:
死代码检测工具在以下常见场景中会产生误报:

1. Entry Points

1. 入口点

Problem: Main functions, CLI handlers, API route handlers — nothing in your code calls them directly, but they're invoked by the runtime/framework.
Solutions:
  • Rust: Entry points like
    fn main()
    are automatically excluded. For CLI subcommands, ensure they're registered in the command enum.
  • TypeScript/JavaScript: Configure entry points in tool config (ts-prune, unimported)
  • Python: Use
    __all__
    to mark public API, vulture respects it
  • Go: Exported functions in
    main
    package are excluded
问题: 主函数、CLI处理器、API路由处理器等,代码中没有直接调用它们,但会被运行时/框架调用。
解决方案:
  • Rust
    fn main()
    等入口点会被自动排除。对于CLI子命令,确保它们已在命令枚举中注册。
  • TypeScript/JavaScript:在工具配置中指定入口点(ts-prune、unimported)
  • Python:使用
    __all__
    标记公共API,vulture会尊重该配置
  • Go
    main
    包中的导出函数会被排除

2. Test Code

2. 测试代码

Problem: Test functions are called by the test runner, not by application code.
Solutions:
  • Rust: Code in
    #[cfg(test)]
    modules is automatically excluded
  • TypeScript/JavaScript: Exclude test directories in config
  • Python: Ignore patterns like
    test_*
    ,
    setUp
    ,
    tearDown
  • Go: Test files (
    *_test.go
    ) are automatically handled
问题: 测试函数由测试运行器调用,而非应用代码。
解决方案:
  • Rust
    #[cfg(test)]
    模块中的代码会被自动排除
  • TypeScript/JavaScript:在配置中排除测试目录
  • Python:忽略
    test_*
    setUp
    tearDown
    等命名模式
  • Go:测试文件(
    *_test.go
    )会被自动处理

3. Framework Magic

3. 框架魔术特性

Problem: Decorators, derive macros, annotations that use code implicitly.
Examples:
  • Rust:
    #[derive(Serialize)]
    uses private fields
  • Python:
    @dataclass
    ,
    @property
    decorators
  • TypeScript: Decorators in frameworks like Angular, NestJS
Solutions:
  • Use language-specific ignore annotations
  • Configure tools to ignore decorated items
  • For Rust, use
    #[allow(dead_code)]
    on specific items
问题: 装饰器、派生宏、注解会隐式使用代码。
示例:
  • Rust:
    #[derive(Serialize)]
    会使用私有字段
  • Python:
    @dataclass
    @property
    装饰器
  • TypeScript:Angular、NestJS等框架中的装饰器
解决方案:
  • 使用语言专属的忽略注解
  • 配置工具忽略带有装饰器的项
  • Rust中,对特定项使用
    #[allow(dead_code)]

4. Public API / Library Code

4. 公共API / 库代码

Problem: Code exported for external consumers appears unused within the project.
Solutions:
  • Rust: Public items (
    pub
    ) in library crates are excluded by default
  • TypeScript: Use
    .tsprunerc
    to ignore library entry points
  • Python: Define
    __all__
    to mark public API
  • Go: Exported symbols (capitalized) in library packages are excluded
问题: 供外部消费者使用的代码在项目内部显示为未使用。
解决方案:
  • Rust:库 crate 中的公共项(
    pub
    )默认会被排除
  • TypeScript:使用
    .tsprunerc
    忽略库入口点
  • Python:定义
    __all__
    标记公共API
  • Go:库包中的导出符号(首字母大写)会被排除

5. Feature Flags and Conditional Compilation

5. 功能标志与条件编译

Problem: Code behind disabled feature flags or build tags.
Solutions:
  • Rust: Enable relevant features when running checks (
    --features=all
    )
  • Go: Use build tags to include all variants
  • Python/TypeScript/JavaScript: Comment or temporarily enable features during checks
问题: 禁用的功能标志或构建标签后的代码。
解决方案:
  • Rust:运行检查时启用相关功能(
    --features=all
  • Go:使用构建标签包含所有变体
  • Python/TypeScript/JavaScript:检查期间注释或临时启用功能

6. Dynamic Loading and Reflection

6. 动态加载与反射

Problem: Code loaded dynamically or invoked via reflection.
Solutions:
  • Document these cases clearly
  • Use tool-specific ignore comments
  • Consider integration tests that exercise dynamic code paths

问题: 动态加载或通过反射调用的代码。
解决方案:
  • 清晰记录这些情况
  • 使用工具专属的忽略注释
  • 考虑编写集成测试覆盖动态代码路径

Integration with Loom Plans

与Loom计划集成

Placement in Plan Stages

在计划阶段中的位置

Best Practice: integration-verify stage
Dead code checks are most valuable as a final quality gate:
yaml
stages:
  - id: integration-verify
    name: "Integration Verification"
    stage_type: integration-verify
    working_dir: "loom"
    acceptance:
      - "cargo test"
      - "cargo clippy -- -D warnings" # Includes dead code check
    truths:
      - "! cargo clippy -- -D dead_code 2>&1 | grep -q 'warning:'"
Per-Stage Checks:
Can also add to individual implementation stages for immediate feedback:
yaml
stages:
  - id: implement-auth
    name: "Implement Authentication"
    stage_type: standard
    working_dir: "loom"
    acceptance:
      - "cargo test auth"
      - "cargo clippy --package auth -- -D warnings"
最佳实践:集成验证阶段
死代码检查作为最终质量关卡时价值最大:
yaml
stages:
  - id: integration-verify
    name: "Integration Verification"
    stage_type: integration-verify
    working_dir: "loom"
    acceptance:
      - "cargo test"
      - "cargo clippy -- -D warnings" # 包含死代码检查
    truths:
      - "! cargo clippy -- -D dead_code 2>&1 | grep -q 'warning:'"
阶段内检查:
也可添加到各个实现阶段,提供即时反馈:
yaml
stages:
  - id: implement-auth
    name: "Implement Authentication"
    stage_type: standard
    working_dir: "loom"
    acceptance:
      - "cargo test auth"
      - "cargo clippy --package auth -- -D warnings"

Combining with Wiring Checks

与集成检查结合使用

Dead code detection is a strong signal but not definitive proof. Combine with
wiring
checks:
yaml
stages:
  - id: integration-verify
    name: "Integration Verification"
    stage_type: integration-verify
    working_dir: "loom"
    acceptance:
      - "cargo clippy -- -D warnings"
    wiring:
      - source: "src/main.rs"
        pattern: "Commands::NewCommand"
        description: "New command registered in CLI enum"
      - source: "src/commands/mod.rs"
        pattern: "pub mod new_command"
        description: "New command module exported"
    truths:
      - "loom new-command --help" # Functional verification
This triple-check approach (dead code + wiring + functional) catches integration issues reliably.
死代码检测是一个强烈的信号,但并非 definitive 的证明。需与
wiring
检查结合:
yaml
stages:
  - id: integration-verify
    name: "Integration Verification"
    stage_type: integration-verify
    working_dir: "loom"
    acceptance:
      - "cargo clippy -- -D warnings"
    wiring:
      - source: "src/main.rs"
        pattern: "Commands::NewCommand"
        description: "New command registered in CLI enum"
      - source: "src/commands/mod.rs"
        pattern: "pub mod new_command"
        description: "New command module exported"
    truths:
      - "loom new-command --help" # 功能验证
这种三重检查方式(死代码检测 + 集成检查 + 功能测试)可可靠地捕获集成问题。

Working Directory and Paths

工作目录与路径

Critical Reminder: The
working_dir
field determines where commands execute.
Example project structure:
text
.worktrees/my-stage/
├── loom/
│   ├── Cargo.toml       <- Build tools expect this directory
│   └── src/
└── CLAUDE.md
Correct Configuration:
yaml
- id: verify
  working_dir: "loom" # Where Cargo.toml exists
  acceptance:
    - "cargo clippy -- -D warnings"
  truths:
    - "test -f src/new_feature.rs" # Relative to working_dir (loom/)
Wrong Configuration:
yaml
- id: verify
  working_dir: "." # Wrong - no Cargo.toml here
  acceptance:
    - "cargo clippy -- -D warnings" # FAILS: could not find Cargo.toml
Path Resolution Rule: ALL paths in acceptance, truths, artifacts, and wiring are relative to
working_dir
.

重要提醒:
working_dir
字段决定命令的执行位置。
示例项目结构:
text
.worktrees/my-stage/
├── loom/
│   ├── Cargo.toml       <- 构建工具期望在此目录
│   └── src/
└── CLAUDE.md
正确配置:
yaml
- id: verify
  working_dir: "loom" # Cargo.toml所在目录
  acceptance:
    - "cargo clippy -- -D warnings"
  truths:
    - "test -f src/new_feature.rs" # 相对于working_dir(loom/)
错误配置:
yaml
- id: verify
  working_dir: "." # 错误 - 此处无Cargo.toml
  acceptance:
    - "cargo clippy -- -D warnings" # 失败:找不到Cargo.toml
路径解析规则: 验收标准、truths、产物及wiring中的所有路径均相对于
working_dir

YAML Best Practices

YAML最佳实践

Never Use Triple Backticks in YAML Descriptions

切勿在YAML描述中使用三重反引号

Wrong:
yaml
truths:
  - description: |
      Check for dead code like this:
      ```
      cargo clippy -- -D warnings
      ```
    command: "cargo clippy -- -D warnings"
This breaks YAML parsing.
Correct:
yaml
truths:
  - "cargo clippy -- -D warnings" # Check for dead code
Or with explicit description:
yaml
truths:
  - description: "Check for dead code using clippy with all warnings as errors"
    command: "cargo clippy -- -D warnings"
错误写法:
yaml
truths:
  - description: |
      Check for dead code like this:
      ```
      cargo clippy -- -D warnings
      ```
    command: "cargo clippy -- -D warnings"
这会破坏YAML解析。
正确写法:
yaml
truths:
  - "cargo clippy -- -D warnings" # 检查死代码
或带显式描述:
yaml
truths:
  - description: "使用clippy将所有警告设为错误,检查死代码"
    command: "cargo clippy -- -D warnings"

Silent Grep with -q

使用-q参数静默执行grep

When using
grep
in truths, use
-q
(quiet) flag to suppress output:
yaml
truths:
  - "! cargo clippy -- -D dead_code 2>&1 | grep -q 'warning:'"
The
!
negates the result (exit 0 if grep finds nothing).
在truths中使用
grep
时,使用
-q
(静默)参数抑制输出:
yaml
truths:
  - "! cargo clippy -- -D dead_code 2>&1 | grep -q 'warning:'"
!
用于取反结果(如果grep未找到任何内容,则返回0)。

Exit Code Checks

退出码检查

Tools that exit non-zero on finding issues can be used directly:
yaml
acceptance:
  - "cargo clippy -- -D warnings" # Exits non-zero on warnings
  - "staticcheck ./..." # Exits non-zero on issues
  - "bunx ts-prune --error" # Exits non-zero on unused exports

可直接使用发现问题时返回非零状态码的工具:
yaml
acceptance:
  - "cargo clippy -- -D warnings" # 出现警告时返回非零
  - "staticcheck ./..." # 出现问题时返回非零
  - "bunx ts-prune --error" # 发现未使用导出项时返回非零

Tool Installation Checklist

工具安装检查清单

Before adding dead code checks to your plan, ensure tools are available:
Rust:
  • Built-in:
    rustc
    ,
    cargo
  • cargo install clippy
    (usually included with rustup)
TypeScript:
  • bun add --dev ts-prune
    or
    npm install --save-dev ts-prune
Python:
  • uv add --dev vulture
    or
    pip install vulture
Go:
  • go install honnef.co/go/tools/cmd/staticcheck@latest
JavaScript:
  • bun add --dev unimported
    or
    npm install --save-dev unimported
Add installation steps to your
knowledge-bootstrap
stage or document in project README.

在将死代码检查添加到计划前,确保工具已可用:
Rust:
  • 内置工具:
    rustc
    cargo
  • cargo install clippy
    (通常随rustup一起安装)
TypeScript:
  • bun add --dev ts-prune
    npm install --save-dev ts-prune
Python:
  • uv add --dev vulture
    pip install vulture
Go:
  • go install honnef.co/go/tools/cmd/staticcheck@latest
JavaScript:
  • bun add --dev unimported
    npm install --save-dev unimported
可将安装步骤添加到
knowledge-bootstrap
阶段,或在项目README中说明。

Examples

示例

Example 1: Rust Project with Comprehensive Checks

示例1:包含全面检查的Rust项目

yaml
stages:
  - id: integration-verify
    name: "Integration Verification"
    stage_type: integration-verify
    working_dir: "loom"
    acceptance:
      - "cargo test"
      - "cargo clippy -- -D warnings"
      - "cargo build --release"
    truths:
      - "test -f src/commands/new_feature.rs"
      - "! cargo clippy -- -D dead_code 2>&1 | grep -q 'warning:'"
    wiring:
      - source: "src/main.rs"
        pattern: "Commands::NewFeature"
        description: "New feature command registered"
yaml
stages:
  - id: integration-verify
    name: "Integration Verification"
    stage_type: integration-verify
    working_dir: "loom"
    acceptance:
      - "cargo test"
      - "cargo clippy -- -D warnings"
      - "cargo build --release"
    truths:
      - "test -f src/commands/new_feature.rs"
      - "! cargo clippy -- -D dead_code 2>&1 | grep -q 'warning:'"
    wiring:
      - source: "src/main.rs"
        pattern: "Commands::NewFeature"
        description: "New feature command registered"

Example 2: TypeScript API with Dead Export Check

示例2:包含死导出检查的TypeScript API

yaml
stages:
  - id: verify-api
    name: "Verify API Implementation"
    stage_type: integration-verify
    working_dir: "api"
    acceptance:
      - "bun test"
      - "bunx ts-prune --error"
      - "bun run typecheck"
    truths:
      - "bunx ts-prune | wc -l | grep -q '^0$'"
      - "curl -f http://localhost:3000/api/health"
yaml
stages:
  - id: verify-api
    name: "Verify API Implementation"
    stage_type: integration-verify
    working_dir: "api"
    acceptance:
      - "bun test"
      - "bunx ts-prune --error"
      - "bun run typecheck"
    truths:
      - "bunx ts-prune | wc -l | grep -q '^0$'"
      - "curl -f http://localhost:3000/api/health"

Example 3: Python Data Pipeline

示例3:Python数据管道

yaml
stages:
  - id: verify-pipeline
    name: "Verify Data Pipeline"
    stage_type: integration-verify
    working_dir: "pipeline"
    acceptance:
      - "pytest"
      - "vulture src/ --min-confidence 80"
      - "mypy src/"
    truths:
      - "! vulture src/ --min-confidence 80 | grep -q 'unused function'"
      - "test -f src/pipeline/transform.py"
    wiring:
      - source: "src/main.py"
        pattern: "from pipeline.transform import TransformStage"
        description: "Transform stage imported in main pipeline"
yaml
stages:
  - id: verify-pipeline
    name: "Verify Data Pipeline"
    stage_type: integration-verify
    working_dir: "pipeline"
    acceptance:
      - "pytest"
      - "vulture src/ --min-confidence 80"
      - "mypy src/"
    truths:
      - "! vulture src/ --min-confidence 80 | grep -q 'unused function'"
      - "test -f src/pipeline/transform.py"
    wiring:
      - source: "src/main.py"
        pattern: "from pipeline.transform import TransformStage"
        description: "Transform stage imported in main pipeline"

Example 4: Go Microservice

示例4:Go微服务

yaml
stages:
  - id: verify-service
    name: "Verify Microservice"
    stage_type: integration-verify
    working_dir: "service"
    acceptance:
      - "go test ./..."
      - "staticcheck ./..."
      - "go build"
    truths:
      - "! staticcheck ./... | grep -q 'U1000'"
      - "! staticcheck ./... | grep -q 'is unused'"
      - "test -f cmd/server/main.go"

yaml
stages:
  - id: verify-service
    name: "Verify Microservice"
    stage_type: integration-verify
    working_dir: "service"
    acceptance:
      - "go test ./..."
      - "staticcheck ./..."
      - "go build"
    truths:
      - "! staticcheck ./... | grep -q 'U1000'"
      - "! staticcheck ./... | grep -q 'is unused'"
      - "test -f cmd/server/main.go"

Summary

总结

Dead code detection is a powerful verification tool for loom plans:
  1. Catches incomplete wiring: Code exists but isn't called = feature not integrated
  2. Language-specific tools: Rust (clippy), TypeScript (ts-prune), Python (vulture), Go (staticcheck), JavaScript (unimported)
  3. Best in integration-verify: Final quality gate after all implementation stages
  4. Combine with wiring checks: Dead code detection + wiring patterns + functional tests = comprehensive verification
  5. Handle false positives: Entry points, tests, framework magic — configure tools appropriately
  6. Working directory matters: Set
    working_dir
    to where build tools expect (where Cargo.toml, package.json, go.mod exist)
Use this skill when designing verification strategies for loom plans. Copy-paste the YAML templates and adapt tool configurations to your project's structure.
死代码检测是Loom计划验证的强大工具:
  1. 捕获未完成集成:代码存在但未被调用 = 功能未集成
  2. 多语言工具支持:Rust(clippy)、TypeScript(ts-prune)、Python(vulture)、Go(staticcheck)、JavaScript(unimported)
  3. 最佳位置:集成验证阶段:所有实现阶段后的最终质量关卡
  4. 与集成检查结合:死代码检测 + 集成匹配规则 + 功能测试 = 全面验证
  5. 处理误报:入口点、测试代码、框架魔术特性等 - 合理配置工具
  6. 工作目录很重要:将
    working_dir
    设置为构建工具期望的目录(Cargo.toml、package.json、go.mod所在位置)
在设计Loom计划的验证策略时使用该技能。可直接复制粘贴YAML模板,并根据项目结构调整工具配置。