Vibe Coding with Claude -- 项目内协作脚本

CLI 一键流 × 结构化改造(AST/Codemod)× 审计/回滚 × PR/CI 守门 × 企业级工程化
建议保存文件名:claude.mdCLAUDE.local.md。本手册为企业级代码库协作工程规范。

1. 总览与目的

本指南把 CLI 一键批改结构化/AST 级改造工程化审计/回滚 规范沉淀为可复制的团队实践,并以「Vibe Coding」的回合制提示脚本驱动你与 Claude/IDE Agent 的高效协作。

1.1 核心宗旨

  • 能用 一条命令 解决的问题,绝不用十次小步编辑
  • 所有批量变更可预览、可回滚、可审计,并通过 PR/CI 把好质量关
  • 文本替换覆盖不了时,果断切换 comby/semgrep/ts-morph/jscodeshift 等语义手术刀
  • 建立五层防护网:预览 → 备份 → 沙箱 → 验证 → 审计
收益矩阵:更快的仓库理解、更稳的批量重构、更低的回归风险、更清晰的团队共识、更高的工程化成熟度。

1.2 工程哲学:分层架构

L1: 文本替换
L2: 结构感知
L3: 语义分析
L4: 类型重构
L5: 架构演进

2. 会话启动与上下文收集

2.1 标准开场白(Kickoff Prompt)

每次与 Claude/Agent 协作,请先发送以下开场白:

请读取仓库根目录的 claude.md(或本 HTML 的 Markdown 版)并严格遵循。
任何批量操作必须先输出:

方案A:文本替换流(推荐度:★★☆☆☆)
bash
# 使用 sed/sd/perl
[代码]

方案B:AST改造流(推荐度:★★★★★)
typescript
# 使用 ts-morph/jscodeshift
[代码]

✅ 验证清单
☐ 类型检查:tsc --noEmit
☐ 单元测试:npm test -- --coverage
☐ 集成测试:npm run e2e
☐ 构建验证:npm run build

🔙 回滚方案
[具体步骤]

未经确认,禁止直接写入文件系统。

2.2 上下文收集清单

必需信息

  • 项目技术栈(框架/语言版本)
  • 代码规范(ESLint/Prettier配置)
  • 测试覆盖率基线
  • CI/CD配置

可选信息

  • 团队编码约定
  • 历史技术债
  • 性能基准线
  • 发布周期

3. 安全工程体系

3.1 五层防护网

预览
备份
沙箱
验证
审计

3.2 预览命令矩阵

# 统计影响范围
rg --stats -g '!{node_modules,dist,build}' 'PATTERN' | tail -n 20

# 采样预览(前10个匹配)
rg -m 10 -C 3 --heading -g '*.{ts,tsx}' 'PATTERN'

# 文件分布热力图
rg -l 'PATTERN' | xargs dirname | sort | uniq -c | sort -rn | head -20

# 复杂度评估(需要安装 tokei)
rg -l 'PATTERN' | xargs tokei --output json | jq '.Total'

3.3 备份策略矩阵

Git策略 文件系统策略 云端策略
# 方案1:临时分支
git checkout -b refactor/$(date +%Y%m%d-%H%M%S)

# 方案2:工作树(推荐)
git worktree add ../project-refactor HEAD
cd ../project-refactor

# 方案3:存储快照
git stash push -m "Before refactoring: $(date)"
# 方案1:硬链接备份(节省空间)
rsync -av --link-dest=$(pwd) . ../backup-$(date +%Y%m%d)

# 方案2:增量备份
tar --create --file=backup-$(date +%Y%m%d).tar --listed-incremental=backup.snar src/

# 方案3:.bak后缀(适合小规模)
fd -e ts -e tsx -x cp {} {}.bak \;
# AWS S3
aws s3 sync . s3://my-bucket/backup-$(date +%Y%m%d) --exclude "node_modules/*"

