<!-- title: Claude Code Routines云端自动化全实战 -->

# Claude Code Routines云端自动化全实战：从定时触发到Agent View并行管理

> **学习目标**：掌握Claude Code Routines（云端定时自动化）和Agent View（多会话并行管理）两大新特性，独立构建无人值守的AI开发工作流。
>
> **适用人群**：已使用Claude Code超过1个月、熟悉CLI操作、有GitHub项目管理经验的开发者。
>
> **关键版本**：Routines（2026年4月14日Research Preview）、Agent View（2026年5月11日GA）。

---

## 前置条件

| 项目 | 要求 |
|------|------|
| Claude Code版本 | ≥ 1.0.50（支持Routines命令） |
| 订阅计划 | Pro / Max / Team（Free不支持Routines） |
| Git仓库 | 至少一个GitHub连接的仓库 |
| 命令行工具 | `claude` CLI已登录并认证 |
| 可选 | Anthropic API Key（用于API触发器） |

升级CLI到最新版：

```bash
npm install -g @anthropic-ai/claude-code@latest
claude --version  # 确认 ≥ 1.0.50
claude auth status  # 确认已登录
```

---

## 一、为什么需要Routines：从手动到自动化的跃迁

### 1.1 传统自动化方案的局限

在Routines出现之前，Claude Code的自动化依赖三种方式：

```mermaid
graph LR
    A[手动模式] --> B[-p Headless模式]
    B --> C[CI/CD集成]
    C --> D[cron + 本地脚本]

    style A fill:#f9f,stroke:#333
    style D fill:#ff9,stroke:#333
```

每种方式都有硬伤：

| 方案 | 核心问题 |
|------|----------|
| `-p` + cron | 需要机器24小时在线，消耗本地资源 |
| GitHub Actions | 每次从零启动，无上下文记忆，配置复杂 |
| 自建Worker | 运维成本高，需要管理队列、重试、日志 |
| `/loop` | 绑定在当前终端，关机即中断 |

### 1.2 Routines的本质

Routines是Anthropic托管的云端自动化。你定义**一次**配置（prompt + repo + connectors），它就在Anthropic基础设施上**反复执行**，无需本地机器在线。

核心公式：

```
Routine = Prompt（做什么）+ Repo（在哪做）+ Trigger（何时做）+ Connectors（用什么做）
```

与本地自动化的根本区别：

| 维度 | 本地自动化 | Routines |
|------|-----------|----------|
| 执行环境 | 你的机器 | Anthropic云 |
| 上下文保持 | 无（每次冷启动） | 有（记忆仓库结构） |
| 基础设施 | 需要自己管理 | 零运维 |
| 触发方式 | cron/CI | Schedule/API/GitHub事件 |
| 并行能力 | 受本地资源限制 | 云端弹性扩展 |

---

## 二、Routine创建：三种触发器实战

### 2.1 创建流程概览

```mermaid
flowchart TD
    A[开始创建Routine] --> B{选择触发类型}
    B -->|定时执行| C[Schedule Trigger]
    B -->|接口调用| D[API Trigger]
    B -->|代码事件| E[GitHub Trigger]

    C --> F[配置cron表达式]
    D --> G[获取Webhook URL]
    E --> H[选择GitHub事件类型]

    F --> I[编写ROUTINE.md]
    G --> I
    H --> I

    I --> J[配置Connectors]
    J --> K[测试运行]
    K --> L[上线监控]

    style A fill:#4CAF50,color:white
    style L fill:#2196F3,color:white
```

### 2.2 Schedule触发器：定时代码审查

这是最常用的触发器，类似cron job但运行在云端。

**步骤1：初始化Routine配置**

```bash
# 进入目标仓库
cd ~/projects/my-api-service

# 创建Routine
claude routine create
```

CLI进入交互式配置：

```
? Routine name: daily-code-review
? Description: 每日凌晨审查昨日所有PR，生成审查报告
? Trigger type: Schedule
? Schedule (cron): 0 2 * * *    # 每天UTC凌晨2点
? Repository: my-org/my-api-service
? Branch: main
```

**步骤2：编写ROUTINE.md**

在仓库根目录创建 `.claude/routines/daily-code-review/ROUTINE.md`：

