<!-- title: Claude Code CI/CD与GitHub Actions全实战 -->

# Claude Code CI/CD与GitHub Actions全实战：从PR自动审查到智能发布管线

## 概述

本教程面向希望在团队中落地Claude Code CI/CD自动化的一线开发者和DevOps工程师。你将学会：配置Anthropic官方 `claude-code-action`、编写PR自动审查与代码修复工作流、搭建Issue自动分类管线、实现CI失败自动诊断、构建多阶段智能发布流水线。学完后可直接将AI能力嵌入GitHub Actions，实现"每条PR都有AI审查官，每次构建失败都有AI排障员"。

**适用人群**：有GitHub Actions基础、日常使用Claude Code的开发者；团队技术负责人；DevOps工程师。

---

## 前置条件

| 项目 | 要求 |
|------|------|
| Claude Code CLI | v2.1+（`claude --version` 确认） |
| GitHub 账号 | 有仓库管理权限 |
| Anthropic API Key | 从 [console.anthropic.com](https://console.anthropic.com) 获取 |
| Git 基础 | 熟悉分支、PR、merge 操作 |
| YAML 语法 | 能读懂 GitHub Actions workflow |

---

## 第一章：理解 Claude Code × GitHub Actions 的架构

### 1.1 整体架构

Claude Code在CI/CD中的集成有两种路径：

- **官方Action（推荐）**：`anthropics/claude-code-action` — Anthropic维护的一键式GitHub Action，封装了认证、上下文获取、结果回写等全部逻辑
- **CLI直接调用**：在workflow中直接运行 `claude -p` 命令 — 适合需要精细控制的场景

```mermaid
flowchart TB
    subgraph GitHub
        PR[Pull Request / Issue]
        GA[GitHub Actions Runner]
        CC[claude-code-action]
        CLI[claude -p CLI]
    end

    subgraph Anthropic
        API[Anthropic API]
    end

    PR -->|触发事件| GA
    GA -->|方式一| CC
    GA -->|方式二| CLI
    CC -->|API调用| API
    CLI -->|API调用| API
    CC -->|审查评论/代码提交| PR
    CLI -->|标准输出| GA

    style CC fill:#e8f5e9,stroke:#2e7d32
    style CLI fill:#fff3e0,stroke:#ef6c00
```

### 1.2 核心能力矩阵

| 能力 | 官方Action | CLI模式 |
|------|:---:|:---:|
| PR代码审查 + 评论 | ✅ 内置 | ⚠️ 需手动实现 |
| 自动修复并提交代码 | ✅ 内置 | ⚠️ 需脚本封装 |
| Issue自动分类/回答 | ✅ 内置 | ⚠️ 需脚本封装 |
| 灵活自定义prompt | ✅ prompt参数 | ✅ 完全自由 |
| 限制可用工具 | ✅ allowedTools | ✅ --allowedTools |
| Token用量控制 | ✅ maxTokens | ✅ --max-turns |
| 私有仓库支持 | ✅ | ✅ |
| 结果解析 | ✅ 自动回写 | ❌ 需自行解析 |

**结论**：绝大多数场景用官方Action即可，只有极度定制化需求才需CLI模式。

---

## 第二章：安装与基础配置

### 2.1 安装官方Action

**方式一：GitHub Marketplace安装（推荐新手）**

1. 打开仓库 → Settings → Actions → General
2. 滚动到 "GitHub Actions" 部分，确认 Allow all actions
3. 在你的仓库中创建 `.github/workflows/claude-review.yml`

**方式二：直接编写Workflow文件（推荐）**

```yaml
# .github/workflows/claude-review.yml
name: Claude Code Review

on:
  pull_request:
    types: [opened, synchronize]
  issue_comment:
    types: [created]

jobs:
  claude-review:
    runs-on: ubuntu-latest
    permissions:
      contents: write          # 允许提交代码修复
      pull-requests: write     # 允许发表评论
      issues: write            # 允许回复Issue
      id-token: write          # OIDC认证

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0       # 获取完整历史，给Claude更多上下文

      - name: Claude Code Review
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Review this pull request. Focus on:
            1. Security vulnerabilities
            2. Performance issues
            3. Code style and best practices
            4. Potential bugs or edge cases
            Provide actionable suggestions.
```

### 2.2 配置API Key密钥

```bash
# 在本地终端执行（需要GitHub CLI）
gh secret set ANTHROPIC_API_KEY --repo your-org/your-repo
# 粘贴你的API Key后按回车

# 验证密钥已设置
gh secret list --repo your-org/your-repo
```

预期输出：
```
ANTHROPIC_API_KEY     Updated 2026-06-06
```

### 2.3 触发第一次审查

```bash
# 创建一个测试PR
git checkout -b test-claude-review
echo "// TODO: review this code" >> src/main.ts
git add . && git commit -m "test: trigger Claude review"
git push origin test-claude-review
gh pr create --title "Test: Claude Code Review" --body "Testing Claude Code Actions"
```

在PR中评论 `@claude` 即可触发审查。Claude会自动分析diff并发表评论。

**常见问题**：

| 问题 | 原因 | 解决 |
|------|------|------|
| Action不触发 | 未配置permissions | 确认 `permissions` 包含 write |
| 401 Unauthorized | API Key无效 | 检查secret名称和值 |
| 无评论产出 | prompt过于模糊 | 细化prompt指令 |
| Token超额 | 大型diff消耗过多 | 设置 `maxTokens` 限制 |

---

## 第三章：六大核心工作流实战

### 3.1 工作流一：PR自动审查 + 自动修复

这是最核心的场景 — Claude不仅能审查，还能直接提交修复代码。

```yaml
# .github/workflows/claude-pr-review.yml
name: Claude PR Review & Fix

on:
  pull_request:
    types: [opened, synchronize]
  issue_comment:
    types: [created]

jobs:
  review:
    if: |
      github.event_name == 'pull_request' ||
      (github.event_name == 'issue_comment' &&
       contains(github.event.comment.body, '@claude'))
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
      issues: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Claude Review
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            You are a senior code reviewer. Analyze this PR carefully:

            1. **Security**: Check for SQL injection, XSS, hardcoded secrets, insecure defaults
            2. **Correctness**: Logic errors, null pointer risks, race conditions
            3. **Performance**: N+1 queries, unnecessary re-renders, memory leaks
            4. **Style**: Naming conventions, code organization, DRY violations

            If you find fixable issues, implement the fixes directly.
            Always explain your reasoning in review comments.
          allowed_tools: "Bash(git*),Bash(npm*),Bash(npx*),Read,Write,Edit"
          max_tokens: 50000
```

**关键参数解析**：

- `allowed_tools`：限制Claude只读代码和使用git/npm，禁止访问网络或执行危险操作
- `max_tokens`：控制单次审查的Token上限，避免大PR导致超额
- `fetch-depth: 0`：获取完整git历史，让Claude理解变更的上下文

**预期行为**：Claude会逐文件审查diff，在有问题的地方发表行内评论，并可能直接提交修复commit。

### 3.2 工作流二：Issue自动分类与回答

让Claude自动处理新Issue的分类、标签分配和初步回答。

```yaml
# .github/workflows/claude-issue-triage.yml
name: Claude Issue Triage

on:
  issues:
    types: [opened, edited]
  issue_comment:
    types: [created]

jobs:
  triage:
    if: |
      github.event_name == 'issues' ||
      (github.event_name == 'issue_comment' &&
       contains(github.event.comment.body, '@claude'))
    runs-on: ubuntu-latest
    permissions:
      issues: write
      contents: read

    steps:
      - uses: actions/checkout@v4

      - name: Claude Triage
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Triage this GitHub issue:

            1. Classify the issue type: bug / feature / question / documentation
            2. Assign appropriate labels
            3. Estimate priority: critical / high / medium / low
            4. If it's a question, provide a helpful answer based on the codebase
            5. If it's a bug, try to identify the root cause file and function
            6. If it's a feature request, assess feasibility and suggest an approach
          allowed_tools: "Bash(git*),Read,Glob,Grep"
```

### 3.3 工作流三：CI失败自动诊断

当CI流水线失败时，Claude自动分析错误日志并提出修复建议。

```yaml
# .github/workflows/claude-ci-diagnosis.yml
name: Claude CI Diagnosis

on:
  workflow_run:
    workflows: ["CI", "Test", "Build"]
    types: [completed]
    branches: [main, develop]

jobs:
  diagnose:
    if: ${{ github.event.workflow_run.conclusion == 'failure' }}
    runs-on: ubuntu-latest
    permissions:
      contents: read
      issues: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4

      - name: Get Failed Run Info
        id: failed-run
        uses: actions/github-script@v7
        with:
          script: |
            const runId = context.payload.workflow_run.id;
            const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: runId
            });
            const failedJobs = jobs.jobs.filter(j => j.conclusion === 'failure');
            const logs = [];
            for (const job of failedJobs) {
              const { data } = await github.rest.actions.downloadJobLogs({
                owner: context.repo.owner,
                repo: context.repo.repo,
                job_id: job.id
              });
              logs.push({ name: job.name, log: data });
            }
            core.setOutput('logs', JSON.stringify(logs));
            core.setOutput('run_url', context.payload.workflow_run.html_url);

      - name: Claude Diagnosis
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            The CI pipeline just failed. Here are the failed job logs:

            ${{ steps.failed-run.outputs.logs }}

            Pipeline URL: ${{ steps.failed-run.outputs.run_url }}

            Please analyze:
            1. What is the root cause of the failure?
            2. Which file(s) and line(s) are likely responsible?
            3. What specific fix would you recommend?
            4. Is this a flaky test or a genuine failure?

            Be specific — reference file paths and line numbers.
          allowed_tools: "Read,Glob,Grep"
```

### 3.4 工作流四：安全扫描与依赖审计

```yaml
# .github/workflows/claude-security-scan.yml
name: Claude Security Scan

on:
  schedule:
    - cron: '0 2 * * 1'    # 每周一凌晨2点
  pull_request:
    paths:
      - 'package.json'
      - 'package-lock.json'
      - '**/requirements*.txt'
      - '**/Cargo.toml'
      - 'go.mod'

jobs:
  security-scan:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      issues: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4

      - name: Install Security Tools
        run: |
          npm install -g npm-audit-resolver 2>/dev/null || true
          pip install safety bandit 2>/dev/null || true

      - name: Run Automated Scans
        run: |
          echo "=== NPM Audit ===" > security-report.txt
          npm audit 2>/dev/null >> security-report.txt || true
          echo "=== Python Safety ===" >> security-report.txt
          safety check 2>/dev/null >> security-report.txt || true
          echo "=== Bandit Scan ===" >> security-report.txt
          bandit -r . -f txt 2>/dev/null >> security-report.txt || true

      - name: Claude Security Analysis
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Analyze the security scan results in security-report.txt.
            Also review the dependency files for known vulnerability patterns:

            1. Critical/High severity vulnerabilities - explain impact and fix
            2. Outdated dependencies with known CVEs
            3. Supply chain risks (unmaintained packages, typosquatting)
            4. Recommend specific version upgrades

            Create a GitHub issue with the findings if any critical issues exist.
          allowed_tools: "Read,Write,Bash(git*)"
```

### 3.5 工作流五：自动化文档生成

```yaml
# .github/workflows/claude-docs-gen.yml
name: Claude Docs Generation

on:
  push:
    branches: [main]
    paths:
      - 'src/**'
      - 'lib/**'

jobs:
  generate-docs:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Generate API Docs
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Review all changed files in this commit compared to the previous commit.
            For each changed public API:
            1. Update or create JSDoc/TSDoc comments
            2. Update the API documentation in docs/ directory
            3. Update the CHANGELOG.md with a new entry
            4. If README.md examples are affected, update them too

            Commit changes to a new branch 'docs/auto-update' and create a PR.
          allowed_tools: "Read,Write,Edit,Bash(git*),Bash(npm*)"
```

### 3.6 工作流六：定时代码质量巡检

```yaml
# .github/workflows/claude-quality-patrol.yml
name: Claude Quality Patrol

on:
  schedule:
    - cron: '30 3 * * 1-5'   # 工作日每天凌晨3:30
  workflow_dispatch:           # 支持手动触发

jobs:
  patrol:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      issues: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Quality Analysis
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Perform a weekly code quality patrol:

            1. **Dead Code**: Find unused exports, unreachable code, orphaned files
            2. **Complexity Hotspots**: Functions over 50 lines, deep nesting (>4 levels)
            3. **Duplication**: Similar code blocks that could be extracted
            4. **TODO Accumulation**: Count and categorize TODO/FIXME/HACK comments
            5. **Test Coverage Gaps**: Modules with tests/ vs modules without

            Output a structured report and create issues for the top 5 findings.
          allowed_tools: "Read,Glob,Grep,Bash(git*)"
```

---

## 第四章：高级配置与安全加固

### 4.1 多环境密钥管理

```yaml
# 为不同环境使用不同密钥
jobs:
  claude-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Determine API Key
        id: api-key
        run: |
          if [ "${{ github.event.pull_request.base.ref }}" == "main" ]; then
            echo "key=${{ secrets.ANTHROPIC_API_KEY_PROD }}" >> $GITHUB_OUTPUT
          else
            echo "key=${{ secrets.ANTHROPIC_API_KEY_DEV }}" >> $GITHUB_OUTPUT
          fi

      - name: Claude Review
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ steps.api-key.outputs.key }}
```

### 4.2 成本控制策略

```yaml
# 成本感知的审查 — 根据PR大小决定审查深度
jobs:
  check-size:
    runs-on: ubuntu-latest
    outputs:
      depth: ${{ steps.size.outputs.depth }}
    steps:
      - uses: actions/checkout@v4
      - id: size
        run: |
          LINES=$(git diff --stat origin/main...HEAD | tail -1 | awk '{print $4+$6}')
          if [ "$LINES" -gt 500 ]; then
            echo "depth=full" >> $GITHUB_OUTPUT
          elif [ "$LINES" -gt 100 ]; then
            echo "depth=standard" >> $GITHUB_OUTPUT
          else
            echo "depth=quick" >> $GITHUB_OUTPUT
          fi

  review:
    needs: check-size
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Claude Review (${{ needs.check-size.outputs.depth }})
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          max_tokens: ${{ needs.check-size.outputs.depth == 'full' && '100000' || needs.check-size.outputs.depth == 'standard' && '50000' || '20000' }}
          prompt: ${{ needs.check-size.outputs.depth == 'full' && 'Perform a comprehensive review covering security, performance, architecture, and style.' || 'Quick review for critical issues only.' }}
```

### 4.3 安全沙箱：限制Claude的能力边界

```yaml
# 最小权限原则 — 只允许读取和分析
- name: Claude Read-Only Review
  uses: anthropics/claude-code-action@v1
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    allowed_tools: "Read,Glob,Grep"    # 仅读取工具，无写入能力
    # 等价于CLI模式: claude -p "..." --allowedTools "Read,Glob,Grep"
```

**工具权限分级表**：

| 级别 | allowed_tools | 适用场景 |
|------|--------------|---------|
| 只读审查 | `Read,Glob,Grep` | PR审查、安全扫描 |
| 只读+分析 | `Read,Glob,Grep,Bash(npm*),Bash(python*)` | 性能分析、依赖审计 |
| 审查+修复 | `Read,Write,Edit,Bash(git*)` | 自动修复、文档更新 |
| 完全权限 | 不设置allowed_tools | 全自动模式（谨慎使用） |

### 4.4 使用CLAUDE.md指导CI中的Claude

在仓库根目录创建 `CLAUDE.md`，Action会自动读取作为项目上下文：

```markdown
# CLAUDE.md

## Project: E-Commerce API (Node.js/TypeScript)

### Architecture
- Monorepo with packages/api, packages/shared, packages/workers
- Express.js + PostgreSQL + Redis
- Testing: Vitest + Playwright E2E

### Code Review Standards
- All DB queries must use parameterized statements
- API endpoints must have input validation (zod schemas)
- Error handling must use the shared AppError class
- Tests required for all new endpoints

### CI Context
- Node.js 20 LTS
- Build: `npm run build`
- Test: `npm test`
- Lint: `npm run lint`
```

---

## 第五章：CLI模式 — 更精细的控制

当官方Action无法满足需求时，可以直接在workflow中调用 `claude -p`。

### 5.1 基础CLI调用

```yaml
# .github/workflows/claude-cli-mode.yml
name: Claude CLI Mode

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  custom-analysis:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Custom Analysis
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          # 获取PR的diff
          git diff origin/main...HEAD > pr-diff.txt

          # 使用claude -p非交互模式分析
          claude -p \
            --allowedTools "Read,Glob,Grep" \
            --max-turns 3 \
            "Analyze the diff in pr-diff.txt. Output a JSON with:
            { \"summary\": \"one-line summary\",
              \"risk_level\": \"low|medium|high\",
              \"findings\": [{\"file\": \"path\", \"line\": N, \"issue\": \"description\"}],
              \"suggested_action\": \"approve|request_changes|comment\" }" \
            > analysis-result.json

          # 解析结果并发表评论
          RISK=$(cat analysis-result.json | python3 -c "import sys,json; print(json.load(sys.stdin)['risk_level'])")
          echo "## 🤖 Claude Analysis Result" > comment.md
          echo "**Risk Level**: $RISK" >> comment.md
          cat analysis-result.json >> comment.md

          # 使用gh CLI发表评论
          gh pr comment ${{ github.event.pull_request.number }} --body-file comment.md
```

### 5.2 多步骤编排：分析→修复→验证

```yaml
# .github/workflows/claude-auto-fix.yml
name: Claude Auto-Fix Pipeline

on:
  issue_comment:
    types: [created]

jobs:
  auto-fix:
    if: contains(github.event.comment.body, '@claude fix')
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      # 阶段一：分析问题
      - name: Analyze
        id: analyze
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p \
            --max-turns 2 \
            --allowedTools "Read,Glob,Grep,Bash(git*)" \
            "Analyze the failing tests or the issue described in PR #${{ github.event.issue.number }}.
            Identify the root cause files. List them one per line." \
            > affected-files.txt

      # 阶段二：自动修复
      - name: Fix
        id: fix
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p \
            --max-turns 10 \
            --allowedTools "Read,Write,Edit,Bash(git*),Bash(npm*),Bash(npx*)" \
            "Based on the analysis, fix the issues in the following files:
            $(cat affected-files.txt)

            After fixing, run: npm test

            If tests pass, commit with message 'fix: auto-resolved by Claude'"

      # 阶段三：验证修复
      - name: Verify
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          npm test
          claude -p \
            --max-turns 1 \
            "Summarize what was changed and why. Keep it under 100 words." \
            > fix-summary.txt

      - name: Comment Result
        if: always()
        run: |
          if [ -f fix-summary.txt ]; then
            gh pr comment ${{ github.event.issue.number }} --body "## ✅ Auto-Fix Applied
          $(cat fix-summary.txt)"
          else
            gh pr comment ${{ github.event.issue.number }} --body "## ❌ Auto-Fix Failed
          Check the [workflow logs](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for details."
          fi
```

---

## 第六章：团队协作与共享配置

### 6.1 组织级共享工作流

大型团队可以将Claude Code工作流集中管理，各仓库引用：

```yaml
# .github/workflows/claude-review.yml （在仓库中）
jobs:
  review:
    uses: your-org/.github/.github/workflows/claude-review.yml@main
    secrets: inherit
```

组织级工作流模板（放在 `.github` 仓库）：

```yaml
# your-org/.github/.github/workflows/claude-review.yml
name: Reusable Claude Review

on:
  workflow_call:
    inputs:
      review_depth:
        description: 'Review depth: quick, standard, full'
        type: string
        default: 'standard'
      allowed_tools:
        description: 'Allowed tools for Claude'
        type: string
        default: 'Read,Glob,Grep,Bash(git*)'

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Claude Code Review
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            ${{ inputs.review_depth == 'full' && 'Perform comprehensive code review...' || 'Quick review for critical issues...' }}
          allowed_tools: ${{ inputs.allowed_tools }}
```

### 6.2 项目级CLAUDE.md模板

```markdown
# CLAUDE.md

## Tech Stack
- **Language**: TypeScript 5.x (strict mode)
- **Framework**: Next.js 15 with App Router
- **Database**: PostgreSQL 16 with Prisma ORM
- **Testing**: Vitest + Playwright
- **CI**: GitHub Actions

## Review Checklist (for CI mode)
- [ ] No `any` types in production code
- [ ] All API routes have error boundaries
- [ ] Database queries use Prisma (no raw SQL)
- [ ] Components follow Server/Client component boundary rules
- [ ] New features include E2E tests

## Forbidden Patterns
- Never use `eval()` or `new Function()`
- Never commit `console.log` in production code
- Never hardcode API URLs — use environment variables
- Never bypass TypeScript checks with `@ts-ignore`

## Project-Specific Context
- `src/app/` — Next.js App Router pages
- `src/components/` — React components (Server by default)
- `src/lib/` — Shared utilities and business logic
- `prisma/` — Database schema and migrations
```

---

## 第七章：完整实战案例 — 智能发布管线

以下是一个端到端的智能发布管线，覆盖"PR审查→测试→安全扫描→版本号更新→Changelog→发布"全流程。

```yaml
# .github/workflows/smart-release.yml
name: Smart Release Pipeline

on:
  pull_request:
    types: [closed]
    branches: [main]

jobs:
  # 阶段一：判断是否需要发布
  check-release:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    outputs:
      should_release: ${{ steps.check.outputs.release }}
      change_level: ${{ steps.check.outputs.level }}
    steps:
      - uses: actions/checkout@v4
      - id: check
        run: |
          TITLE="${{ github.event.pull_request.title }}"
          if echo "$TITLE" | grep -qi "breaking\|major"; then
            echo "level=major" >> $GITHUB_OUTPUT
            echo "release=true" >> $GITHUB_OUTPUT
          elif echo "$TITLE" | grep -qi "feat\|feature"; then
            echo "level=minor" >> $GITHUB_OUTPUT
            echo "release=true" >> $GITHUB_OUTPUT
          elif echo "$TITLE" | grep -qi "fix\|patch\|hotfix"; then
            echo "level=patch" >> $GITHUB_OUTPUT
            echo "release=true" >> $GITHUB_OUTPUT
          else
            echo "release=false" >> $GITHUB_OUTPUT
          fi

  # 阶段二：Claude生成Changelog
  generate-changelog:
    needs: check-release
    if: needs.check-release.outputs.should_release == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Claude Generate Changelog
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Generate a changelog entry for version bump (level: ${{ needs.check-release.outputs.change_level }}).

            1. Read the git log since the last tag
            2. Categorize changes: Features, Bug Fixes, Breaking Changes, Improvements
            3. Update CHANGELOG.md with the new entry at the top
            4. Bump version in package.json accordingly
            5. Commit and tag with the new version
          allowed_tools: "Read,Write,Edit,Bash(git*)"

  # 阶段三：安全扫描
  security-scan:
    needs: generate-changelog
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm audit --audit-level=high
      - name: Claude Security Review
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Review the dependency tree for security vulnerabilities. Flag any critical issues."
          allowed_tools: "Read,Bash(npm*)"

  # 阶段四：创建GitHub Release
  create-release:
    needs: [generate-changelog, security-scan]
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - name: Extract Version
        id: version
        run: echo "v=$(node -p 'require(\"./package.json\").version')" >> $GITHUB_OUTPUT

      - name: Create Release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: v${{ steps.version.outputs.v }}
          release_name: Release v${{ steps.version.outputs.v }}
          body_path: CHANGELOG.md
```

### 完整管线流程图

```mermaid
flowchart LR
    PR[PR Merged to main] --> Check{判断变更级别}
    Check -->|feat| Minor[Minor Release]
    Check -->|fix| Patch[Patch Release]
    Check -->|breaking| Major[Major Release]
    Check -->|chore/docs| Skip[跳过发布]

    Minor --> CL[生成Changelog]
    Patch --> CL
    Major --> CL

    CL --> Sec[安全扫描]
    Sec -->|通过| Rel[创建GitHub Release]
    Sec -->|失败| Alert[通知团队]

    style PR fill:#e3f2fd,stroke:#1565c0
    style Rel fill:#e8f5e9,stroke:#2e7d32
    style Alert fill:#ffebee,stroke:#c62828
    style Skip fill:#f5f5f5,stroke:#9e9e9e
```

---

## 第八章：监控、调优与排错

### 8.1 监控Token消耗

```yaml
# 在每个Claude步骤后记录Token使用
- name: Log Token Usage
  if: always()
  run: |
    echo "## Token Usage Report" >> $GITHUB_STEP_SUMMARY
    echo "Run ID: ${{ github.run_id }}" >> $GITHUB_STEP_SUMMARY
    echo "Trigger: ${{ github.event_name }}" >> $GITHUB_STEP_SUMMARY
    echo "Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> $GITHUB_STEP_SUMMARY
```

### 8.2 常见错误排查手册

| 错误现象 | 诊断命令 | 解决方案 |
|---------|---------|---------|
| Action不触发 | 检查workflow文件的 `on` 事件配置 | 确认触发条件匹配 |
| `@claude` 无响应 | 查看 Actions tab 的workflow run | 确认 permissions 设置 |
| Token超限 | 检查Anthropic控制台用量 | 降低 `max_tokens`，减小审查范围 |
| Claude回复与代码无关 | 检查 `fetch-depth` 是否为0 | 设置 `fetch-depth: 0` |
| 修复commit冲突 | 检查是否与最新main同步 | 使用 `rebase` 或在prompt中说明 |
| 中文乱码 | 检查workflow编码设置 | 添加 `LANG: en_US.UTF-8` env |

### 8.3 调优清单

```
□ PR小于100行 → max_tokens: 20000（快速审查）
□ PR 100-500行 → max_tokens: 50000（标准审查）
□ PR大于500行 → max_tokens: 100000 + 分批审查
□ 安全关键仓库 → allowed_tools 仅 Read,Glob,Grep
□ 文档更新仓库 → 允许 Write,Edit 但限制 Bash
□ 成本敏感 → 设置 max-turns: 3 防止多轮对话
□ 私有仓库 → 确保 secrets 继承正确
□ 大型团队 → 使用组织级共享工作流模板
```

---

## 第九章：与本地工作流的衔接

CI中的Claude和本地终端的Claude Code可以无缝协作。

### 9.1 本地推代码 → CI审查 → 本地修复

```bash
# 本地开发完成
git add . && git commit -m "feat: add payment module"
git push origin feature/payment

# CI自动触发Claude审查，你可以在PR页面看到评论

# 本地查看CI结果
gh pr checks  # 查看所有check状态
gh pr view --comments  # 查看Claude的审查评论

# 根据Claude的反馈在本地修复
claude  # 进入交互模式
> 根据PR审查意见修复 src/payment/processor.ts 中的安全问题

# 修复后推送
git add . && git commit -m "fix: address security review feedback"
git push origin feature/payment
# CI会再次触发审查
```

### 9.2 本地预审查 — 在推送前让Claude检查

```bash
# 利用git pre-push hook在推送前触发本地Claude审查
cat > .git/hooks/pre-push << 'EOF'
#!/bin/bash
# 只在main分支保护时检查
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" = "main" ]; then
  echo "⚠️ 直接推送到main分支需要Claude审查"
  claude -p "Review the staged changes for critical issues only. 
  Output APPROVE or REJECT with reason." \
    --max-turns 1 \
    --allowedTools "Read,Glob,Grep"
fi
EOF
chmod +x .git/hooks/pre-push
```

---

## 延伸阅读

- [Anthropic官方：Claude Code GitHub Actions文档](https://code.claude.com/docs/en/github-actions) — 官方Action的完整配置参考
- [anthropics/claude-code-action GitHub仓库](https://github.com/anthropics/claude-code-action) — 源码、示例和Migration Guide
- [Claude Code CI & Automation Best Practices](https://muhammadusmangm.github.io/claude-code-best-practices/guides/ci-and-automation/) — 社区维护的CI/CD最佳实践指南
- [Streamlined CI/CD Pipelines Using Claude Code & GitHub Actions](https://medium.com/@itsmybestview/streamlined-ci-cd-pipelines-using-claude-code-github-actions-74be17e51499) — 实战案例分析

---

## 训练营适用性评估

| 维度 | 评估 |
|------|------|
| **适合训练营类型** | DevOps工程师训练营、团队工程效能提升营、AI辅助开发训练营 |
| **教学时长** | 3-4小时（含实操） |
| **难度等级** | ⭐⭐⭐（中级，需要GitHub Actions基础） |
| **实验环境要求** | 每人一个GitHub仓库 + Anthropic API Key |
| **最佳分组方式** | 2-3人一组，每组一个项目仓库 |
| **前置课程** | Claude Code入门篇 + 基础CI/CD知识 |
| **考核方式** | 成功配置一个自动PR审查工作流并验证触发 |

---

## 参考来源

1. [Claude Code GitHub Actions — 官方文档](https://code.claude.com/docs/en/github-actions) — Anthropic官方GitHub Actions集成文档，涵盖安装、配置和触发方式
2. [anthropics/claude-code-action — GitHub](https://github.com/anthropics/claude-code-action) — 官方Action源码仓库，7.9k stars，含完整示例和Migration Guide
3. [CI & Automation — Claude Code Best Practices](https://muhammadusmangm.github.io/claude-code-best-practices/guides/ci-and-automation/) — 社区维护的CI自动化最佳实践，涵盖headless模式和安全策略
4. [Claude Code GitHub Actions: Automate Code Review, Testing & CI/CD](https://skillsplayground.com/guides/claude-code-github-actions/) — 2026年2月更新的完整配置指南
5. [CI/CD Pipeline Design with Claude Code: GitHub Actions from Zero to Deploy](https://dev.to/myougatheaxo/cicd-pipeline-design-with-claude-code-github-actions-from-zero-to-deploy-2b14) — 从零搭建CI/CD管线的实战教程

> [!tip] 51学通信知识星球
> **星主：爱卫生**（微信：gprshome201101）——公众号「51学通信」创办者，19 年通信行业运维与讲师经验，著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书（各大电商平台有售）。
> **星球定位**：深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域，主打运维岗位与信令分析。
> **当前规模**：5200 篇主题 / 990 个回答，198 元/年。
> **加入福利**：加入星球后请加爱卫生微信，拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题，另有群内分享。
> **AI 加持**：51学通信知识星球已作为 skill 接入 WorkBuddy，使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例，做总结、找文档和 PPT 等场景全覆盖。

![51学通信知识星球海报-扫码加入](https://wiki.500nian.com/images/zhixingqiu_qrcode.png)
