ai-code-cleanup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AI Code Cleanup

AI Code Cleanup

This skill identifies and removes AI-generated artifacts that degrade code quality, including defensive bloat, unnecessary comments, type casts, and style inconsistencies.
本技能可识别并移除会降低代码质量的AI生成产物,包括防御性冗余代码、不必要的注释、类型转换和风格不一致问题。

When to Use This Skill

何时使用本技能

  • After AI-assisted coding sessions
  • Before code reviews or merging branches
  • When cleaning up code that feels "over-engineered"
  • When removing unnecessary defensive code
  • When standardizing code style after AI generation
  • When preparing code for production
  • 在AI辅助编码会话之后
  • 代码评审或合并分支之前
  • 清理“过度设计”的代码时
  • 移除不必要的防御性代码时
  • AI生成后统一代码风格时
  • 为生产环境准备代码时

What This Skill Does

本技能的功能

  1. Identifies AI Artifacts: Detects patterns typical of AI-generated code
  2. Removes Bloat: Eliminates unnecessary defensive code and comments
  3. Fixes Type Issues: Removes unnecessary type casts and workarounds
  4. Standardizes Style: Ensures consistency with project conventions
  5. Preserves Functionality: Maintains code behavior while improving quality
  6. Validates Changes: Ensures code still compiles and tests pass
  1. 识别AI生成产物:检测AI生成代码的典型模式
  2. 移除冗余内容:删除不必要的防御性代码和注释
  3. 修复类型问题:移除不必要的类型转换和变通方案
  4. 统一代码风格:确保与项目规范保持一致
  5. 保留功能完整性:在提升代码质量的同时维持代码行为不变
  6. 验证变更有效性:确保代码仍可编译且测试通过

How to Use

使用方法

Clean Up Branch

清理分支

Remove AI slop from this branch
Clean up the code in this pull request
Remove AI slop from this branch
Clean up the code in this pull request

Specific Cleanup

针对性清理

Remove unnecessary comments and defensive code from src/
Remove unnecessary comments and defensive code from src/

Slop Patterns to Remove

需要移除的冗余模式

1. Unnecessary Comments

1. 不必要的注释

Patterns:
  • Comments explaining obvious code
  • Comments inconsistent with file's documentation style
  • Redundant comments that restate the code
  • Over-documentation of simple operations
Example:
javascript
// ❌ AI-generated: Obvious comment
// Set the user's name
user.name = name;

// ✅ Clean: Self-documenting code
user.name = name;
模式:
  • 解释显而易见代码的注释
  • 与文件文档风格不一致的注释
  • 重复代码内容的冗余注释
  • 对简单操作过度注释的内容
示例:
javascript
// ❌ AI-generated: Obvious comment
// Set the user's name
user.name = name;

// ✅ Clean: Self-documenting code
user.name = name;

2. Defensive Bloat

2. 防御性冗余代码

Patterns:
  • Extra try/catch blocks abnormal for that codebase
  • Defensive null/undefined checks on trusted paths
  • Redundant input validation when callers already validate
  • Error handling that can never trigger
Example:
javascript
// ❌ AI-generated: Unnecessary defensive code
function processUser(user) {
  try {
    if (user && user.name && typeof user.name === 'string') {
      return user.name.toUpperCase();
    }
    return null;
  } catch (error) {
    console.error(error);
    return null;
  }
}

// ✅ Clean: Trust the input, handle real errors
function processUser(user) {
  return user.name.toUpperCase();
}
模式:
  • 代码库中不常见的额外try/catch块
  • 在可信路径上进行的防御性null/undefined检查
  • 调用方已验证时的冗余输入验证
  • 永远不会触发的错误处理代码
示例:
javascript
// ❌ AI-generated: Unnecessary defensive code
function processUser(user) {
  try {
    if (user && user.name && typeof user.name === 'string') {
      return user.name.toUpperCase();
    }
    return null;
  } catch (error) {
    console.error(error);
    return null;
  }
}

// ✅ Clean: Trust the input, handle real errors
function processUser(user) {
  return user.name.toUpperCase();
}

3. Type Workarounds

3. 类型变通方案

