今天要分享的是我精心打磨的代码规范执行子代理——这个配置能让Claude Code像一个严格但友善的代码质量管家,从代码风格到架构模式,从命名规范到测试覆盖率,帮你建立和维护团队的代码质量标准。

一、为什么代码规范需要专属子代理?

1.1 代码规范的独特挑战

团队开发中,代码风格不统一就像乐队演奏时各弹各的调:

// 场景对比:团队中不同开发者的代码风格

// ❌ 开发者A的风格
function calc_user_score(usr){
var score=0
if(usr.level=="vip"){
score=usr.points*2}
else{score=usr.points}
return score}

// ❌ 开发者B的风格
function CalculateUserScore( User )
{
    let Score = 0;
    if( User.Level === "vip" )
    {
        Score = User.Points * 2;
    }
    else
    {
        Score = User.Points;
    }
    return Score;
}

// ✅ 代码规范子代理统一后的风格
/**
 * 计算用户积分
 * @param {User} user - 用户对象
 * @returns {number} 计算后的积分
 */
function calculateUserScore(user) {
const multiplier = user.level === 'vip' ? 2 : 1;
return user.points * multiplier;
}

1.2 代码规范子代理解决的五大痛点

| 痛点类型

|

具体问题

|

子代理解决方案

风格混乱

|

每个人写法不同

|

自动格式化统一

| |

质量参差

|

代码质量不一致

|

质量门槛把关

| |

审查耗时

|

人工审查效率低

|

自动化检查

| |

规范执行难

|

规范文档没人看

|

工具强制执行

| |

新人上手慢

|

不了解团队规范

|

自动提示纠正

|

1.3 通俗理解代码规范

代码规范就像交通规则:

  • 没有规范 = 没有交通规则(各行其道,容易撞车)
  • 有规范没执行 = 有规则没人遵守(形同虚设)
  • 自动化规范 = 智能交通系统(自动引导,违规提醒)

代码规范子代理就像一个智能交通管理系统,让所有代码都按规则"行驶"。

二、代码规范子代理配置完全解析

2.1 配置文件双语版本

英文原版(推荐使用)
---
name: code-standards-enforcer
description: Claude Code代码规范守护者子代理实战指南:打造你的团队代码质量管家 --知识铺
model: sonnet
---
You are a code quality specialist focused on establishing and enforcing consistent development standards across teams and projects.

## Standards Enforcement Expertise
- Coding style guide creation and customization
- Linting and formatting tool configuration (ESLint, Prettier, SonarQube)
- Git hooks and pre-commit workflow automation
- Code review checklist development and automation
- Architectural decision record (ADR) template creation
- Documentation standards and API specification enforcement
- Performance benchmarking and quality gate establishment
- Dependency management and security policy enforcement

## Quality Assurance Framework
1. Automated code formatting on commit with Prettier/Black
2. Comprehensive linting rules for language-specific best practices  
3. Architecture compliance checking with custom rules
4. Naming convention enforcement across codebase
5. Comment and documentation quality assessment
6. Test coverage thresholds and quality metrics
7. Performance regression detection in CI pipeline
8. Security policy compliance verification

## Enforceable Standards Categories
- Code formatting and indentation consistency
- Naming conventions for variables, functions, and classes
- File and folder structure organization patterns
- Import/export statement ordering and grouping
- Error handling and logging standardization
- Database query optimization and ORM usage patterns
- API design consistency and REST/GraphQL standards
- Component architecture and design pattern adherence
- Configuration management and environment variable handling

## Implementation Strategy
- Gradual rollout with team education and training
- IDE integration for real-time feedback and correction
- CI/CD pipeline integration with quality gates
- Custom rule development for organization-specific needs
- Metrics dashboard for code quality trend tracking
- Exception management for legacy code migration
- Team onboarding automation with standards documentation
- Regular standards review and community feedback integration
- Tool version management and configuration synchronization

Establish maintainable quality standards that enhance team productivity while ensuring consistent, professional codebase evolution. Focus on automation over manual enforcement to reduce friction and improve developer experience.
中文理解版(带详细注释)
---
name: code-standards-enforcer
description: Claude Code代码规范守护者子代理实战指南:打造你的团队代码质量管家 --知识铺
model: sonnet
---
你是一位代码质量专家,专注于在团队和项目间建立并执行一致的开发标准。

## 标准执行专业技能 / Standards Enforcement Expertise
- 编码风格指南创建和定制
- 代码检查和格式化工具配置(ESLint、Prettier、SonarQube)
- Git钩子和预提交工作流自动化
- 代码审查清单开发和自动化
- 架构决策记录(ADR)模板创建
- 文档标准和API规范执行
- 性能基准和质量门槛建立
- 依赖管理和安全策略执行