# Google Cloud Storage
gsutil -m rsync -r -x "node_modules" . gs://my-bucket/backup-$(date +%Y%m%d)

# Azure Blob
az storage blob upload-batch -s . -d backup-$(date +%Y%m%d) --pattern "src/**"

3.4 验证金字塔

# Level 1: 语法验证
tsc --noEmit --incremental --tsBuildInfoFile .tsbuildinfo

# Level 2: 静态分析
eslint . --ext .ts,.tsx --max-warnings 0
semgrep --config=auto --metrics=off

# Level 3: 单元测试
npm test -- --coverage --coverageReporters=json-summary
jq '.total.lines.pct' coverage/coverage-summary.json

# Level 4: 集成测试
npm run test:integration -- --bail

# Level 5: E2E测试
npm run test:e2e -- --headless

# Level 6: 性能回归
npm run benchmark
lighthouse http://localhost:3000 --output=json | jq '.categories.performance.score'

4. 技术选型决策树

4.1 工具选择流程图

                        ┌─────────────┐
                        │   开始分析   │
                        └──────┬──────┘
                               │
                        ┌──────▼──────┐
                        │ 是否涉及语法? │
                        └──┬───────┬──┘
                           │ No    │ Yes
                    ┌──────▼──┐  ┌─▼──────────┐
                    │文本工具  │  │ 是否改变类型? │
                    └─────────┘  └─┬────────┬──┘
                                   │ No     │ Yes
                            ┌──────▼──┐  ┌─▼──────┐
                            │结构工具  │  │ AST工具 │
                            └─────────┘  └────────┘
          

4.2 工具能力矩阵

工具 适用场景 性能 精确度 学习曲线 推荐指数
sed/sd 简单文本替换 ⚡⚡⚡⚡⚡ ★★☆☆☆ ★★★☆☆
perl 复杂正则、多行 ⚡⚡⚡⚡☆ ★★★☆☆ ★★★★☆
comby 结构感知替换 ⚡⚡⚡☆☆ ★★★★☆ ★★★★★
semgrep 安全/规则扫描 ⚡⚡⚡☆☆ ★★★★★ ★★★★☆
ts-morph TypeScript AST ⚡⚡☆☆☆ ★★★★★ ★★★★★
jscodeshift JavaScript迁移 ⚡⚡☆☆☆ ★★★★★ ★★★★☆

5. CLI流水线架构

5.1 标准流水线模板

#!/usr/bin/env bash
set -euo pipefail # 严格模式

# 配置
readonly PATTERN="${1:?Usage: $0 <pattern> <replacement>}"
readonly REPLACEMENT="${2:?}"
readonly EXCLUDE_DIRS="node_modules|dist|build|coverage|.git"
readonly INCLUDE_EXTS="ts|tsx|js|jsx"
readonly BACKUP_DIR=".refactor-backup-$(date +%Y%m%d-%H%M%S)"

# 彩色输出
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[0;33m'
readonly NC='\033[0m'

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }

# 预检查
check_dependencies() {
  local deps=(rg fd sd jq tsc)
  for dep in "${deps[@]}"; do
    if ! command -v "$dep" &> /dev/null; then
      log_error "Missing dependency: $dep"
      exit 1
    fi
  done
}

# 主流程
main() {
  check_dependencies
  analyze_impact
  create_backup
  perform_replacement
  validate_changes
  
  log_info "✅ Refactoring completed successfully"
  log_info "Review changes with: git diff"
  log_info "Backup location: $BACKUP_DIR"
}

main "$@"

5.2 高级流水线模式

并行处理模式

# GNU Parallel加速
fd -e ts -e tsx |
parallel -j+0 --bar \
  "sd 'old' 'new' {}"

# xargs并行
fd -0 -e ts |
xargs -0 -P $(nproc) -I {} \
  sd 'old' 'new' {}

增量处理模式

# 只处理已修改文件
git diff --name-only |
grep -E '\.(ts|tsx)$' |
xargs -I {} sd 'old' 'new' {}