```markdown
# Daily Code Review

## 任务
审查过去24小时内合并到main分支的所有Pull Request。

## 检查维度
1. **安全性**：SQL注入、XSS、敏感信息泄露
2. **性能**：N+1查询、内存泄漏风险、大循环优化
3. **代码规范**：TypeScript类型安全、命名一致性
4. **架构一致性**：是否符合项目的分层架构

## 输出
- 在GitHub Issue中创建审查报告
- 标记高风险项为 `security` 标签
- 赋值给对应PR的作者
```

**步骤3：配置trigger.yaml**

`.claude/routines/daily-code-review/trigger.yaml`：

```yaml
name: daily-code-review
description: "每日凌晨审查昨日所有PR"
trigger:
  type: schedule
  schedule: "0 2 * * *"    # UTC时间
repository:
  owner: my-org
  name: my-api-service
  branch: main
connectors:
  - github
settings:
  timeout: 30m
  max_turns: 50
  model: claude-sonnet-4-6
```

**步骤4：激活并验证**

```bash
# 推送配置到远端
git add .claude/routines/
git commit -m "Add daily code review routine"
git push

# 在CLI中激活
claude routine enable daily-code-review

# 验证状态
claude routine list
```

预期输出：

```
┌────────────────────┬──────────┬────────────────┬─────────┐
│ Name               │ Trigger  │ Schedule       │ Status  │
├────────────────────┼──────────┼────────────────┼─────────┤
│ daily-code-review  │ schedule │ 0 2 * * *      │ active  │
└────────────────────┴──────────┴────────────────┴─────────┘
```

手动触发一次测试：

```bash
claude routine run daily-code-review --dry-run
```

`--dry-run` 模式下Routine会完整执行但不创建Issue，只输出到终端。

### 2.3 API触发器：Webhook驱动自动化

API触发器让外部系统通过HTTP请求启动Routine。适合CI/CD流水线、监控系统、Slack Bot等场景。

**步骤1：创建API Routine**

```bash
claude routine create
```

```
? Routine name: security-hotfix
? Description: 收到安全告警后自动分析并生成修复PR
? Trigger type: API
? Repository: my-org/my-api-service
```

**步骤2：获取Webhook URL**

```bash
claude routine enable security-hotfix
claude routine webhook security-hotfix
```

输出：

```
Webhook URL: https://api.claude.com/routines/trigger/sec_xxxxxxxxxxxx
Secret: whsec_xxxxxxxxxxxxxxxx

示例请求:
curl -X POST https://api.claude.com/routines/trigger/sec_xxxxxxxxxxxx \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Secret: whsec_xxxxxxxxxxxxxxxx" \
  -d '{"alert_type": "CVE-2026-1234", "severity": "critical", "package": "lodash@4.17.20"}'
```

**步骤3：编写ROUTINE.md**

```markdown
# Security Hotfix Routine

## 输入
Webhook payload中的告警信息。

## 任务
1. 分析CVE详情，判断是否影响本项目
2. 如果影响，检查依赖树找到受影响路径
3. 尝试升级到安全版本
4. 运行测试套件验证兼容性
5. 如果测试通过，创建修复PR
6. 如果升级引入破坏性变更，创建Issue说明风险

## 约束
- 只修改package.json和lock文件
- 不做代码重构
- PR标题格式: [security] fix CVE-XXXX-XXXX
```

**步骤4：集成到监控系统**

以GitHub Actions为例，在`.github/workflows/security-alert.yml`：

```yaml
name: Security Alert Handler
on:
  workflow_dispatch:
    inputs:
      alert_type:
        description: 'Alert type (CVE, etc.)'
      severity:
        description: 'Severity level'
      package:
        description: 'Affected package'

jobs:
  trigger-routine:
    runs-on: ubuntu-latest
    steps:
      - name: Trigger Claude Security Routine
        run: |
          curl -X POST ${{ secrets.CLAUDE_ROUTINE_WEBHOOK }} \
            -H "Content-Type: application/json" \
            -H "X-Webhook-Secret: ${{ secrets.CLAUDE_WEBHOOK_SECRET }}" \
            -d '{
              "alert_type": "${{ inputs.alert_type }}",
              "severity": "${{ inputs.severity }}",
              "package": "${{ inputs.package }}"
            }'
```

### 2.4 GitHub事件触发器：PR/Issue驱动的自动化

这是最强大的触发器，直接响应GitHub仓库事件，无需中间层。

**支持的GitHub事件类型**：

