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

# Claude Code CI/CD流水线集成：从GitHub Actions到Agent SDK全实战

## 概述

本教程面向希望将Claude Code集成到CI/CD流水线中的开发者和DevOps工程师。你将学会使用官方 `anthropics/claude-code-action@v1` 构建自动化代码审查、Issue分类、定时维护等GitHub Actions工作流，掌握 `--print` 无头模式的脚本化调用，并通过Agent SDK实现程序化Agent编排。**适用人群**：有GitHub Actions基础的中高级开发者，团队技术负责人。

## 前置条件

| 要求 | 说明 |
|------|------|
| GitHub仓库 | 一个你有管理权限的仓库 |
| Anthropic API Key | 在[console.anthropic.com](https://console.anthropic.com)获取 |
| Claude Code CLI | `npm install -g @anthropic-ai/claude-code` |
| Node.js 18+ | Agent SDK运行环境 |
| GitHub Actions基础 | 了解workflow文件结构、secrets配置 |

---

## 第一部分：三分钟快速启动——`/install-github-app`

最简单的接入方式是通过Claude Code终端内建的安装命令。

```bash
# 在项目根目录打开Claude Code
claude

# 在交互界面中执行
/install-github-app
```

该命令会引导你完成三个步骤：
1. **注册GitHub App** — 跳转到Anthropic的GitHub App授权页面
2. **安装App到仓库** — 选择你要授权的仓库
3. **自动配置Secret** — 将API Key写入仓库Secrets

> **限制**：此快速启动方式仅适用于Anthropic直接API用户。如果你使用AWS Bedrock或Google Vertex AI，需要按[Cloud Providers文档](https://github.com/anthropics/claude-code-action/blob/main/docs/cloud-providers.md)手动配置。

---

## 第二部分：GitHub Actions工作流深度配置

### 2.1 核心架构理解

```mermaid
flowchart TB
    subgraph 触发源
        PR[Pull Request]
        Comment[PR/Issue评论]
        Issue[Issue事件]
        Schedule[定时任务]
        Manual[手动触发]
    end

    subgraph GitHub Actions
        Checkout[检出代码]
        ClaudeAction[claude-code-action@v1]
        subgraph 模式自动检测
            Interactive[交互模式<br/>无prompt → 监听@claude]
            Agent[Agent模式<br/>有prompt → 立即执行]
        end
        StructuredOut[结构化输出]
    end

    subgraph 后续动作
        PostComment[发布PR评论]
        InlineReview[行内代码审查]
        CreateIssue[创建Issue]
        RetryCI[重试CI流水线]
    end

    PR & Comment & Issue & Schedule & Manual --> Checkout --> ClaudeAction
    ClaudeAction --> Interactive & Agent
    Interactive & Agent --> StructuredOut
    StructuredOut --> PostComment & InlineReview & CreateIssue & RetryCI
```

### 2.2 模式自动检测机制

v1版本引入了**智能模式检测**——不再需要手动指定 `mode` 参数：

| 场景 | 检测条件 | 运行模式 |
|------|----------|----------|
| 有人评论 `@claude` | 无 `prompt` 输入 | **交互模式** — 创建跟踪评论，逐步更新进度 |
| 配置了 `prompt` | 有 `prompt` 输入 | **Agent模式** — 立即执行，不创建跟踪评论 |
| PR审查/Issue分配 | 事件触发 + @claude | **交互模式** |
| 定时任务 | `schedule` 事件 + `prompt` | **Agent模式** |

### 2.3 最小可用的自动代码审查工作流

创建 `.github/workflows/claude-review.yml`：

```yaml
name: Claude Auto Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 1

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            REPO: ${{ github.repository }}
            PR NUMBER: ${{ github.event.pull_request.number }}

            请审查此Pull Request，重点关注：
            - 代码质量与最佳实践
            - 潜在Bug或逻辑问题
            - 安全隐患
            - 性能考量

            注意：PR分支已在当前工作目录中检出。

            使用 `gh pr comment` 发布总体反馈。
            使用 `mcp__github_inline_comment__create_inline_comment`（设置 confirmed: true）标注具体代码问题。
            只发布GitHub评论，不要将审查文本作为消息提交。

          claude_args: |
            --allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*)"
```

**预期结果**：
- PR创建或更新时，Claude自动开始审查
- 总体反馈以PR评论形式发布
- 具体代码问题以行内注释形式标注

**常见问题**：

| 问题 | 原因 | 解决方案 |
|------|------|----------|
| Action未触发 | 权限不足 | 确认 `pull-requests: write` 权限已设置 |
| 评论未发布 | `allowedTools` 缺少工具 | 添加 `Bash(gh pr comment:*)` 到允许列表 |
| 审查过于笼统 | prompt不够具体 | 在prompt中加入具体检查清单 |

### 2.4 关键参数详解

#### 认证参数（三选一）

```yaml
# 方式1：Anthropic API Key（最常用）
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

# 方式2：OAuth Token
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}

# 方式3：Workload Identity Federation（企业推荐）
anthropic_federation_rule_id: ${{ secrets.FEDERATION_RULE_ID }}
anthropic_organization_id: ${{ secrets.ORG_ID }}
# 无需静态API Key，通过GitHub OIDC令牌认证
```

#### `claude_args`——万能配置通道

v1版本将大部分配置统一到 `claude_args` 参数中，直接透传给Claude CLI：

```yaml
claude_args: |
  --max-turns 15                          # 最大对话轮次
  --model claude-4-0-sonnet-20250805      # 指定模型
  --allowedTools Edit,Read,Write,Bash     # 允许的工具
  --disallowedTools WebSearch             # 禁止的工具
  --system-prompt "你是安全审计专家"        # 自定义系统提示
  --mcp-config '{"mcpServers":{...}}'     # MCP服务器配置
  --json-schema '{...}'                   # 结构化输出Schema
```

#### v0.x → v1 迁移对照表

| v0.x参数 | v1替代方案 |
|-----------|-----------|
| `mode: "tag"` | 删除，自动检测 |
| `direct_prompt` | `prompt` |
| `custom_instructions` | `claude_args` 中 `--system-prompt` |
| `max_turns: "10"` | `claude_args: "--max-turns 10"` |
| `model: "claude-..."` | `claude_args: "--model claude-..."` |
| `allowed_tools` | `claude_args: "--allowedTools ..."` |
| `mcp_config` | `claude_args: "--mcp-config '{...}'"` |

---

## 第三部分：六大实战场景

### 场景一：安全关键路径审查

仅当涉及认证、API、安全配置文件的变更时触发：

```yaml
name: Security Path Review
on:
  pull_request:
    types: [opened, synchronize]
    paths:
      - "src/auth/**"
      - "src/api/**"
      - "config/security.yml"
      - "**/middleware/**"

jobs:
  security-review:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 1

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            REPO: ${{ github.repository }}
            PR NUMBER: ${{ github.event.pull_request.number }}

            此PR修改了认证或API关键文件。请进行安全专项审查：
            - 认证/授权流程漏洞
            - 输入验证与过滤
            - SQL注入或XSS风险
            - API安全最佳实践
            - 敏感数据泄露检查
          claude_args: |
            --allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*)"
```

### 场景二：外部贡献者专属审查

对首次贡献者自动进行更详细的审查：

```yaml
name: External Contributor Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  external-review:
    if: github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
      id-token: write
    steps:
      - uses: actions/checkout@v6

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            REPO: ${{ github.repository }}
            PR NUMBER: ${{ github.event.pull_request.number }}
            CONTRIBUTOR: ${{ github.event.pull_request.user.login }}

            这是来自 @${{ github.event.pull_request.user.login }} 的首次贡献。

            请提供全面的审查，重点关注：
            - 项目编码规范合规性
            - 测试覆盖（单元和集成）
            - 新功能文档
            - 潜在破坏性变更
            - License头部要求

            保持友好但严格的审查态度。使用行内评论提供代码具体反馈。
          claude_args: |
            --allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*),Bash(gh pr view:*)"
```

### 场景三：Issue自动分类与标记

新Issue创建时自动分类并添加标签：

```yaml
name: Issue Auto Triage
on:
  issues:
    types: [opened]

jobs:
  triage:
    runs-on: ubuntu-latest
    permissions:
      issues: write
      id-token: write
    steps:
      - uses: actions/checkout@v6

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            REPO: ${{ github.repository }}
            ISSUE NUMBER: ${{ github.event.issue.number }}

            分析此Issue并执行以下操作：
            1. 判断Issue类型（bug/feature/question/docs）
            2. 评估优先级（critical/high/medium/low）
            3. 添加合适的标签
            4. 如果是Bug，添加对应的组件标签
            5. 发布一条欢迎评论，总结Issue内容

            使用 `gh issue edit` 添加标签，使用 `gh issue comment` 发布评论。
          claude_args: |
            --allowedTools "Bash(gh issue edit:*),Bash(gh issue comment:*),Bash(gh label:*)"
```

### 场景四：结构化输出——CI失败智能分析

Claude分析CI日志并返回结构化JSON，后续步骤根据结果自动决策：

```yaml
name: CI Failure Analysis
on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]
    branches: [main]

jobs:
  analyze:
    if: ${{ github.event.workflow_run.conclusion == 'failure' }}
    runs-on: ubuntu-latest
    permissions:
      contents: read
      issues: write
      actions: read
    steps:
      - uses: actions/checkout@v6

      - name: Analyze with Claude
        id: analyze
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            CI流水线在 ${{ github.repository }} 的main分支上失败了。
            分析失败日志，判断是否为flaky test（不稳定测试）。

            返回JSON格式：
            - is_flaky: boolean（是否为不稳定测试）
            - confidence: 0-1（置信度）
            - summary: string（失败摘要）
            - suggested_fix: string（建议修复方案）
          claude_args: |
            --allowedTools "Bash(gh run view:*),Bash(gh run log:*),Read"
            --json-schema '{"type":"object","properties":{"is_flaky":{"type":"boolean"},"confidence":{"type":"number"},"summary":{"type":"string"},"suggested_fix":{"type":"string"}},"required":["is_flaky","confidence","summary"]}'

      - name: Auto-retry if flaky
        if: fromJSON(steps.analyze.outputs.structured_output).is_flaky == true
        run: |
          echo "检测到不稳定测试，自动重试CI..."
          gh workflow run CI --ref main
```

### 场景五：定时仓库健康巡检

每周日自动扫描仓库健康状况：

```yaml
name: Weekly Maintenance
on:
  schedule:
    - cron: "0 2 * * 0"   # 每周日凌晨2点
  workflow_dispatch:        # 支持手动触发

jobs:
  maintenance:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      issues: write
      pull-requests: write
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            REPO: ${{ github.repository }}

            执行每周仓库健康巡检：

            1. 检查 package.json 中的过时依赖
            2. 运行 npm audit 扫描安全漏洞
            3. 审查超过90天未处理的开放Issue
            4. 检查最近提交中的 TODO 注释
            5. 验证 README.md 中的示例是否仍然有效
            6. 检查 CHANGELOG.md 是否需要更新

            创建一个汇总Issue报告所有发现。
            如果发现严重安全问题，也在相关开放PR中评论。
          claude_args: |
            --allowedTools "Read,Bash(npm:*),Bash(gh issue:*),Bash(gh pr:*),Bash(git log:*)"
```

### 场景六：自定义团队审查清单

将团队审查标准编码为prompt：

```yaml
name: Team Checklist Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  checklist:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
      id-token: write
    steps:
      - uses: actions/checkout@v6

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          track_progress: true    # 启用进度跟踪评论
          prompt: |
            REPO: ${{ github.repository }}
            PR NUMBER: ${{ github.event.pull_request.number }}

            按照团队检查清单审查此PR：

            ## 代码质量
            - [ ] 遵循代码风格指南
            - [ ] 无注释掉的代码
            - [ ] 有意义的变量命名
            - [ ] DRY原则

            ## 测试
            - [ ] 新函数有单元测试
            - [ ] 新端点有集成测试
            - [ ] 边界情况覆盖
            - [ ] 测试覆盖率 > 80%

            ## 文档
            - [ ] README已更新
            - [ ] API文档已更新
            - [ ] 复杂逻辑有行内注释

            ## 安全
            - [ ] 无硬编码凭据
            - [ ] 输入验证已实现
            - [ ] 无日志中的敏感数据

            对每项检查是否满足，发布带结果的汇总评论。
          claude_args: |
            --allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*)"
```

---

## 第四部分：`--print` 无头模式与脚本化调用

### 4.1 无头模式基础

当不需要GitHub Actions的完整集成时，可以直接在脚本中使用Claude Code的 `--print` 模式：

```bash
# 基本用法——输出到终端
claude -p "解释这个函数的作用"

# 管道输入——将文件内容传给Claude
cat src/auth.ts | claude -p "审查这段代码的安全问题"

# JSON输出格式
claude -p --output-format json "分析项目结构"

# 流式JSON输出（适合长时间任务）
claude -p --output-format stream-json "重构这个模块"
```

### 4.2 批量文件处理脚本

```bash
#!/bin/bash
# batch-review.sh — 批量审查所有待审查的PR

REPO="myorg/myproject"
PRS=$(gh pr list --repo "$REPO" --state open --json number --jq '.[].number')

for PR_NUM in $PRS; do
  echo "=== 审查 PR #$PR_NUM ==="

  # 获取PR diff
  DIFF=$(gh pr diff "$PR_NUM" --repo "$REPO")

  # 让Claude审查并生成评论
  REVIEW=$(echo "$DIFF" | claude -p --output-format text \
    "你是一名代码审查专家。审查以下diff，指出问题并给出建议。
     只输出审查意见，不要其他内容。用中文回复。")

  # 发布评论到PR
  echo "$REVIEW" | gh pr comment "$PR_NUM" --repo "$REPO" --body-file -

  echo "--- PR #$PR_NUM 审查完成 ---"
done

echo "全部完成！共审查 $(echo $PRS | wc -w) 个PR"
```

### 4.3 CI失败自动修复流水线

```bash
#!/bin/bash
# auto-fix-ci.sh — CI失败时自动尝试修复

set -e

# 1. 获取CI失败日志
LOGS=$(gh run view --log 2>/dev/null || echo "无法获取日志")

# 2. 让Claude诊断并修复
claude -p --output-format json \
  "CI失败了。以下是日志：
   $LOGS

   请分析失败原因，返回JSON：
   {\"fixable\": boolean, \"files_to_edit\": [...], \"description\": \"...\"}
  " > /tmp/diagnosis.json

FIXABLE=$(cat /tmp/diagnosis.json | jq -r '.fixable')

if [ "$FIXABLE" = "true" ]; then
  echo "Claude认为可以自动修复，开始修复流程..."

  # 3. 让Claude实际执行修复
  claude -p --allowedTools "Edit,Read,Bash(npm test:*)" \
    "根据 /tmp/diagnosis.json 中的分析修复CI失败。
     修复后运行测试验证。"

  echo "修复完成，提交变更..."
  git add -A
  git commit -m "fix: 自动修复CI失败（Claude Code生成）"
  git push
else
  echo "Claude认为无法自动修复，需要人工介入"
  cat /tmp/diagnosis.json | jq '.description'
fi
```

### 4.4 输出格式与管道组合

```text
flowchart LR
    Input[输入源] --> Claude[Claude Code --print]

    subgraph 输入方式
        File[文件管道<br/>cat file | claude -p]
        Arg[命令行参数<br/>claude -p 'prompt']
        Stdin[标准输入<br/>echo text | claude -p]
    end

    subgraph 输出格式
        Text[text — 纯文本]
        JSON[json — 结构化JSON]
        Stream[stream-json — 流式JSON]
    end

    Claude --> Text --> Tools1[管道到其他CLI工具]
    Claude --> JSON --> Tools2[jq解析/程序处理]
    Claude --> Stream --> Tools3[实时处理/进度跟踪]
```

```bash
# 生成结构化输出供后续处理
claude -p --output-format json \
  "列出src/目录下所有需要重构的文件，返回JSON数组" \
  | jq -r '.[].file' \
  | xargs -I {} claude -p "重构文件 {} 以提高可读性"

# 多步骤管道：分析 → 生成 → 验证
claude -p "分析测试覆盖率报告" < coverage/lcov.info \
  | claude -p "根据分析结果生成测试用例" \
  | claude -p "验证生成的测试是否合理，返回最终版本"
```

---

## 第五部分：Agent SDK——程序化构建AI Agent

### 5.1 SDK概述

Claude Agent SDK（前身Claude Code SDK）将Claude Code的完整能力暴露为TypeScript/Python API：

```bash
# 安装TypeScript SDK
npm install @anthropic-ai/claude-agent-sdk

# 或Python SDK
pip install claude-agent-sdk
```

### 5.2 TypeScript实战：自动化代码审查Agent

```typescript
// auto-reviewer.ts
import { Agent } from "@anthropic-ai/claude-agent-sdk";

async function reviewPullRequest(repo: string, prNumber: number) {
  const agent = new Agent({
    apiKey: process.env.ANTHROPIC_API_KEY,
    model: "claude-4-0-sonnet-20250805",
    maxTurns: 15,
    allowedTools: ["Read", "Bash"],
  });

  // 获取PR diff
  const { stdout: diff } = await agent.run(
    `Run: gh pr diff ${prNumber} --repo ${repo}`,
  );

  // 执行审查
  const result = await agent.run(
    `你是一名高级代码审查员。审查以下Pull Request变更：

    仓库: ${repo}
    PR编号: ${prNumber}
    
    Diff内容:
    ${diff}
    
    请提供：
    1. 总体评价（1-10分）
    2. 具体问题列表（含文件名和行号）
    3. 改进建议
    4. 安全风险提示`
  );

  // 发布审查评论
  await agent.run(
    `使用 gh pr comment ${prNumber} --repo ${repo} --body "${result.replace(/"/g, '\\"')}" 
     发布以上审查结果作为PR评论。`
  );

  console.log(`PR #${prNumber} 审查完成`);
  return result;
}

