返回

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:初版發布

系列導航