| 事件 | 触发时机 | 典型用途 |
|------|---------|---------|
| `pull_request.opened` | 新PR创建 | 自动审查代码 |
| `pull_request.synchronize` | PR新增提交 | 增量审查 |
| `issues.opened` | 新Issue创建 | 自动分诊 |
| `issue_comment.created` | Issue评论 | 响应指令 |
| `push` | 代码推送 | 运行检查 |

**实战：PR自动审查Routine**

`.claude/routines/pr-review/ROUTINE.md`：

```markdown
# PR Auto Review

## 任务
对新打开的Pull Request进行自动审查。

## 检查清单
1. PR描述是否完整（What/Why/How）
2. 是否包含测试变更
3. 代码风格是否与现有代码一致
4. 是否引入新的TODO或FIXME
5. 错误处理是否完善
6. API变更是否有对应的文档更新

## 输出
- 在PR中留下审查评论
- 使用GitHub Review API提交审查
- 严重问题标记为 "Request Changes"
- 小问题标记为 "Comment"
```

`.claude/routines/pr-review/trigger.yaml`：

```yaml
name: pr-auto-review
description: "自动审查新PR"
trigger:
  type: github
  events:
    - pull_request.opened
    - pull_request.synchronize
repository:
  owner: my-org
  name: my-api-service
connectors:
  - github
settings:
  timeout: 15m
  max_turns: 30
```

---

## 三、Connectors：让Routine连接外部世界

Connectors是Routine与外部服务通信的桥梁。一个Routine可以配置多个Connector。

### 3.1 可用Connectors

```mermaid
graph TB
    subgraph "Claude Code Routine"
        R[Routine核心]
    end

    subgraph "Connectors"
        G[GitHub<br/>PR/Issue/Review]
        S[Slack<br/>消息通知]
        N[Notion<br/>文档更新]
        W[Webhook<br/>自定义HTTP]
        D[Docker<br/>容器操作]
    end

    R --> G
    R --> S
    R --> N
    R --> W
    R --> D

    style R fill:#7C4DFF,color:white
    style G fill:#333,color:white
    style S fill:#4A154B,color:white
    style N fill:#000,color:white
```

### 3.2 配置GitHub Connector

```bash
# 首次使用需要授权
claude connector auth github
# 浏览器打开GitHub OAuth页面，授权后自动返回
```

在trigger.yaml中启用：

```yaml
connectors:
  - github:
      permissions:
        issues: write       # 创建/更新Issue
        pull_requests: write # 创建PR和Review
        contents: write      # 推送代码变更
```

### 3.3 配置Slack Connector（通知）

```yaml
connectors:
  - github
  - slack:
      channels:
        - "#engineering"
        - "#security-alerts"
      events:
        - on_complete: "✅ Routine {{name}} completed"
        - on_failure: "❌ Routine {{name}} failed: {{error}}"
        - on_pr_created: "🔔 New PR by {{author}}: {{title}}"
```

---

## 四、Agent View：多会话并行管理仪表盘

Routines在云端执行，Agent View则管理**本地**的并行开发会话。两者互补：Routines处理定时任务，Agent View让你同时推进多个开发任务。

### 4.1 启动Agent View

三种入口：

```bash
# 方式1：直接打开Agent View
claude agents

# 方式2：在活跃会话中按 Ctrl+B 推到后台
# （会话自动进入Agent View）

# 方式3：用/bg命令启动后台会话
claude --bg "重构src/utils目录下的所有工具函数，添加TypeScript泛型"
```

Agent View界面：

```
┌─────────────────────────────────────────────────┐
│  Agent View                           [N]ew [Q] │
├────┬──────────────────┬─────────┬───────────────┤
│ #  │ Session          │ Status  │ Last Activity │
├────┼──────────────────┼─────────┼───────────────┤
│ 1  │ 重构utils        │ running │ 2m ago        │
│ 2  │ 修复auth bug     │ done ✓  │ 5m ago        │
│ 3  │ 添加单元测试      │ waiting │ 1m ago        │
│ 4  │ 依赖更新          │ error ✗ │ 3m ago        │
└────┴──────────────────┴─────────┴───────────────┘
↑↓ 选择  Enter 进入  D 详情  X 终止
```

### 4.2 后台会话工作流