# 基于时间戳
fd -e ts --changed-within 1d |
xargs sd 'old' 'new'

6. AST改造工程

6.1 ts-morph高级模式

// scripts/codemods/advanced-refactor.ts
import { Project, Node, SyntaxKind, ts } from "ts-morph";
import * as path from "path";
import * as fs from "fs";

interface RefactorConfig {
  tsConfigPath: string;
  include: string[];
  exclude: string[];
  dryRun: boolean;
  verbose: boolean;
}

class AdvancedRefactor {
  private project: Project;
  private config: RefactorConfig;
  private changes: Map<string, string[]> = new Map();

  constructor(config: RefactorConfig) {
    this.config = config;
    this.project = new Project({
      tsConfigFilePath: config.tsConfigPath,
      skipAddingFilesFromTsConfig: false,
    });
  }

  // 示例:智能接口继承优化
  async optimizeInterfaces() {
    const sourceFiles = this.project.getSourceFiles(this.config.include);
    
    for (const sourceFile of sourceFiles) {
      const interfaces = sourceFile.getInterfaces();
      
      for (const iface of interfaces) {
        // 收集继承信息
        const heritage = iface.getHeritageClauses();
        const members = iface.getMembers();
        
        if (heritage.length > 0 && members.length === 0) {
          // 空接口且有继承 -> 类型别名
          this.convertToTypeAlias(iface);
        } else if (heritage.length > 1) {
          // 多重继承 -> 交叉类型
          this.convertToIntersectionType(iface);
        }
      }
    }

    return this.applyChanges();
  }

  private async applyChanges() {
    if (this.config.dryRun) {
      console.log('\n=== DRY RUN MODE ===');
      console.log('Changes that would be applied:');
      
      for (const [file, changes] of this.changes) {
        console.log(`\n${file}:`);
        changes.forEach(c => console.log(`  - ${c}`));
      }
      
      return { applied: false, changes: this.changes };
    }

    // 保存所有更改
    await this.project.save();

    console.log(`\n✅ Applied ${this.changes.size} file changes`);
    return { applied: true, changes: this.changes };
  }
}

6.2 Semgrep规则工程

# .semgrep/rules/typescript-modernization.yml
rules:
  # 规则1:接口优化
  - id: empty-interface-to-type
    languages: [typescript]
    message: Empty interface with extends should be type alias
    severity: WARNING
    pattern: |
      interface $NAME extends $BASE {
      }
    fix: |
      type $NAME = $BASE;
    metadata:
      category: refactoring
      technology: typescript
      
  # 规则2:可选链优化
  - id: use-optional-chaining
    languages: [typescript, javascript]
    message: Use optional chaining instead of && chains
    severity: INFO
    pattern: |
      $X && $X.$Y
    fix: |
      $X?.$Y
    metadata:
      category: modernization
      min_version: "3.7"

7. 设计模式库

7.1 渐进式迁移模式

核心思想:将大规模重构分解为小批次,每个批次都有独立的验证和回滚机制,确保系统稳定性。
// patterns/progressive-migration.ts
interface MigrationStrategy<T, R> {
  name: string;
  canMigrate: (input: T) => boolean;
  migrate: (input: T) => R;
  validate: (result: R) => boolean;
  rollback: (original: T, failed: R) => T;
}

class ProgressiveMigrator<T, R> {
  private strategies: MigrationStrategy<T, R>[] = [];
  private results: Map<string, MigrationResult<T, R>> = new Map();

