返回

17. OpenClaw 实战:构建 AI 编程助手

本文演示如何使用 OpenClaw 构建 AI 编程助手,集成 Claude Code、Codex 等工具,实现代码审查、自动化测试、CI/CD 集成等功能,提升开发效率。

适用于 OpenClaw v2026.2 | 需要安装 coding-agentgit-workflowstest-runner 技能,有项目代码库访问权限。

TL;DR: 代码审查:Agent 分析 PR 变更生成审查报告。自动化测试:"test-runner": {"frameworks": ["jest", "vitest"]}。CI/CD 集成:Webhook 接收 GitHub/GitLab 事件。多项目管理:"projects": {"frontend": {...}, "backend": {...}}。核心命令:openclaw agent --message "审查这个 PR"

实战目标

构建一个能够:

  1. 代码审查自动化
  2. 运行测试并报告结果
  3. 生成代码文档
  4. 集成 CI/CD 流水线
  5. 多项目上下文切换

的 AI 编程助手。

安装必要技能

# 编程相关技能
openclaw skill install coding-agent
openclaw skill install debug-pro
openclaw skill install git-workflows
openclaw skill install docker-essentials

# 测试技能
openclaw skill install test-runner

代码审查自动化

配置代码审查

---
name: code-review-assistant
version: 1.0.0
description: Automated code review with OpenClaw
triggers:
  - code review
  - 代码审查
  - review
  - PR review
---

# Code Review Assistant

Automate code review for pull requests.

## Features

- Review code changes
- Check for common issues
- Suggest improvements
- Generate review comments

## Review Checklist

1. **Code Quality**
   - Naming conventions
   - Code structure
   - Error handling

2. **Security**
   - SQL injection
   - XSS vulnerabilities
   - Secret exposure

3. **Performance**
   - N+1 queries
   - Memory leaks
   - Inefficient algorithms

4. **Best Practices**
   - DRY principle
   - SOLID principles
   - Design patterns

代码审查场景

用户:审查这个 PR

Agent:好的,让我审查 PR #123...

[获取 PR 信息]
[分析代码变更]
[检查潜在问题]

## PR #123 审查报告

### 概览
- 分支: feature/user-search
- 变更: +156 -23
- 文件: 8 个

### 问题发现

**严重** (1):
- 🚨 `auth.js:45` - 密码明文存储风险

**警告** (3):
- ⚠️ `search.js:23` - 潜在的 SQL 注入
- ⚠️ `user.js:78` - 未处理的 Promise
- ⚠️ `utils.js:12` - 已弃用的 API

**建议** (5):
- 💡 考虑添加单元测试
- 💡 使用常量替代魔法数字
- 💡 建议添加错误边界
- 💡 考虑提取公共方法
- 💡 建议添加类型注释

### 代码亮点
- ✅ 良好的函数命名
- ✅ 合理的模块划分
- ✅ 适当的注释

需要我生成审查评论吗?

自动化测试

测试运行配置

{
  "skills": {
    "test-runner": {
      "frameworks": ["jest", "vitest", "pytest"],
      "coverage": {
        "enabled": true,
        "threshold": 80
      },
      "reporting": {
        "format": "markdown",
        "output": "test-report.md"
      }
    }
  }
}

测试场景

用户:运行测试并报告结果

Agent:正在运行测试...

[执行测试命令]
[收集测试结果]
[分析覆盖率]

## 测试报告

### 测试结果
- 总计: 45 个测试
- 通过: 42 ✅
- 失败: 2 ❌
- 跳过: 1 ⏭️

### 失败的测试

**1. UserSearch.test.js**

AssertionError: expected [] to equal [{id: 1, name: ’test’}]

建议: 检查数据库连接或 mock 数据

**2. Auth.test.js**

Timeout: Async callback not invoked within 5000ms

建议: 增加超时时间或检查异步逻辑

### 覆盖率

| 文件 | 语句 | 分支 | 函数 | 行 |
|-----|-----|-----|-----|-----|
| auth.js | 85% | 78% | 90% | 85% |
| search.js | 72% | 65% | 80% | 70% |
| user.js | 90% | 85% | 95% | 90% |
| **总计** | **82%** | **76%** | **88%** | **82%** |

是否需要我修复失败的测试?

CI/CD 集成

GitHub Actions 集成