```mermaid
sequenceDiagram
    participant U as 开发者
    participant M as 主会话
    participant AV as Agent View
    participant B1 as 后台Session 1
    participant B2 as 后台Session 2

    U->>M: 开始编写feature
    M->>M: 遇到需要大量重构的部分
    
    Note over M,B1: 按Ctrl+B或输入/bg
    M->>AV: 推当前会话到后台
    AV->>B1: Session 1继续运行
    
    U->>AV: 查看所有后台会话
    AV-->>U: 显示Session状态列表
    
    U->>AV: 新建另一个后台任务
    AV->>B2: Session 2开始执行
    
    Note over B1,B2: 两个Session并行运行
    
    B1-->>AV: 完成通知
    AV-->>U: Session 1完成
    
    U->>AV: Enter进入Session 1
    AV->>U: 查看完整对话历史
    U->>M: 继续主会话工作
```

### 4.3 实战：多任务并行开发

场景：你需要同时完成三项任务。

**步骤1：启动主会话并分派后台任务**

```bash
# 启动主Claude Code会话
claude
```

在会话中：

```
> /bg "审查packages/api/src下的所有endpoint，确保每个都有input validation"
> Session pushed to background. Use `claude agents` to monitor.

> /bg "为packages/db/src/migrations目录下的所有migration添加rollback脚本"
> Session pushed to background.

> /bg "更新README.md，添加新的环境变量说明和部署流程"
> Session pushed to background.
```

**步骤2：在主会话继续工作**

三个后台Session在并行执行，你在主会话继续写新feature。

**步骤3：检查后台状态**

按 `Ctrl+B` 进入Agent View：

```
┌─────────────────────────────────────────────────────────────┐
│  Agent View                                    [N]ew [Q]uit │
├────┬──────────────────────────────────┬──────────┬──────────┤
│ #  │ Session                          │ Status   │ Activity │
├────┼──────────────────────────────────┼──────────┼──────────┤
│ 1  │ 审查endpoint input validation    │ running  │ 30s ago  │
│ 2  │ 添加migration rollback脚本       │ running  │ 45s ago  │
│ 3  │ 更新README环境变量说明           │ done ✓   │ 10s ago  │
└────┴──────────────────────────────────┴──────────┴──────────┘
```

**步骤4：查看完成的Session**

按Enter进入Session 3：

```
> ✅ README.md已更新：
> - 添加了DATABASE_URL环境变量说明
> - 添加了REDIS_URL配置
> - 新增"部署流程"章节
> - 创建了commit: "docs: update env vars and deployment guide"
```

### 4.4 后台Session的限制与注意事项

| 限制 | 说明 |
|------|------|
| 工作目录 | 每个Session在启动时的工作目录中运行 |
| 文件冲突 | 多个Session修改同一文件会产生冲突，需手动合并 |
| 上下文独立 | 各Session上下文完全隔离，互不可见 |
| 资源消耗 | 每个Session独立消耗API配额 |
| 自动清理 | 完成的Session默认保留24小时后自动清理 |

---

## 五、完整实战：构建无人值守的开发运维体系

### 5.1 架构总览

```mermaid
graph TB
    subgraph "GitHub仓库"
        CODE[源代码]
        PR[Pull Requests]
        ISSUES[Issues]
    end

    subgraph "Claude Code Routines（云端）"
        R1[每日安全扫描<br/>Schedule: 0 3 * * *]
        R2[依赖更新检查<br/>Schedule: 0 5 * * 1]
        R3[PR自动审查<br/>Trigger: PR opened]
        R4[Issue分诊<br/>Trigger: Issue opened]
        R5[安全热修复<br/>Trigger: API webhook]
    end

    subgraph "Agent View（本地）"
        AV[多会话仪表盘]
        S1[Feature开发]
        S2[Bug修复]
        S3[文档编写]
    end

    subgraph "通知"
        SLACK[Slack]
        GH_NOTIF[GitHub通知]
    end

    R1 -->|扫描报告| ISSUES
    R2 -->|更新PR| PR
    R3 -->|审查评论| PR
    R4 -->|标签+赋值| ISSUES
    R5 -->|修复PR| PR

    R1 -->|结果| SLACK
    R5 -->|告警| SLACK

    AV --> S1
    AV --> S2
    AV --> S3

    S1 -->|推送| CODE
    S2 -->|推送| CODE

    style R1 fill:#4CAF50,color:white
    style R2 fill:#2196F3,color:white
    style R3 fill:#FF9800,color:white
    style R4 fill:#9C27B0,color:white
    style R5 fill:#F44336,color:white
```