## 质量保证框架 / Quality Assurance Framework
1. 使用Prettier/Black在提交时自动格式化代码
2. 针对特定语言最佳实践的全面检查规则
3. 使用自定义规则的架构合规性检查
4. 跨代码库的命名约定执行
5. 注释和文档质量评估
6. 测试覆盖率阈值和质量指标
7. CI管道中的性能回归检测
8. 安全策略合规性验证

## 可执行标准类别 / Enforceable Standards Categories
- 代码格式和缩进一致性
- 变量、函数和类的命名约定
- 文件和文件夹结构组织模式
- 导入/导出语句排序和分组
- 错误处理和日志标准化
- 数据库查询优化和ORM使用模式
- API设计一致性和REST/GraphQL标准
- 组件架构和设计模式遵守
- 配置管理和环境变量处理

## 实施策略 / Implementation Strategy
- 配合团队教育和培训的渐进式推出
- IDE集成实现实时反馈和纠正
- CI/CD管道集成与质量门槛
- 组织特定需求的自定义规则开发
- 代码质量趋势跟踪的指标仪表板
- 遗留代码迁移的异常管理
- 带标准文档的团队入职自动化
- 定期标准审查和社区反馈集成
- 工具版本管理和配置同步

建立可维护的质量标准,提升团队生产力,同时确保一致、专业的代码库演进。
专注于自动化而非手动执行,减少摩擦,改善开发者体验。

2.2 核心概念通俗解释

// 1. 什么是Linting?
// 就像语法检查器,找出代码中的问题
// ESLint配置示例
{
"rules": {
    "no-unused-vars": "error",  // 禁止未使用的变量
    "no-console": "warn",       // 警告console语句
    "indent": ["error", 2]      // 强制2空格缩进
  }
}

// 2. 什么是代码格式化?
// 就像自动排版,让代码整齐美观
// Prettier会自动修正:
const ugly={a:1,b:2,c:3}  // 格式化前
const pretty = { a: 1, b: 2, c: 3 };  // 格式化后

// 3. 什么是Git Hooks?
// 就像门禁系统,提交代码前自动检查
// pre-commit hook示例
#!/bin/sh
npm run lint
npm run test

// 4. 什么是质量门槛?
// 就像考试及格线,达不到标准就不能通过
if (coverage < 80) {
thrownewError('测试覆盖率必须达到80%');
}

三、5分钟快速配置指南

步骤1:打开子代理管理

# 在Claude Code中输入
/agents

步骤2:创建规范执行专家

  1. 点击 “Create New Agent**”**
  2. 选择 **“User-level agent”**(全局可用)

步骤3:粘贴配置

选择上面的英文版或中文版配置,完整粘贴

步骤4:配置工具权限

规范执行需要的权限:

  • Read - 读取代码文件
  • Write - 创建配置文件
  • Edit - 修改代码格式
  • MultiEdit - 批量格式化
  • Bash - 运行检查工具

步骤5:选择标识颜色

建议选择 🟡 黄色(代表规范和标准),保存配置

四、实战案例:代码规范子代理的强大能力

案例1:建立完整的团队代码规范体系

输入指令

为我们的JavaScript项目建立完整的代码规范体系

代码规范子代理输出完整的规范方案

// ========== 团队代码规范体系 ==========
// 项目:JavaScript/TypeScript全栈项目
// 覆盖:前端React + 后端Node.js

// 第一部分:工具链配置

// 1. ESLint配置 (.eslintrc.js)
module.exports = {
root: true,
env: {
    browser: true,
    es2021: true,
    node: true,
    jest: true
  },
extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended'// 必须放最后
  ],
parser: '@typescript-eslint/parser',
parserOptions: {
    ecmaFeatures: { jsx: true },
    ecmaVersion: 12,
    sourceType: 'module'
  },
plugins: ['react', '@typescript-eslint', 'import', 'jsx-a11y'],
rules: {
    // 代码质量
    'no-console': ['warn', { allow: ['warn', 'error'] }],
    'no-debugger': 'error',
    'no-alert': 'error',
    'no-unused-vars': 'off',  // 使用TS规则
    '@typescript-eslint/no-unused-vars': ['error', { 
      argsIgnorePattern: '^_',
      varsIgnorePattern: '^_'
    }],
    
    // 命名规范
    'camelcase': ['error', { properties: 'never' }],
    '@typescript-eslint/naming-convention': [
      'error',
      {
        selector: 'interface',
        format: ['PascalCase'],
        prefix: ['I']
      },
      {
        selector: 'typeAlias',
        format: ['PascalCase']
      },
      {
        selector: 'enum',
        format: ['PascalCase']
      }
    ],
    
    // React规范
    'react/prop-types': 'off',  // 使用TypeScript
    'react/react-in-jsx-scope': 'off',  // React 17+
    'react/jsx-filename-extension': ['error', { 
      extensions: ['.tsx', '.jsx'] 
    }],
    
    // 导入规范
    'import/order': ['error', {
      groups: [
        'builtin',
        'external',
        'internal',
        'parent',
        'sibling',
        'index'
      ],
      'newlines-between': 'always',
      alphabetize: { order: 'asc' }
    }]
  }
};

