<!-- title: Claude Code动态工作流与自动化编排全实战 -->

# Claude Code动态工作流与自动化编排全实战

## 概述

本教程面向中高级开发者，深入讲解Claude Code的三大自动化核心能力：**`-p`（Print/Headless）非交互模式**、**Hooks生命周期钩子**、以及2026年5月随Opus 4.8发布的**Dynamic Workflows动态工作流**。学完本教程，你将掌握从单次脚本调用到千人级子Agent并行编排的完整自动化链路，构建真正"无人值守"的AI开发流水线。

**适合人群**：已有Claude Code基础使用经验，希望将其集成到CI/CD、批量任务、大规模代码重构等自动化场景的开发者。

## 前置条件

| 项目 | 要求 |
|------|------|
| Claude Code版本 | ≥ 2.1.154（Dynamic Workflows需要） |
| 运行环境 | macOS / Linux / WSL2 |
| 账户 | Claude Max订阅或API Key |
| 基础知识 | Shell脚本、JSON、Git |
| 可选 | Python 3.10+（Agent SDK）、Node.js 18+ |

---

## 第一部分：Headless模式 — 非交互式调用基础

### 1.1 核心概念

`-p`（`--print`）标志是Claude Code自动化的基石。它让Claude在非交互模式下运行：接收一条Prompt，执行完毕后输出结果并退出，整个过程无需人类介入。

```bash
# 最基本用法
claude -p "解释当前项目的目录结构"

# 管道输入
cat error.log | claude -p "分析这段错误日志的根本原因"

# 从文件读取Prompt
claude -p "$(cat prompt.txt)"
```

### 1.2 输出格式三剑客

`--output-format` 控制返回数据的结构化程度，是脚本集成的关键参数：

```bash
# text — 纯文本，适合直接阅读
claude -p "生成README" --output-format text

# json — 完整结构化响应，包含cost、duration、session_id等元信息
claude -p "列出所有TODO注释" --output-format json

# stream-json — NDJSON流式输出，每行一个JSON对象，适合实时处理
claude -p "重构src/目录" --output-format stream-json | jq -c 'select(.type == "assistant")'
```

**stream-json的典型消息类型**：

```jsonl
{"type":"system","subtype":"init","session_id":"abc123","tools":["Read","Write","Bash"]}
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"正在分析..."}]}}
{"type":"result","subtype":"success","cost_usd":0.023,"duration_ms":4521,"num_turns":3}
```

### 1.3 关键CLI标志组合

```bash
# 限制工具集 — 只允许读取，不允许修改
claude -p "审查代码质量" \
  --allowedTools "Read,Glob,Grep" \
  --output-format json

# 限制交互轮数 — 防止无限循环
claude -p "修复lint错误" \
  --max-turns 10 \
  --output-format text

# 延续上次会话 — 实现多轮对话
claude -p --continue "继续上次未完成的重构"

# 指定模型
claude -p "执行复杂架构分析" \
  --model claude-opus-4-6 \
  --output-format json
```

### 1.4 退出码与错误处理

| 退出码 | 含义 | 处理策略 |
|--------|------|----------|
| 0 | 成功完成 | 继续流水线 |
| 1 | 一般错误 | 检查stderr |
| 2 | 权限不足 | 检查`--allowedTools` |
| 130 | 超时/被中断 | 增加`--max-turns`或超时时间 |

```bash
#!/bin/bash
# 安全的headless调用模板
result=$(claude -p "$1" --output-format json --max-turns 15 2>&1)
exit_code=$?

if [ $exit_code -eq 0 ]; then
  echo "$result" | jq -r '.result'
else
  echo "ERROR (code=$exit_code): $result" >&2
  exit $exit_code
fi
```

### 1.5 实战：批量代码审查脚本