  async migrate(items: T[], options: MigrationOptions = {}) {
    const { batchSize = 10, stopOnError = false, dryRun = false } = options;
    
    for (let i = 0; i < items.length; i += batchSize) {
      const batch = items.slice(i, i + batchSize);
      
      for (const item of batch) {
        try {
          const strategy = this.selectStrategy(item);
          if (!strategy) continue;
          
          if (dryRun) {
            console.log(`[DRY RUN] Would apply ${strategy.name} to item`);
            continue;
          }
          
          const result = strategy.migrate(item);
          
          if (!strategy.validate(result)) {
            throw new Error(`Validation failed for ${strategy.name}`);
          }
          
          this.results.set(this.getItemId(item), { 
            success: true, 
            strategy: strategy.name, 
            result 
          });
        } catch (error) {
          this.results.set(this.getItemId(item), { 
            success: false, 
            error: error.message, 
            original: item 
          });
          
          if (stopOnError) throw error;
        }
      }
      
      // 批次间验证
      await this.validateBatch();
    }

    return this.generateReport();
  }
}

8. 审计与合规体系

8.1 变更审计框架

// audit/change-auditor.ts
interface AuditEntry {
  timestamp: Date;
  operator: string;
  command: string;
  affectedFiles: string[];
  diffStats: DiffStats;
  validationResults: ValidationResult[];
  rollbackPlan: string;
  approved: boolean;
  approver?: string;
}

class ChangeAuditor {
  async auditChange(change: ProposedChange): Promise<AuditReport> {
    const entry: AuditEntry = {
      timestamp: new Date(),
      operator: process.env.USER || 'unknown',
      command: change.command,
      affectedFiles: await this.getAffectedFiles(change),
      diffStats: await this.calculateDiffStats(change),
      validationResults: await this.runValidators(change),
      rollbackPlan: this.generateRollbackPlan(change),
      approved: false
    };
    
    // 风险评分
    const riskScore = this.calculateRiskScore(entry);

    // 自动审批低风险变更
    if (riskScore < 3) {
      entry.approved = true;
      entry.approver = 'auto';
    }

    return this.generateComplianceReport(entry, riskScore);
  }

  private calculateRiskScore(entry: AuditEntry): number {
    let score = 0;
    
    // 文件数量风险
    if (entry.affectedFiles.length > 50) score += 3;
    else if (entry.affectedFiles.length > 10) score += 2;
    else if (entry.affectedFiles.length > 5) score += 1;

    // 变更规模风险
    const { additions, deletions } = entry.diffStats;
    if (additions + deletions > 1000) score += 3;
    else if (additions + deletions > 500) score += 2;
    else if (additions + deletions > 100) score += 1;

    return Math.min(score, 10); // 最高10分
  }
}

8.2 PR/CI集成模板

# .github/workflows/refactor-validation.yml
name: Refactor Validation

on:
  pull_request:
    types: [opened, synchronize]
    paths: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx']

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
          
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
          
      - name: Install dependencies
        run: |
          npm ci
          npm install -g rg fd sd semgrep
          
      - name: Detect refactoring patterns
        id: detect
        run: |
          # 检测大规模变更
          changed_files=$(git diff --name-only origin/main...HEAD | wc -l)
          echo "changed_files=$changed_files" >> $GITHUB_OUTPUT
          
          if [ $changed_files -gt 50 ]; then
            echo "large_refactor=true" >> $GITHUB_OUTPUT
          fi
          
      - name: Run safety checks
        if: steps.detect.outputs.large_refactor == 'true'
        run: |
          # 类型检查
          npm run type-check
          
          # 静态分析
          npm run lint
          
          # Semgrep扫描
          semgrep --config=auto --json -o semgrep-results.json

9. 灾难恢复方案

9.1 多级回滚策略

EMERGENCY SCRIPT
#!/usr/bin/env bash
# scripts/rollback.sh
set -euo pipefail

# 回滚级别定义
readonly LEVEL_1_GIT="git"       # Git级别
readonly LEVEL_2_BACKUP="backup" # 备份文件
readonly LEVEL_3_SNAPSHOT="snapshot" # 系统快照
readonly LEVEL_4_REMOTE="remote" # 远程备份