# .github/workflows/openclaw-review.yml
name: OpenClaw Review

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup OpenClaw
        run: npm install -g openclaw@latest
        
      - name: Run Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          openclaw agent --message "Review PR #${{ github.event.pull_request.number }}" \
            --output review-comment.md
            
      - name: Post Comment
        uses: actions/github-script@v6
        with:
          script: |
            const fs = require('fs');
            const comment = fs.readFileSync('review-comment.md', 'utf8');
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: comment
            });

自动部署

用户:部署到 staging

Agent:正在部署到 staging 环境...

[拉取最新代码]
[运行测试]
[构建项目]
[部署到服务器]

## 部署报告

### 部署信息
- 环境: staging
- 分支: main
- 提交: abc1234
- 时间: 2026-02-26 15:30

### 部署步骤
1. ✅ 拉取代码
2. ✅ 安装依赖
3. ✅ 运行测试 (45/45 通过)
4. ✅ 构建项目
5. ✅ 部署到服务器

### 健康检查
- API: ✅ 正常
- 数据库: ✅ 连接正常
- Redis: ✅ 连接正常

### 访问地址
- URL: https://staging.example.com
- API: https://api-staging.example.com

部署成功!

多项目管理

项目配置

{
  "projects": {
    "frontend": {
      "path": "~/projects/frontend",
      "skills": ["coding-agent", "test-runner"],
      "context": "AGENTS.md"
    },
    "backend": {
      "path": "~/projects/backend",
      "skills": ["coding-agent", "docker-essentials"],
      "context": "AGENTS.md"
    },
    "mobile": {
      "path": "~/projects/mobile",
      "skills": ["coding-agent"],
      "context": "AGENTS.md"
    }
  }
}

项目切换

用户:切换到 backend 项目

Agent:已切换到 backend 项目。

当前项目信息:
- 名称: backend
- 路径: ~/projects/backend
- 技术: Python/FastAPI
- 最近提交: 添加用户认证

需要我帮你做什么?

代码生成

生成样板代码

用户:为 User 模型创建 CRUD API

Agent:好的,我将为 User 模型创建 CRUD API...

[分析现有代码结构]
[生成代码文件]

已生成以下文件:

**1. models/user.py**
```python
from pydantic import BaseModel
from datetime import datetime

class User(BaseModel):
    id: int
    name: str
    email: str
    created_at: datetime
    updated_at: datetime

class UserCreate(BaseModel):
    name: str
    email: str

class UserUpdate(BaseModel):
    name: str | None = None
    email: str | None = None

2. routers/users.py

from fastapi import APIRouter, HTTPException
from models.user import User, UserCreate, UserUpdate

router = APIRouter(prefix="/users", tags=["users"])

@router.get("/", response_model=list[User])
async def list_users(): ...

@router.get("/{user_id}", response_model=User)
async def get_user(user_id: int): ...

@router.post("/", response_model=User)
async def create_user(user: UserCreate): ...

@router.put("/{user_id}", response_model=User)
async def update_user(user_id: int, user: UserUpdate): ...

@router.delete("/{user_id}")
async def delete_user(user_id: int): ...

3. tests/test_users.py

from fastapi.testclient import TestClient

def test_list_users(): ...
def test_create_user(): ...
def test_update_user(): ...
def test_delete_user(): ...

需要我运行测试验证吗?


## 文档生成

### API 文档

用户:为这个 API 生成文档

Agent:正在分析 API 端点…

[扫描路由文件] [提取 API 信息] [生成文档]

API 文档

用户模块

GET /users

获取用户列表

参数

名称 类型 必需 说明
page int 页码
limit int 每页数量

响应

{
  "data": [User],
  "total": int,
  "page": int,
  "limit": int
}

POST /users

创建用户

请求体

{
  "name": "string",
  "email": "string"
}

响应

{
  "id": 1,
  "name": "string",
  "email": "string",
  "created_at": "2026-02-26T00:00:00Z",
  "updated_at": "2026-02-26T00:00:00Z"
}

是否保存到 docs/api.md?


## 故障排查

### CI/CD 问题

```bash
# 检查 CI/CD 状态
openclaw ci status

# 查看 CI/CD 日志
openclaw ci logs --last

# 重新运行失败的作业
openclaw ci retry

代码问题

# 分析代码问题
openclaw analyze --project backend

# 生成修复建议
openclaw suggest --file auth.js

小结

通过 OpenClaw 构建编程助手:

  • 代码审查:自动化 PR 审查
  • 测试运行:自动化测试和报告
  • CI/CD 集成:自动化部署流程
  • 多项目管理:快速切换上下文
  • 代码生成:样板代码生成
  • 文档生成:API 文档自动生成

更新记录

  • 2026-02-26:初版发布

系列导航