```bash
#!/bin/bash
# batch-review.sh — 对所有修改的文件逐一执行AI审查
set -euo pipefail

CHANGED_FILES=$(git diff --name-only main...HEAD)

for file in $CHANGED_FILES; do
  echo "=== 审查: $file ==="
  
  # 只审查代码文件
  if [[ ! "$file" =~ \.(ts|tsx|py|go|rs|java)$ ]]; then
    echo "跳过非代码文件: $file"
    continue
  fi
  
  claude -p "审查这个文件的代码质量，关注安全性、性能和可维护性: $(cat "$file")" \
    --allowedTools "Read" \
    --output-format json \
    --max-turns 3 \
    > "reviews/$(basename "$file").json"
    
  echo "✓ 审查完成: $file"
done

echo "全部审查结果已保存到 reviews/ 目录"
```

---

## 第二部分：Hooks — 生命周期事件钩子

### 2.1 Hooks架构总览

Hooks是Claude Code的事件驱动机制，允许你在特定生命周期节点自动执行Shell命令、HTTP请求或LLM提示。这是将Claude Code从"工具"升级为"平台"的关键设计。

```mermaid
flowchart TD
    A[用户提交Prompt] --> B[UserPromptSubmit Hook]
    B --> C{Hook通过?}
    C -->|exit 0| D[Claude思考并选择工具]
    C -->|exit 2| E[阻断本次操作]
    D --> F[PreToolUse Hook]
    F --> G{Hook通过?}
    G -->|exit 0| H[执行工具]
    G -->|exit 2| I[阻止工具执行]
    H --> J[PostToolUse Hook]
    J --> K[继续Agentic Loop]
    K --> L{任务完成?}
    L -->|否| D
    L -->|是| M[Stop Hook]
    M --> N[Notification Hook]

    style B fill:#4CAF50,color:white
    style F fill:#FF9800,color:white
    style J fill:#2196F3,color:white
    style M fill:#9C27B0,color:white
    style N fill:#F44336,color:white
```

### 2.2 六大生命周期事件

| 事件 | 触发时机 | 典型用途 |
|------|----------|----------|
| **PreToolUse** | 工具执行前 | 命令审计、安全拦截、参数校验 |
| **PostToolUse** | 工具执行后 | 自动格式化、日志记录、通知推送 |
| **Notification** | 长时间任务通知 | Slack/邮件通知、桌面提醒 |
| **Stop** | 任务完成时 | 质量检查、报告生成、CI触发 |
| **SubAgentStop** | 子Agent完成时 | 子任务结果汇总 |
| **UserPromptSubmit** | 用户输入后 | Prompt预处理、注入上下文 |

### 2.3 配置文件结构

Hooks在`.claude/settings.json`中配置，支持项目级和用户级两个层级：

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3 .claude/hooks/audit_command.py"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write $CLAUDE_FILE_PATH 2>/dev/null || true"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "bash .claude/hooks/on_complete.sh"
          }
        ]
      }
    ],
    "Notification": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "curl -X POST $SLACK_WEBHOOK -H 'Content-type: application/json' --data '{\"text\":\"Claude Code任务完成\"}'"
          }
        ]
      }
    ]
  }
}
```

### 2.4 Hook通信协议

Hook通过标准的Unix管道与Claude Code通信：

```
┌─────────────────┐     JSON on stdin      ┌──────────────────┐
│                  │ ──────────────────────▶ │                   │
│   Claude Code    │                        │   Hook Script     │
│                  │ ◀────────────────────── │                   │
└─────────────────┘     JSON on stdout      └──────────────────┘
                         exit code:
                         0 = 继续
                         2 = 阻断
```

**PreToolUse收到的JSON输入示例**：

```json
{
  "session_id": "sess_abc123",
  "tool_name": "Bash",
  "tool_input": {
    "command": "rm -rf /tmp/test",
    "description": "清理临时文件"
  }
}
```

**Hook的输出格式**：

```json
{
  "decision": "block",
  "reason": "检测到危险的rm -rf命令，已拦截"
}
```

### 2.5 实战：安全防护Hook系统

```python
#!/usr/bin/env python3
# .claude/hooks/pre_tool_use.py — 安全拦截器
import json
import sys