// 2. Prettier配置 (.prettierrc)
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"jsxBracketSameLine": false,
"arrowParens": "always",
"endOfLine": "lf"
}

// 3. Git Hooks配置 (.husky + lint-staged)
// package.json
{
"scripts": {
    "prepare": "husky install",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
    "format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\""
  },
"lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ],
    "*.{json,css,md}": [
      "prettier --write"
    ]
  }
}

// .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
npm run test:staged

// .husky/commit-msg  
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx commitlint --edit $1

// 第二部分:代码组织规范

// 项目结构规范
const projectStructure = `
src/
├── components/          # 可复用组件
│   ├── common/         # 通用组件
│   ├── layouts/        # 布局组件
│   └── features/       # 功能组件
├── pages/              # 页面组件
├── hooks/              # 自定义Hooks
├── services/           # API服务
├── utils/              # 工具函数
├── types/              # TypeScript类型
├── styles/             # 全局样式
├── constants/          # 常量定义
└── tests/              # 测试文件
`;

// 文件命名规范
const namingConventions = {
components: 'PascalCase.tsx',     // UserProfile.tsx
pages: 'PascalCase.tsx',          // HomePage.tsx
hooks: 'camelCase.ts',            // useAuth.ts
utils: 'camelCase.ts',            // formatDate.ts
types: 'PascalCase.ts',           // User.ts
constants: 'SCREAMING_SNAKE.ts',  // API_ENDPOINTS.ts
tests: '*.test.ts or *.spec.ts'   // user.test.ts
};

// 第三部分:代码风格规范

class CodeStyleGuide {
// 1. 函数规范
static functionRules = `
    // ✅ 好的做法:函数单一职责,名称描述清晰
    function calculateUserDiscount(user: User): number {
      if (user.isVip) {
        return 0.2;
      }
      return 0.1;
    }
    
    // ❌ 不好的做法:函数做太多事情
    function processUser(user) {
      // 验证、计算、保存、发送邮件...
    }
  `;

// 2. 变量规范
static variableRules = `
    // ✅ 好的做法:语义化命名
    const isUserLoggedIn = true;
    const maxRetryCount = 3;
    const userEmail = 'user@example.com';
    
    // ❌ 不好的做法:简写、魔法数字
    const flag = true;
    const n = 3;
    const str = 'user@example.com';
  `;

// 3. 注释规范
static commentRules = `
    /**
     * 计算订单总价
     * @param items - 订单项列表
     * @param discount - 折扣率 (0-1)
     * @returns 计算后的总价
     */
    function calculateTotal(
      items: OrderItem[],
      discount: number
    ): number {
      // 计算商品总价
      const subtotal = items.reduce(
        (sum, item) => sum + item.price * item.quantity,
        0
      );
      
      // 应用折扣
      return subtotal * (1 - discount);
    }
  `;
}

// 第四部分:质量门槛配置

// SonarQube质量门槛
const qualityGates = {
coverage: {
    threshold: 80,
    message: '代码覆盖率必须达到80%'
  },
duplications: {
    threshold: 3,
    message: '重复代码不能超过3%'
  },
maintainability: {
    rating: 'A',
    message: '可维护性评级必须为A'
  },
reliability: {
    bugs: 0,
    message: '不允许有bug'
  },
security: {
    vulnerabilities: 0,
    message: '不允许有安全漏洞'
  }
};

// Jest测试配置
module.exports = {
collectCoverageFrom: [
    'src/**/*.{js,jsx,ts,tsx}',
    '!src/**/*.d.ts',
    '!src/index.tsx',
    '!src/serviceWorker.ts'
  ],
coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80
    }
  }
};

// 第五部分:CI/CD集成

// GitHub Actions工作流
const ciWorkflow = `
name: Code Quality Check

on:
  pull_request:
    branches: [main, develop]
  push:
    branches: [main, develop]

jobs:
  quality-check:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v2
    
    - name: Setup Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '18'
        cache: 'npm'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Run ESLint
      run: npm run lint
    
    - name: Check formatting
      run: npm run format:check
    
    - name: Run tests
      run: npm run test:coverage
    
    - name: SonarCloud Scan
      uses: SonarSource/sonarcloud-github-action@master
      env:
        GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
        SONAR_TOKEN: \${{ secrets.SONAR_TOKEN }}
    
    - name: Check quality gates
      run: |
        if [ "\$(cat coverage/coverage-summary.json | jq '.total.lines.pct')" -lt 80 ]; then
          echo "Coverage is below 80%"
          exit 1
        fi
`;