// 批量审查
async function batchReview(repo: string) {
  const agent = new Agent({
    apiKey: process.env.ANTHROPIC_API_KEY,
    maxTurns: 3,
  });

  const { stdout } = await agent.run(
    `Run: gh pr list --repo ${repo} --state open --json number --jq '.[].number'`
  );

  const prNumbers = stdout.trim().split("\n").map(Number);

  for (const num of prNumbers) {
    try {
      await reviewPullRequest(repo, num);
    } catch (error) {
      console.error(`PR #${num} 审查失败:`, error);
    }
  }
}

batchReview("myorg/myproject");
```

### 5.3 Python实战：结构化输出的CI诊断Agent

```python
# ci_diagnostic_agent.py
import json
import os
from claude_agent_sdk import Agent

def diagnose_ci_failure(run_id: str, repo: str) -> dict:
    """诊断CI失败并返回结构化结果"""
    
    agent = Agent(
        api_key=os.environ["ANTHROPIC_API_KEY"],
        model="claude-4-0-sonnet-20250805",
        max_turns=10,
        allowed_tools=["Read", "Bash"],
    )
    
    # 获取CI日志
    agent.run(f"获取CI运行日志: gh run view {run_id} --repo {repo} --log")
    
    # 结构化分析
    result = agent.run(
        prompt="分析CI失败日志，返回JSON格式的诊断结果",
        json_schema={
            "type": "object",
            "properties": {
                "root_cause": {"type": "string"},
                "is_flaky": {"type": "boolean"},
                "confidence": {"type": "number"},
                "affected_files": {
                    "type": "array",
                    "items": {"type": "string"}
                },
                "suggested_fix": {"type": "string"},
                "severity": {
                    "type": "string",
                    "enum": ["critical", "high", "medium", "low"]
                }
            },
            "required": [
                "root_cause", "is_flaky", "confidence",
                "suggested_fix", "severity"
            ]
        }
    )
    
    return json.loads(result)