def main():
    data = json.load(sys.stdin)
    tool_name = data.get("tool_name", "")
    tool_input = data.get("tool_input", {})
    
    # 规则1：拦截危险Bash命令
    if tool_name == "Bash":
        cmd = tool_input.get("command", "")
        dangerous_patterns = [
            "rm -rf /", "DROP TABLE", "format C:",
            "> /dev/sda", "curl.*|.*sh", "chmod 777"
        ]
        import re
        for pattern in dangerous_patterns:
            if re.search(pattern, cmd, re.IGNORECASE):
                print(json.dumps({
                    "decision": "block",
                    "reason": f"拦截危险命令: 匹配模式 '{pattern}'"
                }))
                sys.exit(2)
    
    # 规则2：保护关键文件不被写入
    if tool_name in ("Write", "Edit"):
        file_path = tool_input.get("file_path", "")
        protected = [".env", "credentials", "secret", "production.yaml"]
        for keyword in protected:
            if keyword in file_path.lower():
                print(json.dumps({
                    "decision": "block",
                    "reason": f"保护敏感文件: {file_path}"
                }))
                sys.exit(2)
    
    # 通过所有检查
    sys.exit(0)

if __name__ == "__main__":
    main()
```

### 2.6 实战：自动格式化Hook

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'FILE=$(cat | jq -r \".tool_input.file_path // .tool_input.filepath // empty\"); if [ -n \"$FILE\" ]; then case \"$FILE\" in *.py) python3 -m black \"$FILE\" 2>/dev/null ;; *.ts|*.tsx) npx prettier --write \"$FILE\" 2>/dev/null ;; *.go) gofmt -w \"$FILE\" 2>/dev/null ;; esac; fi'"
          }
        ]
      }
    ]
  }
}
```

---

## 第三部分：Dynamic Workflows — 千人级并行编排

### 3.1 什么是Dynamic Workflows

2026年5月28日，Anthropic随Claude Opus 4.8发布了Dynamic Workflows（研究预览版）。这是Claude Code架构的一次范式跃迁：从"所有逻辑都在上下文窗口中"变为"Claude自动编写JavaScript工作流脚本来协调子Agent"。

**核心能力**：
- 单条Prompt可扇出（fan-out）至**1000个并行子Agent**
- Claude自动生成`workflow.js`编排脚本
- 每个子Agent拥有独立的上下文窗口，互不干扰
- 支持动态分支、条件路由、结果聚合

```mermaid
flowchart LR
    P[用户Prompt] --> O[Orchestrator Agent]
    O -->|生成workflow.js| W[JavaScript运行时]
    W --> S1[SubAgent 1]
    W --> S2[SubAgent 2]
    W --> S3[SubAgent 3]
    W --> S4[SubAgent N...]
    S1 --> R[结果聚合]
    S2 --> R
    S3 --> R
    S4 --> R
    R --> F[最终输出]

    style O fill:#FF6B6B,color:white
    style W fill:#4ECDC4,color:white
    style R fill:#45B7D1,color:white
```

### 3.2 启用Dynamic Workflows

Dynamic Workflows目前是研究预览功能，需要显式启用：

```bash
# 方法1：环境变量
export CLAUDE_CODE_ENABLE_DYNAMIC_WORKFLOWS=1

# 方法2：在.claude/settings.json中配置
# {
#   "experimentalFeatures": {
#     "dynamicWorkflows": true
#   }
# }

# 方法3：headless模式中使用
CLAUDE_CODE_ENABLE_DYNAMIC_WORKFLOWS=1 claude -p \
  "将src/目录下所有组件从Class组件迁移到Hooks" \
  --model claude-opus-4-6
```

### 3.3 工作原理：三阶段执行

**阶段一：规划**
Claude分析任务复杂度，判断是否需要动态工作流。对于大型任务，Claude会自动生成一个`workflow.js`文件，定义子Agent的分工和依赖关系。

**阶段二：执行**
JavaScript运行时解析workflow.js，将任务分发给并行子Agent。每个子Agent是一个独立的Claude Code会话，拥有自己的工具集和上下文。

**阶段三：聚合**
所有子Agent完成后，结果被收集、合并，由编排器生成最终输出。

### 3.4 实战：大规模代码迁移