Patterns:
  • Casts to
    any
    to bypass type issues
  • Unnecessary type assertions (
    as X
    )
  • @ts-ignore
    or
    @ts-expect-error
    without legitimate reason
  • Overly complex generic constraints
Example:
typescript
// ❌ AI-generated: Type workaround
const data = response.data as any;
const result = processData(data as ProcessedData);

// ✅ Clean: Proper typing
const data = response.data;
const result = processData(data);
模式:
  • 强制转换为
    any
    以绕过类型问题
  • 不必要的类型断言(
    as X
  • 无合理理由的
    @ts-ignore
    @ts-expect-error
  • 过于复杂的泛型约束
示例:
typescript
// ❌ AI-generated: Type workaround
const data = response.data as any;
const result = processData(data as ProcessedData);

// ✅ Clean: Proper typing
const data = response.data;
const result = processData(data);

4. Style Inconsistencies

4. 风格不一致问题

Patterns:
  • Naming conventions different from rest of file
  • Formatting that doesn't match surrounding code
  • Import organization inconsistent with file patterns
  • Variable declarations inconsistent with file style
Example:
javascript
// ❌ AI-generated: Inconsistent style
const UserData = fetchUser();
var processedData = process(UserData);
let FinalResult = format(processedData);

// ✅ Clean: Consistent style
const userData = fetchUser();
const processedData = process(userData);
const finalResult = format(processedData);
模式:
  • 与文件其余部分不同的命名规范
  • 与周围代码不匹配的格式
  • 与文件模式不一致的导入组织方式
  • 与文件风格不符的变量声明
示例:
javascript
// ❌ AI-generated: Inconsistent style
const UserData = fetchUser();
var processedData = process(UserData);
let FinalResult = format(processedData);

// ✅ Clean: Consistent style
const userData = fetchUser();
const processedData = process(userData);
const finalResult = format(processedData);

5. AI Tells

5. AI生成特征

Patterns:
  • Unnecessary emoji usage in code or comments
  • Overly verbose variable names
  • Redundant intermediate variables
  • "Just in case" code with no actual use case
模式:
  • 代码或注释中不必要的表情符号使用
  • 过于冗长的变量名
  • 冗余的中间变量
  • 无实际使用场景的“以防万一”代码

Cleanup Process

清理流程

1. Get the Diff

1. 获取差异

bash
git diff $(git merge-base HEAD main)..HEAD --name-only
bash
git diff $(git merge-base HEAD main)..HEAD --name-only

2. Analyze Each File

2. 分析每个文件

For each changed file:
  • Read the full file to understand existing style
  • Identify patterns from slop categories
  • Make surgical edits to remove slop
  • Preserve functionality
对于每个已修改的文件:
  • 通读整个文件以了解现有风格
  • 识别冗余分类中的模式
  • 进行精准编辑以移除冗余内容
  • 保留功能完整性

3. Verification

3. 验证

  • Ensure code still compiles/runs
  • Changes should reduce code, not add more
  • Run tests to verify behavior
  • Check for any regressions
  • 确保代码仍可编译/运行
  • 变更应减少代码量,而非增加
  • 运行测试以验证行为不变
  • 检查是否存在任何回归问题

Examples

示例

Example 1: Comment Cleanup

示例1:注释清理

Input: Remove unnecessary comments from
src/auth.js
Output:
markdown
undefined
输入:移除
src/auth.js
中的不必要注释
输出
markdown
undefined

AI Code Cleanup: src/auth.js

AI Code Cleanup: src/auth.js

Removed

Removed

  • 12 redundant comments explaining obvious code
  • 3 comments inconsistent with file style
  • 5 over-documented simple operations
  • 12 redundant comments explaining obvious code
  • 3 comments inconsistent with file style
  • 5 over-documented simple operations

Changes

Changes

javascript
// Before
// Function to validate user email
// Takes email string as input
// Returns boolean indicating validity
function validateEmail(email) {
  // Check if email is not empty
  if (!email) {
    return false; // Return false if empty
  }
  // Return regex test result
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

// After
function validateEmail(email) {
  if (!email) return false;
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
javascript
// Before
// Function to validate user email
// Takes email string as input
// Returns boolean indicating validity
function validateEmail(email) {
  // Check if email is not empty
  if (!email) {
    return false; // Return false if empty
  }
  // Return regex test result
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

// After
function validateEmail(email) {
  if (!email) return false;
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

Result

结果

  • Lines reduced: 12 → 4
  • Functionality preserved
  • Tests pass
undefined
  • 行数减少:12 → 4
  • 功能保留
  • 测试通过
undefined

Example 2: Defensive Bloat Removal

示例2:防御性冗余代码移除

Input: Remove defensive bloat from
src/api/users.js
Output:
markdown
undefined
输入:移除
src/api/users.js
中的防御性冗余代码
输出
markdown
undefined

AI Code Cleanup: src/api/users.js

AI Code Cleanup: src/api/users.js

Removed

Removed

  • 3 unnecessary try/catch blocks
  • 8 redundant null checks on validated inputs
  • 2 error handlers that can never trigger
  • 3 unnecessary try/catch blocks
  • 8 redundant null checks on validated inputs
  • 2 error handlers that can never trigger

Changes

Changes

javascript
// Before
async function getUser(userId) {
  try {
    if (!userId || typeof userId !== 'string') {
      throw new Error('Invalid userId');
    }
    const user = await db.users.findById(userId);
    if (user && user.id) {
      return user;
    }
    return null;
  } catch (error) {
    console.error(error);
    throw error;
  }
}

// After
async function getUser(userId) {
  const user = await db.users.findById(userId);
  return user || null;
}
javascript
// Before
async function getUser(userId) {
  try {
    if (!userId || typeof userId !== 'string') {
      throw new Error('Invalid userId');
    }
    const user = await db.users.findById(userId);
    if (user && user.id) {
      return user;
    }
    return null;
  } catch (error) {
    console.error(error);
    throw error;
  }
}

// After
async function getUser(userId) {
  const user = await db.users.findById(userId);
  return user || null;
}

Result

结果

  • Code reduced: 15 lines → 3 lines
  • Functionality preserved
  • Error handling appropriate for context
undefined
  • 代码减少:15行 → 3行
  • 功能保留
  • 错误处理符合上下文需求
undefined

Reference Files

参考文件

  • references/REFACTORING_PLAN.template.md
    - Refactoring plan template with code smells, before/after metrics, and rollback strategy
  • references/REFACTORING_PLAN.template.md
    - 包含代码异味、前后指标和回滚策略的重构计划模板

Best Practices

最佳实践

Cleanup Guidelines

清理指南

  1. Preserve Functionality: Only remove code that doesn't affect behavior
  2. Maintain Style: Follow existing project conventions
  3. Keep Real Errors: Don't remove legitimate error handling
  4. Test After Changes: Always verify code still works
  5. Incremental: Make changes incrementally, test as you go
  1. 保留功能完整性:仅移除不影响行为的代码
  2. 维持风格一致性:遵循现有项目规范
  3. 保留真实错误处理:不要移除合理的错误处理代码
  4. 变更后测试:始终验证代码仍可正常工作
  5. 增量式变更:逐步进行变更,边改边测

What to Keep

需要保留的内容

  • Legitimate error handling
  • Necessary type assertions
  • Helpful comments that add context
  • Defensive code for untrusted inputs
  • Style that matches the codebase
  • 合理的错误处理
  • 必要的类型断言
  • 提供上下文的有用注释
  • 针对不可信输入的防御性代码
  • 与代码库一致的风格

What to Remove

需要移除的内容

  • Obvious comments
  • Unnecessary defensive code
  • Type workarounds
  • Style inconsistencies
  • AI-generated artifacts
  • 显而易见的注释
  • 不必要的防御性代码
  • 类型变通方案
  • 风格不一致问题
  • AI生成的冗余产物

Related Use Cases

相关用例

  • Post-AI coding cleanup
  • Code review preparation
  • Code quality improvement
  • Style standardization
  • Removing technical debt
  • AI编码后清理
  • 代码评审准备
  • 代码质量提升
  • 风格统一
  • 移除技术债务