# 批量处理所有失败的CI运行
def process_all_failures(repo: str):
    agent = Agent(api_key=os.environ["ANTHROPIC_API_KEY"])
    
    # 获取最近失败的工作流运行
    runs = agent.run(
        f"列出最近10次失败的CI运行: gh run list --repo {repo} "
        f"--status failure --limit 10 --json databaseId --jq '.[].databaseId'"
    )
    
    for run_id in runs.strip().split("\n"):
        diagnosis = diagnose_ci_failure(run_id, repo)
        
        if diagnosis["is_flaky"] and diagnosis["confidence"] > 0.8:
            print(f"⚠️ Run {run_id}: 不稳定测试（置信度 {diagnosis['confidence']}）")
            print(f"   建议: {diagnosis['suggested_fix']}")
        else:
            print(f"🔴 Run {run_id}: 真实失败")
            print(f"   根因: {diagnosis['root_cause']}")
            print(f"   严重度: {diagnosis['severity']}")


if __name__ == "__main__":
    process_all_failures("myorg/myproject")
```

---

## 第六部分：安全与最佳实践

### 6.1 安全配置清单

```mermaid
flowchart TB
    subgraph 认证安全
        APIKey[API Key存为Secret<br/>不要硬编码]
        OIDC[优先使用OIDC<br/>Workload Identity Federation]
        Scope[最小权限原则<br/>只授予必需权限]
    end

    subgraph 工具控制
        Allow[白名单工具<br/>--allowedTools]
        Disallow[黑名单工具<br/>--disallowedTools]
        MaxTurns[限制轮次<br/>--max-turns]
    end

    subgraph 输出安全
        NoSecret[结构化输出中<br/>排除敏感信息]
        Sign[启用提交签名<br/>use_commit_signing]
        Review[敏感操作<br/>人工review]
    end

    认证安全 & 工具控制 & 输出安全