```bash
# 场景：将100+文件从JavaScript迁移到TypeScript
CLAUDE_CODE_ENABLE_DYNAMIC_WORKFLOWS=1 claude -p \
  "将src/目录下所有.js文件迁移到TypeScript：
   1. 添加类型注解
   2. 创建对应的.ts文件
   3. 更新所有import路径
   4. 确保每个迁移后的文件通过tsc --noEmit检查
   每个文件分配给一个独立的子Agent并行处理" \
  --model claude-opus-4-6 \
  --output-format stream-json
```

Claude会自动生成类似如下的编排脚本：

```javascript
// workflow.js (由Claude自动生成)
const files = await glob("src/**/*.js");

const tasks = files.map(file => ({
  agent: {
    prompt: `将 ${file} 迁移为TypeScript。添加完整的类型注解，确保通过 tsc --noEmit。`,
    tools: ["Read", "Write", "Edit", "Bash"],
    model: "claude-sonnet-4-6"
  }
}));

const results = await Promise.all(tasks.map(t => runAgent(t)));
await aggregate(results);
```

### 3.5 ultracode模式

Dynamic Workflows引入了一个新概念——**ultracode**模式。当启用时，Claude会最大化利用并行能力：

```bash
# 启用ultracode
CLAUDE_CODE_ENABLE_DYNAMIC_WORKFLOWS=1 claude -p \
  "重构整个项目的错误处理模式" \
  --model claude-opus-4-6

# ultracode会在settings中配置
# "ultracode": "xhigh"  — 最高并行度，适合大批量任务
# "ultracode": "high"   — 高并行度
# "ultracode": "medium" — 中等并行度（默认）
```

---

## 第四部分：Agent SDK — 编程式调用

### 4.1 SDK概述

Claude Agent SDK（原Claude Code SDK）让你从Python或TypeScript代码中直接调用Claude Code的完整能力——包括文件读写、命令执行、代码编辑等所有工具。

**安装**：

```bash
# Python
pip install claude-agent-sdk

# TypeScript
npm install @anthropic-ai/claude-agent-sdk
```

### 4.2 Python SDK快速上手

```python
import asyncio
from claude_code_sdk import query, ClaudeCodeOptions

async def main():
    # 基础调用
    result = await query(
        prompt="分析当前项目的架构，找出可以优化的瓶颈",
        options=ClaudeCodeOptions(
            allowed_tools=["Read", "Glob", "Grep", "Bash"],
            max_turns=10,
            output_format="json"
        )
    )
    
    # 处理流式响应
    async for event in query_stream(
        prompt="重构auth模块",
        options=ClaudeCodeOptions(
            allowed_tools=["Read", "Write", "Edit", "Bash"],
            max_turns=20
        )
    ):
        if event.type == "assistant":
            print(f"助手: {event.message.content}")
        elif event.type == "result":
            print(f"完成! 耗时: {event.duration_ms}ms, 费用: ${event.cost_usd}")

asyncio.run(main())
```

### 4.3 多轮会话管理

```python
from claude_code_sdk import query, ClaudeCodeOptions, Session

async def code_review_pipeline():
    # 创建持久会话
    session = Session()
    
    # 第一轮：全局分析
    r1 = await session.query("分析这个项目的测试覆盖率")
    
    # 第二轮：基于分析结果深入
    r2 = await session.query("为覆盖率最低的三个模块编写测试")
    
    # 第三轮：验证
    r3 = await session.query("运行所有测试，确保新测试通过")
    
    return r3

asyncio.run(code_review_pipeline())
```

### 4.4 多Agent并行编排

```python
import asyncio
from claude_code_sdk import query, ClaudeCodeOptions

async def parallel_review():
    """并行审查多个文件"""
    files = ["src/auth.py", "src/api.py", "src/db.py", "src/utils.py"]
    
    options = ClaudeCodeOptions(
        allowed_tools=["Read", "Grep"],
        max_turns=5,
        output_format="json"
    )
    
    # 并发启动4个审查任务
    tasks = [
        query(
            prompt=f"审查文件 {f} 的安全漏洞、性能问题和代码风格。输出JSON格式。",
            options=options
        )
        for f in files
    ]
    
    results = await asyncio.gather(*tasks)
    
    # 聚合结果
    for f, r in zip(files, results):
        print(f"\n{'='*50}")
        print(f"文件: {f}")
        print(r)

asyncio.run(parallel_review())
```