### 5.2 完整Routine配置模板

将以下模板放入仓库的 `.claude/routines/` 目录。

**security-scan/ROUTINE.md**：

```markdown
# Security Scan Routine

## 任务
扫描项目中所有依赖的安全漏洞。

## 步骤
1. 运行 `npm audit --json` 获取漏洞列表
2. 分析每个漏洞的影响范围和严重程度
3. 检查项目是否实际使用了受影响的代码路径
4. 对 critical/high 级别的漏洞：
   - 尝试自动升级到安全版本
   - 运行测试验证兼容性
   - 如果测试通过，创建修复PR
   - 如果需要breaking change，创建Issue说明
5. 生成安全报告，发布到GitHub Issue和Slack

## 输出格式
- Issue标题: `[Security] Weekly Scan - YYYY-MM-DD`
- 标签: `security`, `automated`
- 包含: 漏洞表格（包名/版本/CVE/严重性/状态）
```

**security-scan/trigger.yaml**：

```yaml
name: weekly-security-scan
description: "每周安全扫描依赖漏洞"
trigger:
  type: schedule
  schedule: "0 3 * * 1"    # 每周一UTC 3:00
repository:
  owner: my-org
  name: my-api-service
  branch: main
connectors:
  - github:
      permissions:
        issues: write
        pull_requests: write
        contents: write
  - slack:
      channels: ["#security-alerts"]
settings:
  timeout: 45m
  max_turns: 80
  model: claude-sonnet-4-6
```

### 5.3 Routine管理命令速查

```bash
# 列出所有Routine
claude routine list

# 查看单个Routine详情
claude routine info daily-code-review

# 手动触发（测试用）
claude routine run daily-code-review

# 查看执行历史
claude routine logs daily-code-review --last 10

# 暂停Routine
claude routine pause daily-code-review

# 恢复Routine
claude routine resume daily-code-review

# 删除Routine
claude routine delete daily-code-review

# 更新Routine配置
claude routine update daily-code-review --schedule "0 4 * * *"
```

---

## 六、成本与配额管理

### 6.1 各计划Routine配额

| 计划 | 月费 | Schedule Routine | API Routine | GitHub Routine | 月执行上限 |
|------|------|-----------------|-------------|----------------|-----------|
| Pro | $20 | 5个 | 3个 | 3个 | 200次 |
| Max 5x | $100 | 20个 | 10个 | 10个 | 2,000次 |
| Max 20x | $200 | 50个 | 25个 | 25个 | 10,000次 |
| Team Standard | $25/人 | 10个 | 5个 | 5个 | 500次 |
| Team Premium | $100/人 | 30个 | 15个 | 15个 | 5,000次 |

### 6.2 成本优化策略

**策略1：合并相近的Schedule**

```yaml
# 不好：两个独立Routine
- schedule: "0 2 * * *"   # 安全扫描
- schedule: "0 3 * * *"   # 依赖检查

# 好：合并为一个Routine
- schedule: "0 2 * * *"   # 安全扫描 + 依赖检查
```

ROUTINE.md中用section分隔：

```markdown
## Part 1: 安全扫描
（步骤省略）

## Part 2: 依赖检查
（步骤省略）
```

**策略2：用API触发器替代高频Schedule**

```yaml
# 不好：每5分钟轮询
schedule: "*/5 * * * *"

# 好：事件驱动，只在需要时触发
trigger:
  type: github
  events:
    - push    # 只在代码推送时触发
```

**策略3：设置合理的timeout和max_turns**

```yaml
settings:
  timeout: 10m      # 不要设置过长
  max_turns: 30     # 限制交互轮次
  model: claude-sonnet-4-6  # Sonnet比Opus便宜5-10倍
```

### 6.3 监控Routine消耗

```bash
# 查看本月Routine消耗
claude routine usage

# 输出示例：
# ┌────────────────────┬──────────┬─────────┬──────────┐
# │ Routine            │ Runs     │ Tokens  │ Cost     │
# ├────────────────────┼──────────┼─────────┼──────────┤
# │ daily-code-review  │ 22       │ 1.2M    │ $3.40    │
# │ pr-auto-review     │ 45       │ 890K    │ $2.10    │
# │ security-scan      │ 4        │ 2.1M    │ $5.80    │
# ├────────────────────┼──────────┼─────────┼──────────┤
# │ Total              │ 71       │ 4.19M   │ $11.30   │
# │ Quota Remaining    │          │         │ 129 runs │
# └────────────────────┴──────────┴─────────┴──────────┘
```