案例2:自动化代码审查系统

输入

创建一个自动化代码审查系统

代码规范子代理输出

// 自动化代码审查系统

class AutomatedCodeReview {
private rules: ReviewRule[] = [];
private metrics: CodeMetrics;

constructor() {
    this.initializeRules();
    this.metrics = new CodeMetrics();
  }

// 1. 定义审查规则
  initializeRules() {
    this.rules = [
      {
        name: '函数复杂度检查',
        check: (code: string) => {
          const complexity = this.calculateCyclomaticComplexity(code);
          return {
            passed: complexity <= 10,
            message: `函数复杂度为${complexity},建议拆分`
          };
        }
      },
      {
        name: '函数长度检查',
        check: (code: string) => {
          const lines = code.split('\n').length;
          return {
            passed: lines <= 50,
            message: `函数有${lines}行,建议不超过50行`
          };
        }
      },
      {
        name: '命名规范检查',
        check: (code: string) => {
          const violations = this.checkNamingConventions(code);
          return {
            passed: violations.length === 0,
            message: violations.join('\n')
          };
        }
      }
    ];
  }

// 2. 执行代码审查
async review(pullRequest: PullRequest): Promise<ReviewResult> {
    const results: ReviewComment[] = [];
    
    for (const file of pullRequest.files) {
      const fileResults = awaitthis.reviewFile(file);
      results.push(...fileResults);
    }
    
    return {
      status: this.determineStatus(results),
      comments: results,
      metrics: this.calculateMetrics(pullRequest)
    };
  }

// 3. 生成审查报告
  generateReport(result: ReviewResult): string {
    return`
## 代码审查报告

### 总体评分:${result.metrics.score}/100

### 发现的问题
${result.comments.map(c => `- [ ] ${c.message}`).join('\n')}

### 代码质量指标
- 测试覆盖率:${result.metrics.coverage}%
- 代码重复率:${result.metrics.duplication}%
- 技术债务:${result.metrics.debt}小时

### 建议改进
${this.generateSuggestions(result)}
    `;
  }
}

五、进阶技巧:定制你的代码规范子代理

5.1 针对不同语言

Python****规范版

## Standards Enforcement Expertise
- PEP 8风格指南
- Black格式化工具
- Pylint代码检查
- mypy类型检查

Go规范版

## Standards Enforcement Expertise
- gofmt格式化
- golint检查
- go vet静态分析
- 有效Go编程规范

5.2 添加团队特色

## Team Standards
- 分支命名:feature/JIRA-123-description
- 提交信息:type(scope): message
- PR模板:必须包含测试和文档
- 代码所有权:CODEOWNERS文件

六、常见问题解答

Q1:代码规范子代理什么时候触发?

触发关键词

  • standard、规范、风格
  • lint、format、格式化
  • review、审查、检查
  • quality、质量

Q2:如何处理遗留代码?

渐进式改进策略:

  1. 建立基线(记录当前状态)
  2. 新代码严格执行规范
  3. 修改时顺带改进周围代码
  4. 定期技术债务清理
  5. 重要模块优先重构

Q3:如何让团队接受规范?

推广策略:

  • 工具自动化(减少人工)
  • 培训分享(理解价值)
  • 渐进实施(逐步严格)
  • 及时反馈(快速修正)
  • 榜样示范(优秀代码展示)

七、规范实施效果数据

| 评估指标

|

实施前

|

实施后

|

改进幅度

代码一致性

|

45%

|

95%

|

+111%

| |

审查时间

|

2小时

|

30分钟

|

-75%

| |

Bug率

|

15/千行

|

3/千行

|

-80%

| |

新人上手

|

2周

|

3天

|

-79%

| |

技术债务

|

增加

|

减少

|

-60%

|

八、总结:代码规范子代理的核心价值

这个代码规范守护者子代理带来的价值:

  1. 统一标准:让团队代码风格一致
  2. 自动执行:工具强制而非人工检查
  3. 持续改进:代码质量稳步提升
  4. 降低成本:减少审查和维护时间
  5. 知识传承:规范就是最好的文档

记住:好的代码规范不是限制创造力,而是让团队专注于解决问题而不是争论风格。

快速开始清单

  • [ ] 阅读子代理基础文章
  • [ ] 选择配置版本(英文/中文)
  • [ ] 输入 /agents 创建代理
  • [ ] 配置所有工具权限
  • [ ] 测试第一个功能:“建立项目代码规范”
  • [ ] 团队讨论并调整规范
  • [ ] 逐步推广实施

现在就配置你的代码规范守护者子代理,让团队代码整齐如一!📏✨

#子代理 #ClaudeCode #AI #程序员 #前端达人