---

## 第五部分：CI/CD集成 — GitHub Actions实战

### 5.1 自动PR审查

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

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      
      - name: Claude Code Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          # 获取变更文件列表
          CHANGED=$(git diff --name-only origin/main...HEAD)
          
          # 逐一审查
          for file in $CHANGED; do
            echo "审查: $file"
            claude -p \
              "作为代码审查专家，审查文件 $file 的变更。
               关注：安全性、性能、可维护性、测试覆盖。
               用中文输出审查意见，格式为GitHub评论。" \
              --allowedTools "Read,Grep,Glob" \
              --output-format text \
              --max-turns 5 \
              >> review_comments.md
            
            echo -e "\n---\n" >> review_comments.md
          done
      
      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = fs.readFileSync('review_comments.md', 'utf8');
            github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: review
            });
```

### 5.2 自动修复CI失败

```yaml
# .github/workflows/auto-fix.yml
name: Auto-fix CI Failures

on:
  workflow_run:
    workflows: ["Test"]
    types: [completed]
    conclusion: failure

jobs:
  auto-fix:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Get Failure Logs
        run: |
          gh run view ${{ github.event.workflow_run.id }} --log > failure.log
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Claude Auto-fix
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p \
            "CI测试失败了，错误日志如下：$(cat failure.log)
             请分析失败原因，修复代码，确保测试通过。
             只修改必要的代码，不要过度重构。" \
            --allowedTools "Read,Write,Edit,Bash" \
            --max-turns 15 \
            --output-format json \
            > fix_result.json
          
          # 检查修复是否成功
          if [ "$(jq -r '.exit_code // 0' fix_result.json)" = "0" ]; then
            echo "fix_applied=true" >> $GITHUB_OUTPUT
          fi
      
      - name: Commit and Push Fix
        if: steps.auto-fix.outputs.fix_applied == 'true'
        run: |
          git config user.name "Claude Code Bot"
          git config user.email "claude-bot@example.com"
          git add -A
          git commit -m "fix: 自动修复CI测试失败

          Co-Authored-By: Claude <noreply@anthropic.com>"
          git push
```

### 5.3 定时代码质量扫描

```yaml
# .github/workflows/quality-scan.yml
name: Weekly Quality Scan

on:
  schedule:
    - cron: '0 2 * * 1'  # 每周一凌晨2点

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Full Codebase Analysis
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p \
            "对整个代码库进行全面质量审计：
             1. 安全漏洞扫描（OWASP Top 10）
             2. 性能瓶颈识别
             3. 死代码检测
             4. 依赖安全审计
             5. 代码复杂度分析
             输出结构化JSON报告。" \
            --allowedTools "Read,Glob,Grep,Bash" \
            --max-turns 30 \
            --output-format json \
            > quality_report.json
      
      - name: Create Issue
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const report = JSON.parse(fs.readFileSync('quality_report.json', 'utf8'));
            github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: `Weekly Quality Report - ${new Date().toISOString().split('T')[0]}`,
              body: report.result || 'See attached report',
              labels: ['quality', 'automated']
            });