```

### 6.2 权限最小化矩阵

| 场景 | 必需权限 | 推荐工具白名单 |
|------|----------|---------------|
| PR代码审查 | `contents: read`, `pull-requests: write` | `mcp__github_inline_comment__create_inline_comment, Bash(gh pr comment:*)` |
| Issue分类 | `issues: write` | `Bash(gh issue edit:*)`, `Bash(gh issue comment:*)` |
| 自动修复 | `contents: write`, `pull-requests: write` | `Edit, Read, Write, Bash(npm test:*)` |
| 定时巡检 | `contents: write`, `issues: write` | `Read, Bash(npm:*)`, `Bash(gh issue:*)` |

### 6.3 成本控制策略

```yaml
# 策略1：限制对话轮次
claude_args: |
  --max-turns 10

# 策略2：使用轻量模型做初步分析
claude_args: |
  --model claude-4-0-sonnet-20250805

# 策略3：路径过滤——只处理关键文件变更
on:
  pull_request:
    paths:
      - "src/**"
      - "!**/*.test.ts"    # 排除测试文件

# 策略4：条件触发——只对特定分支
on:
  pull_request:
    branches: [main, release/*]

# 策略5：使用结构化输出减少Token消耗
claude_args: |
  --json-schema '{"type":"object","properties":{"approved":{"type":"boolean"},"issues":{"type":"array","items":{"type":"string"}}}}'
```

### 6.4 云服务商集成

除了Anthropic直接API，还支持三大云平台：

```yaml
# AWS Bedrock
- uses: anthropics/claude-code-action@v1
  with:
    use_bedrock: true
    # 通过OIDC自动认证，无需API Key

# Google Vertex AI
- uses: anthropics/claude-code-action@v1
  with:
    use_vertex: true
    # 通过OIDC自动认证

# Microsoft Foundry
# 参见 docs/cloud-providers.md
```

---

## 第七部分：完整实战项目——自动化代码质量守卫

将上述知识整合为一个完整的代码质量自动化系统。

### 项目结构

```
.github/
├── workflows/
│   ├── claude-review.yml        # PR自动审查
│   ├── claude-triage.yml        # Issue自动分类
│   ├── claude-maintenance.yml   # 每周健康巡检
│   └── claude-ci-analysis.yml   # CI失败分析
├── claude-prompts/
│   ├── review-template.md       # 审查提示词模板
│   └── security-checklist.md    # 安全检查清单
└── CLAUDE.md                    # 项目级Claude配置
```

### 核心工作流：claude-review.yml

```yaml
name: Claude Code Review
on:
  pull_request:
    types: [opened, synchronize, ready_for_review]
  pull_request_review_comment:
    types: [created]

jobs:
  # 判断是否需要审查（跳过Draft PR）
  check:
    runs-on: ubuntu-latest
    outputs:
      should_review: ${{ steps.check.outputs.result }}
    steps:
      - id: check
        run: |
          if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
            echo "result=false" >> $GITHUB_OUTPUT
          else
            echo "result=true" >> $GITHUB_OUTPUT
          fi

  # 自动审查
  auto-review:
    needs: check
    if: needs.check.outputs.should_review == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          track_progress: true
          prompt: |
            REPO: ${{ github.repository }}
            PR NUMBER: ${{ github.event.pull_request.number }}
            AUTHOR: ${{ github.event.pull_request.user.login }}
            BASE: ${{ github.base_ref }}
            HEAD: ${{ github.head_ref }}

            ## 审查任务

            对此Pull Request进行全面审查。

            ### 代码质量
            - 遵循项目编码规范
            - 无重复代码
            - 合理的错误处理
            - 清晰的函数/变量命名

            ### 安全审查
            - 无硬编码凭据
            - 输入验证充分
            - 无注入风险

            ### 测试覆盖
            - 新功能有对应测试
            - 边界情况覆盖

            ### 性能考量
            - 无不必要的循环/递归
            - 合理的数据结构选择
            - 无N+1查询风险

            使用行内评论标注具体问题。
            发布一条汇总评论，给出总体评分和关键发现。
          claude_args: |
            --max-turns 15
            --allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*),Read"

  # 交互式响应（处理@claude评论）
  interactive:
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request_review_comment'
    permissions:
      contents: read
      pull-requests: write
      id-token: write
    steps:
      - uses: actions/checkout@v6

      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          # 无prompt → 交互模式，响应@claude评论
          claude_args: |
            --allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*),Read,Edit"
```

### CLAUDE.md配置

```markdown
# Project Configuration

## Code Style
- TypeScript strict mode
- ESLint + Prettier
- 2-space indentation

## Testing
- Run: `npm test`
- Coverage: `npm run test:coverage`
- Threshold: 80% line coverage

## Build
- Build: `npm run build`
- Lint: `npm run lint`

## Review Priorities
1. Security > Correctness > Performance > Style
2. All public APIs must have JSDoc comments
3. No `any` types without explicit justification

## CI Commands
- Full CI: `npm run ci` (lint + test + build)
```

---

## 训练营适用性评估

| 训练营类型 | 适用性 | 预计时长 | 推荐模块 |
|-----------|--------|----------|----------|
| DevOps工程师训练营 | ★★★★★ | 4小时 | 全部内容 |
| 全栈开发训练营 | ★★★★ | 3小时 | 第一~四部分 + 实战项目 |
| 团队技术负责人培训 | ★★★★★ | 3小时 | 第二~三部分 + 安全最佳实践 |
| AI工程化实战营 | ★★★★ | 5小时 | 全部内容 + Agent SDK深入 |
| GitHub Actions专项 | ★★★★★ | 2.5小时 | 第二~三部分 + 场景练习 |

**前置知识要求**：Git基本操作、YAML语法、至少一门编程语言（TypeScript/Python）。

---

## 参考来源

1. [anthropics/claude-code-action - GitHub](https://github.com/anthropics/claude-code-action) — 官方GitHub Action仓库，包含完整文档和示例
2. [Run Claude Code programmatically - Claude Code Docs](https://code.claude.com/docs/en/headless) — 官方无头模式和SDK文档
3. [anthropics/claude-agent-sdk-typescript - GitHub](https://github.com/anthropics/claude-agent-sdk-typescript) — 官方Agent SDK TypeScript版本
4. [Claude Code settings - Claude Code Docs](https://code.claude.com/docs/en/settings) — 配置系统与权限管理官方文档
5. [Claude Code Batch Processing Guide](https://smartscope.blog/en/generative-ai/claude/claude-code-batch-processing/) — 批量处理与`-p`模式详解

> [!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)