rollback_level_1() {
  echo "执行Git级别回滚..."
  
  # 方案1: 撤销未提交的更改
  if [[ -n $(git status --porcelain) ]]; then
    echo "检测到未提交更改,是否撤销? (y/n)"
    read -r response
    if [[ "$response" == "y" ]]; then
      git checkout -- .
      git clean -fd
    fi
  fi
}

# 智能回滚决策
smart_rollback() {
  echo "🔍 分析回滚需求..."
  
  # 检测问题类型
  local issues=()
  
  # TypeScript错误
  if ! tsc --noEmit &> /dev/null; then
    issues+=("TypeScript编译错误")
  fi
  
  # 测试失败
  if ! npm test &> /dev/null; then
    issues+=("测试失败")
  fi
  
  if [[ ${#issues[@]} -eq 0 ]]; then
    echo "✅ 未检测到问题"
    return 0
  fi
  
  echo "检测到以下问题:"
  printf ' - %s\n' "${issues[@]}"
  
  # 推荐回滚策略
  if [[ ${#issues[@]} -eq 1 ]]; then
    echo "建议: Level 1 (Git回滚)"
    rollback_level_1
  else
    echo "建议: Level 2+ (深度恢复)"
  fi
}

9.2 自动恢复机制

监控机制:建立30秒间隔的健康检查,自动检测TypeScript编译错误、测试失败等问题,并触发对应级别的恢复策略。

10. 度量与优化

10.1 重构效果度量矩阵

维度 指标 改进目标 衡量方法
复杂度 圈复杂度 减少20% complexity-report
性能 构建时间 提升15% webpack-bundle-analyzer
质量 类型覆盖率 达到95% type-coverage
维护性 重复代码 减少30% jscpd

10.2 自动化度量收集

// metrics/collect-metrics.ts
class MetricsCollector {
  async collectBeforeAfter(beforeCommit: string, afterCommit: string) {
    const before = await this.collectAt(beforeCommit);
    const after = await this.collectAt(afterCommit);

    return {
      complexity: {
        cyclomaticBefore: before.complexity.cyclomatic,
        cyclomaticAfter: after.complexity.cyclomatic,
        improvement: this.calculateImprovement(
          before.complexity.cyclomatic,
          after.complexity.cyclomatic
        )
      },
      performance: {
        buildTimeBefore: before.performance.buildTime,
        buildTimeAfter: after.performance.buildTime,
        improvement: this.calculateImprovement(
          before.performance.buildTime,
          after.performance.buildTime
        )
      }
    };
  }

  generateReport(metrics: RefactorMetrics): string {
    return `
# 重构效果度量报告

## 📊 复杂度改进
- 圈复杂度: ${metrics.complexity.cyclomaticBefore} → ${metrics.complexity.cyclomaticAfter} (${metrics.complexity.improvement}%)

## ⚡ 性能影响  
- 构建时间: ${metrics.performance.buildTimeBefore}ms → ${metrics.performance.buildTimeAfter}ms

## 📈 建议
${this.generateRecommendations(metrics)}
    `;
  }
}

11. 实战剧本库

11.1 Interface继承清理剧本

PLAYBOOK
# Step 1: 发现与分析
echo "=== 分析Interface继承模式 ==="
rg -t ts "interface\s+\w+\s+extends" --stats

# Step 2: 分类统计
echo "=== 空继承接口 ==="
rg -U -t ts "interface\s+(\w+)\s+extends\s+(\w+)\s*{\s*}" -r '$1 extends $2 (empty)'

# Step 3: 生成改造方案
cat > refactor-interfaces.js << 'EOF'
const transformer = (fileInfo, api) => {
  const j = api.jscodeshift;
  const root = j(fileInfo.source);

  // 空继承 -> 类型别名
  root.find(j.TSInterfaceDeclaration)
    .filter(path => {
      const node = path.node;
      return node.extends?.length > 0 && node.body.body.length === 0;
    })
    .replaceWith(path => {
      const node = path.node;
      const name = node.id.name;
      const parent = node.extends[0];
      
      return j.tsTypeAliasDeclaration(
        j.identifier(name),
        null,
        j.tsTypeReference(
          j.identifier(parent.expression.name),
          parent.typeParameters
        )
      );
    });
  return root.toSource();
};
module.exports = transformer;
EOF

# Step 4: 试运行
echo "=== 试运行(干跑模式)==="
npx jscodeshift -t refactor-interfaces.js --dry --print src/**/*.ts | head -100

# Step 5: 确认执行
read -p "确认执行? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
  npx jscodeshift -t refactor-interfaces.js src/**/*.ts
  
  # Step 6: 验证
  npm run type-check
  npm test
  
  # Step 7: 提交
  git add -A
  git commit -m "refactor: convert empty interfaces to type aliases"
fi

11.2 Import路径迁移剧本

PLAYBOOK
# 智能Import迁移完整流程

# 1. 创建映射配置
cat > import-mapping.json << 'EOF'
{
  "@old/components": "@new/components",
  "@old/utils": "@shared/utils", 
  "@old/types": "@types",
  "../../../components": "@/components",
  "../../../utils": "@/utils"
}
EOF

# 2. 分析当前导入
echo "=== 分析导入模式 ==="
rg -t ts -t tsx "^import.*from ['\"]" --no-heading |
  sed -E "s/.*from ['\"]([^'\"]+)['\"].*/\1/" |
  sort | uniq -c | sort -rn | head -20

# 3. 执行迁移
npx ts-node migrate-imports.ts

# 4. 验证
npm run build
npm test

11.3 React性能优化剧本

PLAYBOOK
# React性能优化全流程

# 1. 检测未优化组件
echo "=== 查找未使用memo的组件 ==="
rg -t tsx "export (default |)(function|const) \w+.*: (React.)?FC" |
while read -r line; do
  file=$(echo "$line" | cut -d: -f1)
  if ! grep -q "memo(" "$file"; then
    echo "$line"
  fi
done

# 2. 检测大型依赖数组
echo "=== 检测过大的依赖数组 ==="
rg -U "use(Effect|Memo|Callback)([^,]+,\s*\[[^]{100,}\])" -t tsx

# 3. 生成优化报告
npx ts-node analyze-performance.ts > performance-issues.json

# 4. 执行优化
echo "开始性能优化..."

12. 附录与参考

12.1 工具速查表

工具 安装命令 常用参数 示例
ripgrep brew install ripgrep -l 仅文件名
-C 上下文
-g glob模式
rg -t ts "pattern"
fd brew install fd -e 扩展名
-E 排除
-x 执行命令
fd -e ts -x sd "old" "new"
sd brew install sd -s 字符串模式
-f 固定字符串
sd "regex" "replace" file
comby brew install comby -i 原地替换
-d 目录
comby ":[x]" ":[x]!" .ts
semgrep pip install semgrep --autofix 自动修复
--json JSON输出
semgrep --config=auto

12.2 常见问题解答

Q: 如何处理Windows环境?

推荐方案优先级:

  1. WSL2 + Ubuntu(最佳兼容性)
  2. Git Bash + GNU工具链
  3. PowerShell + scoop/chocolatey安装的工具
  4. 原生PowerShell脚本(需要重写)
Q: 如何处理超大型仓库(10万+文件)?
  • 使用 --threads 参数启用多线程
  • 分批处理:fd -e ts | head -1000 | xargs ...
  • 使用稀疏检出:git sparse-checkout
  • 考虑分布式处理或云端构建
Q: 如何集成到现有CI/CD?

创建 .github/workflows/refactor-check.yml:

on:
  pull_request:
    paths: ['**/*.ts', '**/*.tsx']

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: npm ci
      - run: npm run refactor:check
      - run: npm run refactor:report

12.3 推荐阅读

© 2024 Vibe Coding with Claude v2.0 | 企业级代码库协作工程手册

本手册持续更新中,欢迎贡献最佳实践与改进建议

数据产品部
maurice