```

---

## 第六部分：综合实战 — 全自动代码迁移流水线

### 6.1 场景描述

将一个中型React项目（50+组件）从JavaScript Class组件迁移到TypeScript函数组件+Hooks。

### 6.2 完整流水线架构

```mermaid
flowchart TB
    subgraph Phase1["阶段1: 分析"]
        A[扫描项目结构] --> B[识别Class组件]
        B --> C[生成迁移清单]
    end

    subgraph Phase2["阶段2: 迁移"]
        C --> D1[Agent 1: 组件A]
        C --> D2[Agent 2: 组件B]
        C --> D3[Agent 3: 组件C]
        C --> D4[Agent N: ...]
    end

    subgraph Phase3["阶段3: 验证"]
        D1 --> E[TypeScript编译检查]
        D2 --> E
        D3 --> E
        D4 --> E
        E --> F[运行测试套件]
        F --> G{通过?}
        G -->|是| H[生成PR]
        G -->|否| I[自动修复]
        I --> F
    end

    subgraph Phase4["阶段4: 报告"]
        H --> J[迁移统计]
        J --> K[质量报告]
    end

    style A fill:#E8F5E9
    style D1 fill:#FFF3E0
    style D2 fill:#FFF3E0
    style D3 fill:#FFF3E0
    style D4 fill:#FFF3E0
    style E fill:#E3F2FD
    style H fill:#F3E5F5
```

### 6.3 编排脚本

```bash
#!/bin/bash
# migrate-react.sh — 全自动React迁移流水线
set -euo pipefail

PROJECT_DIR="$1"
LOG_DIR="migration_logs_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$LOG_DIR"

echo "========================================="
echo " React → TypeScript 迁移流水线"
echo " 项目: $PROJECT_DIR"
echo "========================================="

# ---- 阶段1: 分析 ----
echo "[Phase 1] 分析项目结构..."