---

## 七、常见问题与排错

### 7.1 Routine执行失败

**问题：Routine触发后无响应**

```bash
# 检查Routine状态
claude routine info <name>

# 查看最近日志
claude routine logs <name> --last 5

# 常见原因：
# 1. GitHub OAuth过期 → claude connector auth github
# 2. 仓库权限不足 → 检查GitHub token scope
# 3. 超过月执行上限 → claude routine usage
```

**问题：Routine创建了错误的PR**

```bash
# 立即暂停Routine
claude routine pause <name>

# 回滚Routine创建的变更
git revert <routine-commit-hash>

# 检查ROUTINE.md的约束条件是否充分
# 在ROUTINE.md中添加更严格的限制：
```

```markdown
## 约束
- 绝对不要修改测试文件之外的文件
- 不要修改package.json的name/version字段
- 不要删除任何现有代码，只能添加
```

### 7.2 Agent View问题

**问题：后台Session意外终止**

```bash
# 检查Session详情
# 在Agent View中按 D 查看详情

# 常见原因：
# 1. 上下文窗口溢出 → 限制工作范围
# 2. 文件冲突 → 避免多Session操作同一文件
# 3. 命令超时 → 检查.bash_timeout设置
```

**问题：多个Session修改同一文件冲突**

解决方案：为每个Session分配独立的工作区域。

```bash
# 方式1：使用worktree隔离
claude --bg --worktree "重构auth模块" 
# 自动创建git worktree，完全隔离

# 方式2：在ROUTINE.md中明确文件范围
```

```markdown
## 文件范围
只允许修改以下目录：
- src/services/auth/
- tests/auth/

禁止修改：
- src/services/payment/  （另一个Session负责）
- package.json
```

---

## 八、最佳实践总结

### 8.1 Routine设计原则

| 原则 | 说明 | 反模式 |
|------|------|--------|
| 单一职责 | 每个Routine只做一件事 | 一个Routine又审查代码又修bug |
| 幂等安全 | 多次运行结果一致 | Routine每次创建新Issue而不检查已有 |
| 约束明确 | 在ROUTINE.md写清边界 | "帮我改进代码"这种模糊指令 |
| 渐进信任 | 先`--dry-run`再上线 | 直接上线未测试的Routine |
| 通知闭环 | 配置完成/失败通知 | Routine默默执行无人知晓 |

### 8.2 ROUTINE.md编写模板

```markdown
# [Routine名称]

## 目标
[一句话说明这个Routine要做什么]

## 输入
[描述触发时能获取什么信息]

## 步骤
1. [具体步骤1]
2. [具体步骤2]
3. [具体步骤3]

## 输出
[描述期望的输出：PR/Issue/评论/通知]

## 约束
- [禁止事项1]
- [禁止事项2]
- [边界条件]

## 失败处理
- [如果步骤X失败，应该做什么]
```

### 8.3 Agent View使用模式

| 模式 | 场景 | 操作 |
|------|------|------|
| 并行Feature | 同时开发多个独立功能 | `/bg` 推送，各自独立工作 |
| 研究+编码 | 一边搜索资料一边写代码 | 研究Session在后台，主会话编码 |
| 长任务+短任务 | 编译/测试在后台，主会话快速迭代 | 后台跑测试，前台继续改代码 |
| Code Review | 多个PR需要审查 | 每个PR一个Session并行审查 |

---

## 九、进阶：Routine + Agent View联动

最强大的工作模式是Routines和Agent View协同工作：

```mermaid
graph LR
    subgraph "云端自动化"
        R[Routine: PR自动审查]
        R2[Routine: Issue分诊]
    end

    subgraph "本地开发"
        AV[Agent View]
        S1[Session: 修bug]
        S2[Session: 写feature]
    end

    R -->|创建Review评论| PR[GitHub PR]
    PR -->|推送修复| S1
    R2 -->|分诊结果| ISSUE[GitHub Issue]
    ISSUE -->|认领任务| S2

    AV --> S1
    AV --> S2

    style R fill:#4CAF50,color:white
    style R2 fill:#9C27B0,color:white
    style AV fill:#FF9800,color:white
```

**典型工作日**：