INVENTORY=$(claude -p \
  "分析 $PROJECT_DIR 项目的React组件结构。
   列出所有Class组件，按复杂度排序。
   输出JSON格式: [{file, name, complexity, dependencies}]" \
  --allowedTools "Read,Glob,Grep" \
  --max-turns 10 \
  --output-format json)

echo "$INVENTORY" | jq '.' > "$LOG_DIR/inventory.json"
COMPONENT_COUNT=$(echo "$INVENTORY" | jq '.result | length')
echo "发现 $COMPONENT_COUNT 个Class组件"

# ---- 阶段2: 并行迁移 ----
echo "[Phase 2] 启动并行迁移..."

# 使用Dynamic Workflows或手动并行
claude -p \
  "将以下Class组件迁移为TypeScript函数组件+Hooks:
   $(cat "$LOG_DIR/inventory.json")
   
   迁移规则：
   - this.state → useState/useReducer
   - componentDidMount → useEffect
   - componentDidUpdate → useEffect  
   - componentWillUnmount → useEffect cleanup
   - this.props → 函数参数+TypeScript接口
   - PropTypes → TypeScript类型
   - 每个文件一个独立的子Agent处理
   迁移后确保TypeScript编译通过" \
  --allowedTools "Read,Write,Edit,Bash,Glob,Grep" \
  --max-turns 50 \
  --output-format stream-json \
  > "$LOG_DIR/migration_stream.jsonl" || true

# ---- 阶段3: 验证 ----
echo "[Phase 3] 运行验证..."

# TypeScript编译检查
cd "$PROJECT_DIR"
if npx tsc --noEmit 2>&1 | tee "$LOG_DIR/tsc_errors.txt"; then
  echo "✓ TypeScript编译通过"
else
  echo "✗ TypeScript编译错误，尝试自动修复..."
  claude -p \
    "修复以下TypeScript编译错误：$(cat "$LOG_DIR/tsc_errors.txt")" \
    --allowedTools "Read,Write,Edit" \
    --max-turns 15 \
    --output-format text
fi

# 运行测试
if npm test 2>&1 | tee "$LOG_DIR/test_results.txt"; then
  echo "✓ 所有测试通过"
else
  echo "✗ 测试失败，尝试自动修复..."
  claude -p \
    "修复以下测试失败：$(cat "$LOG_DIR/test_results.txt")" \
    --allowedTools "Read,Write,Edit,Bash" \
    --max-turns 20 \
    --output-format text
fi

cd -

# ---- 阶段4: 生成报告 ----
echo "[Phase 4] 生成迁移报告..."

claude -p \
  "基于以下日志生成迁移报告:
   - 清单: $(cat "$LOG_DIR/inventory.json")
   - 迁移流: $(head -100 "$LOG_DIR/migration_stream.jsonl")
   - TSC结果: $(cat "$LOG_DIR/tsc_errors.txt")
   - 测试结果: $(cat "$LOG_DIR/test_results.txt")
   
   报告包含：迁移统计、成功/失败列表、遗留问题、建议后续步骤" \
  --allowedTools "Read" \
  --max-turns 5 \
  --output-format text \
  > "$LOG_DIR/migration_report.md"

echo "========================================="
echo " 迁移完成! 报告: $LOG_DIR/migration_report.md"
echo "========================================="
```

### 6.4 与Hooks集成增强安全性

在上述流水线中配置安全Hook：

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command": "python3 .claude/hooks/safety_check.py"
        }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
          },
          {
            "type": "command",
            "command": "npx eslint --fix \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [{
          "type": "command",
          "command": "curl -s -X POST \"$SLACK_WEBHOOK\" -H 'Content-Type: application/json' -d '{\"text\": \"✅ 迁移任务完成! 查看报告: '$LOG_DIR/migration_report.md\"}' || true"
        }]
      }
    ]
  }
}
```

---

## 第七部分：高级模式与最佳实践

### 7.1 断点续传：多轮Headless会话

```bash
#!/bin/bash
# resume-pipeline.sh — 支持中断恢复的流水线

SESSION_FILE=".claude_session_id"

if [ -f "$SESSION_FILE" ]; then
  SESSION_ID=$(cat "$SESSION_FILE")
  echo "恢复会话: $SESSION_ID"
  claude -p --resume "$SESSION_ID" \
    "继续之前的任务" \
    --output-format json
else
  echo "启动新会话..."
  result=$(claude -p \
    "开始重构任务..." \
    --output-format json)
  
  # 保存session_id
  echo "$result" | jq -r '.session_id' > "$SESSION_FILE"
fi
```

### 7.2 错误重试与指数退避

```bash
#!/bin/bash
# retry-wrapper.sh — 带重试的headless调用

MAX_RETRIES=3
RETRY_DELAY=5

run_claude_with_retry() {
  local prompt="$1"
  local attempt=0
  
  while [ $attempt -lt $MAX_RETRIES ]; do
    attempt=$((attempt + 1))
    echo "尝试 $attempt/$MAX_RETRIES..."
    
    if result=$(claude -p "$prompt" --output-format json --max-turns 20 2>&1); then
      echo "$result"
      return 0
    fi
    
    if [ $attempt -lt $MAX_RETRIES ]; then
      delay=$((RETRY_DELAY * 2 ** (attempt - 1)))
      echo "失败，${delay}秒后重试..."
      sleep $delay
    fi
  done
  
  echo "所有重试均失败" >&2
  return 1
}
```

### 7.3 成本控制策略

```bash
# 使用Sonnet处理简单任务（降低成本）
claude -p "格式化这个文件" \
  --model claude-sonnet-4-6 \
  --max-turns 3

# 使用Opus处理复杂架构决策
claude -p "重新设计认证系统的架构" \
  --model claude-opus-4-6 \
  --max-turns 30

# 限制工具减少API调用
claude -p "审查代码" \
  --allowedTools "Read,Grep" \
  --max-turns 5
```

### 7.4 Agent Teams — 多实例协作

```bash
# agent-team.sh — 启动多个Claude Code实例协作
# 需要 Claude Code ≥ 2.1.150

# 在独立worktree中启动多个Agent
claude -p \
  "作为前端Agent，负责React组件开发" \
  --output-format stream-json &
PID_FRONTEND=$!

claude -p \
  "作为后端Agent，负责API开发" \
  --output-format stream-json &
PID_BACKEND=$!

claude -p \
  "作为测试Agent，等待前两个完成后编写测试" \
  --output-format stream-json &
PID_TEST=$!

# 等待所有Agent完成
wait $PID_FRONTEND $PID_BACKEND $PID_TEST
echo "所有Agent已完成"
```

---

## 常见问题与解决方案

### Q1: Headless模式下Claude卡住不动

**原因**：可能是`--max-turns`设置过低，或Claude在等待用户确认（权限弹窗）。

**解决**：
```bash
# 使用plan权限模式跳过确认
claude -p "任务" --permission-mode plan

# 或者使用bypassPermissions（仅CI环境）
claude -p "任务" --dangerously-skip-permissions
```

### Q2: Dynamic Workflows子Agent全部失败

**原因**：API rate limiting或token额度不足。

**解决**：
```bash
# 降低并行度
# 在CLAUDE.md中添加：
# dynamicWorkflows:
#   maxConcurrency: 5

# 或使用环境变量
export CLAUDE_MAX_CONCURRENCY=5
```

### Q3: Hooks不生效

**原因**：配置文件路径错误或脚本没有执行权限。

**解决**：
```bash
# 检查配置文件位置
ls -la .claude/settings.json
cat .claude/settings.json | jq '.hooks'

# 确保Hook脚本有执行权限
chmod +x .claude/hooks/*.py .claude/hooks/*.sh

# 测试Hook脚本
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | \
  python3 .claude/hooks/pre_tool_use.py
echo "Exit code: $?"
```

### Q4: stream-json输出解析失败

**原因**：某些消息可能跨行或格式不标准。

**解决**：
```bash
# 使用jq的-R选项逐行处理
claude -p "任务" --output-format stream-json | \
  while IFS= read -r line; do
    echo "$line" | jq -c 'select(.type == "result") // empty' 2>/dev/null
  done
```

---

## 延伸阅读

- [Claude Code Headless模式官方文档](https://code.claude.com/docs/en/headless) — 非交互模式的权威参考
- [Hooks参考文档](https://code.claude.com/docs/en/hooks) — 所有Hook事件的JSON schema和通信协议
- [Hooks自动化指南](https://code.claude.com/docs/en/hooks-guide) — Hook实战场景和最佳实践
- [Agent SDK概览](https://code.claude.com/docs/en/agent-sdk/overview) — Python/TypeScript SDK完整API
- [Dynamic Workflows文档](https://code.claude.com/docs/en/agents) — 并行子Agent编排
- [GitHub Actions集成](https://code.claude.com/docs/en/github-actions) — CI/CD自动化模板
- [CLI完整参考](https://code.claude.com/docs/en/cli-reference) — 所有命令行标志和参数

---

## 训练营适用性评估

| 维度 | 评估 |
|------|------|
| **适合训练营** | 进阶训练营（学员已有Claude Code基础） |
| **教学时长** | 4-6小时（含实操练习） |
| **实操占比** | 70%（大量动手配置和调试） |
| **前置要求** | 完成入门篇、熟悉Shell脚本、有GitHub项目经验 |
| **硬件要求** | 稳定网络、Claude Max订阅、Linux/macOS终端 |
| **分组建议** | 2-3人一组，每组负责不同自动化场景 |
| **考核方式** | 完成完整的CI/CD集成Pipeline或Dynamic Workflow迁移任务 |

---

## 参考来源

1. [Run Claude Code programmatically - Claude Code Docs](https://code.claude.com/docs/en/headless) — Headless模式官方文档，包含`-p`标志、输出格式、会话管理
2. [Hooks reference - Claude Code Docs](https://code.claude.com/docs/en/hooks) — Hook事件、JSON schema、通信协议的完整参考
3. [Automate workflows with hooks - Claude Code Docs](https://code.claude.com/docs/en/hooks-guide) — Hook实战指南和配置示例
4. [Run agents in parallel - Claude Code Docs](https://code.claude.com/docs/en/agents) — Dynamic Workflows官方文档
5. [Claude Code Dynamic Workflows: Scripts Replace Context Windows - TechTimes](https://www.techtimes.com/articles/317363/20260529/claude-code-dynamic-workflows-scripts-replace-context-windows-ultracode-automates-orchestration.htm) — Dynamic Workflows技术解析
6. [Claude Code Hooks: Complete Guide with 20+ Ready-to-Use Examples - AI Org](https://aiorg.dev/blog/claude-code-hooks) — 20+个可直接使用的Hook配置示例
7. [Claude Code Headless Mode for Batch Tasks and CI/CD - Restato](https://restato.github.io/blog/claude-code-headless-mode/) — Headless模式批量任务实践

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