1. **09:00** — Routine已在你睡觉时完成了安全扫描，发现2个critical漏洞，自动创建了Issue并通知Slack
2. **09:15** — 打开Agent View，推送一个后台Session处理安全漏洞修复
3. **09:20** — 主会话继续开发新feature
4. **10:00** — Routine自动审查了队友的PR，留下review评论
5. **10:30** — 后台Session完成安全修复，自动创建PR
6. **11:00** — 另一个Routine验证了安全修复PR的测试通过
7. **全天** — Agent View管理3-5个并行Session，你专注于最需要创造力的工作

---

## 十、Routines vs 替代方案对比

| 维度 | Routines | GitHub Actions + `-p` | 自建Worker | `/loop` |
|------|----------|----------------------|-----------|---------|
| 零运维 | ✅ | ❌ 需配置YAML | ❌ 全自建 | ❌ 本地 |
| 上下文理解 | ✅ 理解仓库 | ❌ 无状态 | ⚠️ 需自己实现 | ✅ |
| GitHub集成 | ✅ 原生 | ✅ 原生 | ❌ 需集成 | ⚠️ 手动 |
| 离线执行 | ✅ 云端 | ✅ 云端 | ✅ 云端 | ❌ |
| 成本透明度 | ✅ 内置 | ⚠️ Actions分钟 | ❌ 自行核算 | ✅ |
| 灵活性 | ⚠️ 受限 | ✅ 完全自由 | ✅ 完全自由 | ⚠️ |
| 适合场景 | 标准化任务 | 复杂流水线 | 定制化需求 | 即时迭代 |

选择建议：
- **标准化重复任务**（审查、扫描、分诊）→ Routines
- **复杂CI/CD流水线**（构建、部署、多环境）→ GitHub Actions
- **高度定制需求**（特殊API、内部系统）→ 自建Worker
- **即时探索性工作**（调试、实验）→ `/loop` 或Agent View

---

## 延伸阅读

- [Anthropic官方文档：Automate work with routines](https://code.claude.com/docs/en/routines) — Routine的权威参考
- [Anthropic官方文档：Manage multiple agents with agent view](https://code.claude.com/docs/en/agent-view) — Agent View完整指南
- [Claude Code Routines Cookbook (GitHub)](https://github.com/victorycross/claude-routines-cookbook) — 社区维护的Routine模板库
- [Builder.io: Claude Code Routines Tutorial](https://www.builder.io/blog/claude-code-routines) — 三种触发器的详细教程

---

## 参考来源

1. [Automate work with routines - Claude Code Docs](https://code.claude.com/docs/en/routines) — Anthropic官方Routine文档，定义了Routine的核心概念和三种触发器类型
2. [Manage multiple agents with agent view - Claude Code Docs](https://code.claude.com/docs/en/agent-view) — Agent View官方文档，涵盖`/bg`命令和多会话管理
3. [Claude Code Routines Tutorial: Schedule, API, and GitHub Triggers Explained - Builder.io](https://www.builder.io/blog/claude-code-routines) — 深入讲解三种触发器配置和实战案例
4. [Claude Code Agent View: the CLI Dashboard That Unifies All Sessions - Pasquale Pillitteri](https://pasqualepillitteri.it/en/news/2384/claude-code-agent-view-cli-dashboard-sessions-2026) — Agent View 2026年5月发布的详细分析
5. [Claude Code Routines: Scheduled and Event-Driven AI Automation - BetterStack](https://betterstack.com/community/guides/ai/claude-code-routines/) — 事件驱动自动化的实践指南
6. [victorycross/claude-routines-cookbook - GitHub](https://github.com/victorycross/claude-routines-cookbook) — 社区维护的Routine配置模板和最佳实践

---

## 训练营适用性评估

| 维度 | 评估 |
|------|------|
| 适合训练营类型 | AI开发工具进阶营、DevOps自动化训练营、团队效率提升工作坊 |
| 教学时长 | 4-6小时（含实操） |
| 学员基础要求 | 已完成Claude Code基础课程，熟悉Git操作，了解CI/CD概念 |
| 实操难度 | ⭐⭐⭐（中等，主要难点在ROUTINE.md的编写质量） |
| 硬件要求 | 无特殊要求，云端执行不依赖本地性能 |
| 分组建议 | 2-3人一组，每组管理一个GitHub仓库 |
| 考核方式 | 每组提交一个包含至少3个Routine的仓库配置，现场运行验证 |

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