Skill: smxtx/bu-bu-wei-ying (version 2.0.0)

--- name: bu-bu-wei-ying description: 复杂APP开发统一技能 - 融合敏捷开发、CI/CD、DevOps的最佳实践，核心理念"每步必测、每层必验、环环相扣、层层守护" category: devops metadata: openclaw: requires: bins: - bash - git - npm always: false emoji: "🏰" version: 2.0.0 --- # 步步为营 - 复杂APP开发统一技能 当用户要求进行复杂应用开发、构建 CI/CD 流程、执行 DevOps 任务时，按以下步骤引导。 ## 核心原则 ### 修正原则（最高优先级） **只修正指定问题和相关联代码，不改变其他代码** - 只修改用户明确指出的问题代码 - 只修改与问题直接相关的关联代码 - 已正确运行的功能不得被修改 - 每次修改前确认变更范围 - 修改后验证其他功能未被影响 ### 开发理念 **每步必测** → 每次代码变更必须运行测试 **每层必验** → 每个模块必须通过验证 **环环相扣** → 各阶段必须有序衔接 **层层守护** → 每层必须有保护机制 --- ## 开发流程检查清单 ### 1. 需求分析阶段 - [ ] 明确功能需求和非功能需求 - [ ] 拆分任务为可执行的子任务 - [ ] 预估时间和资源 - [ ] 确定验收标准 ### 2. 代码开发阶段 - [ ] 创建功能分支 `git checkout -b feature/xxx` - [ ] 编写代码并遵循编码规范 - [ ] 编写单元测试（覆盖率 > 80%） - [ ] 运行本地 lint/static analysis - [ ] 进行代码审查 ### 3. 构建阶段 - [ ] 本地构建成功 `npm run build` / `docker build` - [ ] 运行集成测试 - [ ] 安全扫描 `npm audit` / `trivy image` - [ ] 生成构建产物（Docker 镜像/二进制文件） ### 4. 测试阶段 - [ ] 部署到预发布环境 - [ ] 执行 E2E 测试 - [ ] 性能测试（响应时间、并发） - [ ] 回归测试 - [ ] 获取测试报告 ### 5. 发布阶段 - [ ] 创建 Release Tag - [ ] 更新 CHANGELOG - [ ] 执行灰度发布（5% → 25% → 100%） - [ ] 监控系统指标 - [ ] 准备回滚方案 ### 6. 运维监控阶段 - [ ] 确认监控告警正常 - [ ] 检查日志聚合 - [ ] 验证备份机制 - [ ] 文档更新 --- ## 常用命令参考 ### 包管理 ```bash npm install # 安装依赖 npm run build # 构建项目 npm test # 运行测试 npm run lint # 代码检查 npm run audit # 安全审计 ``` ### Docker ```bash docker build -t app:v1 . # 构建镜像 docker run -d app:v1 # 运行容器 docker-compose up -d # 启动服务栈 docker logs -f <container> # 查看日志 ``` ### Git 工作流 ```bash git checkout -b feature/xxx # 创建功能分支 git add . && git commit -m "feat: xxx" git push origin feature/xxx # 推送分支 git merge main # 合并主干 git tag v1.0.0 && git push --tags # 打标签 ``` ### CI/CD 检查 ```bash curl -I http://localhost:PORT/health # 健康检查 netstat -tlnp | grep PORT # 端口检查 tail -100 /var/log/app.log # 查看日志 ``` --- ## 使用示例 ### 示例1：开发新功能 ``` 用户：帮我开发一个用户注册功能 Agent： 1. 创建分支 feature/user-registration 2. 编写 API、数据库模型、单元测试 3. 运行测试确保通过 4. 构建镜像并推送到仓库 5. 执行灰度发布 ``` ### 示例2：排查部署问题 ``` 用户：生产环境部署失败了 Agent： 1. 检查构建日志 2. 验证环境变量配置 3. 测试数据库连接 4. 检查网络/端口 5. 执行回滚（如需要） ``` --- ## 自动化脚本 检查清单脚本位于 `scripts/checklist.sh`： | 命令 | 说明 | |------|------| | `verify-fix <文件> [哈希]` | 验证修正范围（核心安全检查） | | `dev-check` | 完整开发检查（lint + test + build） | | `docker-build [镜像] [标签]` | Docker 构建 + 安全扫描 | | `health [主机] [端口] [端点]` | HTTP 健康检查 | | `canary [镜像] [阶段]` | 灰度发布（默认: 5,25,100%） | | `rollback [命名空间] [部署]` | 回滚到上一个稳定版本 | | `coverage [阈值]` | 测试覆盖率检查（默认: 80%） | | `all` | 执行全部检查 | --- ## 监控模板 从 `templates/` 目录导入监控规则： ### Grafana (grafana-alerts.json) - 应用错误率告警 - 响应延迟告警 - 服务可用性告警 - CPU/内存/磁盘使用率 ### Datadog (datadog-alerts.json) - 错误率告警 - 延迟告警 - 健康检查失败 - 基础设施指标 - 日志错误激增检测 --- ## 验证步骤 每次任务完成后，必须执行： 1. **自检清单** - 对照检查清单确认每项完成 2. **结果报告** - 向用户汇报关键指标（测试覆盖率、构建状态等） 3. **下一步建议** - 提出优化建议或后续行动

path: README.md
content: # 🏰 步步为营 (Bu Bu Wei Ying)

> 复杂APP开发统一技能 - 融合敏捷开发、CI/CD、DevOps的最佳实践

[![License: MIT-0](https://img.shields.io/badge/License-MIT--0-blue.svg)](LICENSE)
[![ClawHub](https://img.shields.io/badge/ClawHub-Skill-green.svg)](https://clawhub.com/skill/bu-bu-wei-ying)

## 核心理念

| 原则 | 说明 |
|------|------|
| **每步必测** | 每次代码变更必须运行测试 |
| **每层必验** | 每个模块必须通过验证 |
| **环环相扣** | 各阶段必须有序衔接 |
| **层层守护** | 每层必须有保护机制 |

## ⚡ 核心原则：修正范围控制

**只修正指定问题和相关联代码，不改变其他代码**

- ✅ 只修改用户明确指出的问题代码
- ✅ 只修改与问题直接相关的关联代码  
- ✅ 已正确运行的功能不得被修改
- ✅ 每次修改前确认变更范围
- ✅ 修改后验证其他功能未被影响

## 功能特性

- 📋 **完整开发流程检查清单** - 6阶段标准化开发流程
- 🔧 **自动化脚本** - 一键执行验证、构建、发布、回滚
- 📊 **监控模板** - Grafana/Datadog 告警规则开箱即用
- 🌐 **多语言支持** - 中文 + 英文双语版本
- 🛡️ **风险矩阵** - Pitfall 提示避免常见错误

## 安装

### ClawHub (推荐)
```bash
clawhub install bu-bu-wei-ying
```

### 手动安装
```bash
# 克隆仓库
git clone https://github.com/YOUR_USERNAME/bu-bu-wei-ying.git

# 或复制 SKILL.md 到你的 skills 目录
cp SKILL.md ~/.hermes/skills/bu-bu-wei-ying/SKILL.md
```

## 使用方法

### 场景 1：开发新功能
```
用户：帮我开发一个用户注册功能
Agent：
1. 创建分支 feature/user-registration
2. 编写 API、数据库模型、单元测试
3. 运行测试确保通过
4. 构建镜像并推送到仓库
5. 执行灰度发布
```

### 场景 2：排查部署问题
```
用户：生产环境部署失败了
Agent：
1. 检查构建日志
2. 验证环境变量配置
3. 测试数据库连接
4. 检查网络/端口
5. 执行回滚（如需要）
```

## 开发流程检查清单

### 1. 需求分析阶段
- [ ] 明确功能需求和非功能需求
- [ ] 拆分任务为可执行的子任务
- [ ] 预估时间和资源
- [ ] 确定验收标准

### 2. 代码开发阶段
- [ ] 创建功能分支 `git checkout -b feature/xxx`
- [ ] 编写代码并遵循编码规范
- [ ] 编写单元测试（覆盖率 > 80%）
- [ ] 运行本地 lint/static analysis
- [ ] 进行代码审查

### 3. 构建阶段
- [ ] 本地构建成功
- [ ] 运行集成测试
- [ ] 安全扫描
- [ ] 生成构建产物

### 4. 测试阶段
- [ ] 部署到预发布环境
- [ ] 执行 E2E 测试
- [ ] 性能测试
- [ ] 回归测试

### 5. 发布阶段
- [ ] 创建 Release Tag
- [ ] 更新 CHANGELOG
- [ ] 执行灰度发布（5% → 25% → 100%）
- [ ] 监控系统指标
- [ ] 准备回滚方案

### 6. 运维监控阶段
- [ ] 确认监控告警正常
- [ ] 检查日志聚合
- [ ] 验证备份机制
- [ ] 文档更新

## 自动化脚本

```bash
# 验证修正范围（核心安全功能）
./scripts/checklist.sh verify-fix <file>

# 完整开发检查
./scripts/checklist.sh dev-check

# Docker 构建 + 安全扫描
./scripts/checklist.sh docker-build [镜像名] [标签]

# HTTP 健康检查
./scripts/checklist.sh health [主机] [端口] [端点]

# 灰度发布（默认: 5,25,100%）
./scripts/checklist.sh canary [镜像] [阶段]

# 回滚
./scripts/checklist.sh rollback [命名空间] [部署]

# 测试覆盖率检查
./scripts/checklist.sh coverage [阈值]

# 执行全部检查
./scripts/checklist.sh all
```

## 监控模板

### Grafana
导入 `templates/grafana-alerts.json`，包含：
- 应用错误率 > 5%
- P95 响应延迟 > 1s
- 服务不可用
- CPU/内存/磁盘使用率

### Datadog
导入 `templates/datadog-alerts.json`，包含：
- 错误率告警
- 延迟告警
- 健康检查失败
- 日志错误激增检测

## 项目结构

```
bu-bu-wei-ying/
├── SKILL.md              # 中文主版本
├── SKILL-en.md          # 英文版本
├── LICENSE              # MIT-0 许可证
├── README.md            # 本文件
├── scripts/
│   └── checklist.sh      # 自动化脚本
└── templates/
    ├── grafana-alerts.json    # Grafana 监控模板
    └── datadog-alerts.json    # Datadog 监控模板
```

## 许可证

本项目采用 [MIT No Attribution](LICENSE) 许可证：

- ✅ 可自由使用、修改、分发
- ✅ 包括商业用途
- ❌ 无需署名
- ❌ 不提供任何担保

## 贡献

欢迎提交 Issue 和 Pull Request！

---

**🏰 步步为营 - 每步必测，每层必验，环环相扣，层层守护**


path: scripts/checklist.sh
content: #!/bin/bash
# ============================================================
# 步步为营 - 开发流程自动化脚本集
# 用于复杂APP开发、CI/CD、DevOps场景
# ============================================================

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目根目录（根据实际情况修改）
PROJECT_ROOT="${PROJECT_ROOT:-.}"

# -------------------------------------------------------
# 辅助函数
# -------------------------------------------------------

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

check_command() {
    if ! command -v "$1" &> /dev/null; then
        log_error "命令 '$1' 未找到，请先安装"
        exit 1
    fi
}

# -------------------------------------------------------
# 1. 修正验证脚本 - 核心安全检查
# 确保只修改了指定问题和相关代码
# -------------------------------------------------------

verify_fix_scope() {
    local target_file="$1"
    local baseline_hash="${2:-}"
    
    log_info "执行修正范围验证..."
    
    if [ ! -f "$target_file" ]; then
        log_error "目标文件不存在: $target_file"
        return 1
    fi
    
    # 检查是否有未追踪的更改
    if git rev-parse --git-dir > /dev/null 2>&1; then
        local changed_files=$(git diff --name-only HEAD)
        local file_count=$(echo "$changed_files" | grep -c "$target_file" || true)
        
        if [ "$file_count" -gt 1 ]; then
            log_warn "检测到多个文件被修改，可能影响其他功能"
            echo "修改的文件列表:"
            echo "$changed_files"
        else
            log_success "修正范围正常，仅修改了目标文件"
        fi
    fi
    
    # 检查目标文件的语法
    log_info "验证文件语法..."
    if [[ "$target_file" == *.py ]]; then
        python3 -m py_compile "$target_file" && log_success "Python 语法正确" || return 1
    elif [[ "$target_file" == *.js ]]; then
        node --check "$target_file" && log_success "JavaScript 语法正确" || return 1
    elif [[ "$target_file" == *.ts ]]; then
        npx tsc --noEmit "$target_file" 2>/dev/null && log_success "TypeScript 语法正确" || log_warn "TypeScript 检查跳过"
    fi
    
    return 0
}

# -------------------------------------------------------
# 2. 开发流程脚本
# -------------------------------------------------------

dev_full_check() {
    log_info "=== 执行完整开发检查 ==="
    
    cd "$PROJECT_ROOT"
    
    # 依赖检查
    log_info "检查依赖..."
    if [ -f "package.json" ]; then
        npm install 2>&1 | tail -5
    fi
    
    # Lint 检查
    log_info "运行代码检查..."
    if [ -f "package.json" ]; then
        npm run lint 2>/dev/null || npm run lint:fix 2>/dev/null || log_warn "Lint 配置未找到"
    fi
    
    # 测试
    log_info "运行测试..."
    if [ -f "package.json" ]; then
        npm test 2>&1 | tail -20
    fi
    
    # 构建
    log_info "执行构建..."
    if [ -f "package.json" ]; then
        npm run build 2>&1 | tail -10
    fi
    
    log_success "完整检查完成"
}

# -------------------------------------------------------
# 3. Docker 构建脚本
# -------------------------------------------------------

docker_build_check() {
    local image_name="${1:-app}"
    local image_tag="${2:-latest}"
    
    log_info "=== Docker 构建流程 ==="
    
    # 安全扫描
    log_info "执行 Trivy 安全扫描（基础镜像）..."
    if command -v trivy &> /dev/null; then
        trivy image --ignore-unfixed alpine:latest 2>/dev/null || log_warn "安全扫描跳过"
    else
        log_warn "Trivy 未安装，跳过安全扫描"
    fi
    
    # 构建
    log_info "构建 Docker 镜像..."
    docker build -t "${image_name}:${image_tag}" .
    
    # 检查
    log_info "验证镜像..."
    docker run --rm "${image_name}:${image_tag}" --help 2>/dev/null || \
    docker run --rm "${image_name}:${image_tag}" sh -c "echo 'Image OK'" || \
    log_warn "镜像验证跳过（无入口命令）"
    
    log_success "Docker 构建完成: ${image_name}:${image_tag}"
}

# -------------------------------------------------------
# 4. 健康检查脚本
# -------------------------------------------------------

health_check() {
    local host="${1:-localhost}"
    local port="${2:-8080}"
    local endpoint="${3:-/health}"
    
    log_info "=== 健康检查: http://${host}:${port}${endpoint} ==="
    
    local response=$(curl -s -w "\n%{http_code}" "http://${host}:${port}${endpoint}" 2>/dev/null)
    local body=$(echo "$response" | sed '$d')
    local status=$(echo "$response" | tail -1)
    
    if [ "$status" == "200" ]; then
        log_success "健康检查通过"
        echo "$body"
        return 0
    else
        log_error "健康检查失败 (HTTP $status)"
        echo "$body"
        return 1
    fi
}

# -------------------------------------------------------
# 5. 灰度发布脚本
# -------------------------------------------------------

canary_release() {
    local image_name="${1:-app}"
    local stages="${2:-5,25,100}"
    
    log_info "=== 灰度发布流程 ==="
    
    IFS=',' read -ra STAGES <<< "$stages"
    for stage in "${STAGES[@]}"; do
        log_info "部署到 ${stage}% 流量..."
        
        # 这里需要根据实际的 K8s 或负载均衡配置修改
        # kubectl patch deployment app -p "{\"spec\":{\"replicas\":${stage}}}"
        
        sleep 5
        log_success "阶段 ${stage}% 部署完成"
        
        if [ "$stage" != "100" ]; then
            read -p "确认无异常后按 Enter 继续..."
        fi
    done
    
    log_success "灰度发布完成"
}

# -------------------------------------------------------
# 6. 回滚脚本
# -------------------------------------------------------

rollback() {
    local namespace="${1:-default}"
    local deployment="${2:-app}"
    
    log_warn "=== 执行回滚 ==="
    read -p "确认回滚到上一个稳定版本? (y/n) " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "执行回滚..."
        kubectl rollout undo deployment/"$deployment" -n "$namespace"
        kubectl rollout status deployment/"$deployment" -n "$namespace"
        log_success "回滚完成"
    else
        log_info "取消回滚"
    fi
}

# -------------------------------------------------------
# 7. 测试覆盖率检查
# -------------------------------------------------------

check_coverage() {
    local threshold="${1:-80}"
    
    log_info "=== 检查测试覆盖率（阈值: ${threshold}%）==="
    
    if [ -f "coverage/coverage-summary.json" ]; then
        local coverage=$(cat coverage/coverage-summary.json | grep -o '"percent":[0-9.]*' | grep -o '[0-9.]*' | head -1)
        
        if [ -n "$coverage" ]; then
            log_info "当前覆盖率: ${coverage}%"
            
            if (( $(echo "$coverage >= $threshold" | bc -l) )); then
                log_success "覆盖率达标"
                return 0
            else
                log_error "覆盖率未达标 (需要 ${threshold}%)"
                return 1
            fi
        fi
    fi
    
    log_warn "覆盖率报告未找到"
    return 0
}

# -------------------------------------------------------
# 主菜单
# -------------------------------------------------------

show_help() {
    echo "步步为营 - 开发自动化脚本"
    echo ""
    echo "用法: $0 <命令> [参数]"
    echo ""
    echo "命令:"
    echo "  verify-fix <文件> [基准哈希]  - 验证修正范围"
    echo "  dev-check                      - 完整开发检查"
    echo "  docker-build [镜像名] [标签]   - Docker 构建"
    echo "  health [主机] [端口] [端点]     - 健康检查"
    echo "  canary [镜像] [阶段]            - 灰度发布"
    echo "  rollback [命名空间] [部署名]    - 回滚"
    echo "  coverage [阈值]                - 覆盖率检查"
    echo "  all                            - 执行全部检查"
    echo ""
}

case "$1" in
    verify-fix)
        verify_fix_scope "$2" "$3"
        ;;
    dev-check)
        dev_full_check
        ;;
    docker-build)
        docker_build_check "$2" "$3"
        ;;
    health)
        health_check "$2" "$3" "$4"
        ;;
    canary)
        canary_release "$2" "$3"
        ;;
    rollback)
        rollback "$2" "$3"
        ;;
    coverage)
        check_coverage "$2"
        ;;
    all)
        dev_full_check
        health_check
        check_coverage
        ;;
    *)
        show_help
        ;;
esac


path: SKILL-en.md
content: ---
name: bu-bu-wei-ying
description: Complex APP Development Unified Skill - Integrates best practices from Agile, CI/CD, and DevOps. Core principle: Test Every Step, Verify Every Layer, Link Every Stage, Protect Every Level.
category: devops
metadata:
  openclaw:
    requires:
      bins:
        - bash
        - git
        - npm
    always: false
    emoji: "🏰"
version: 2.0.0
---

# Bu Bu Wei Ying - Complex APP Development Unified Skill

Use this skill when the user asks for complex application development, CI/CD pipeline setup, or DevOps tasks.

## Core Principles

### Fix Scope Principle (Highest Priority)
**Only fix the specified problem and related code - never modify other code**
- Only modify code that the user explicitly identified as problematic
- Only modify code directly related to the problem
- Never modify features that are already working correctly
- Confirm scope of changes before each modification
- Verify other functionality is not affected after changes

### Development Philosophy
**Test Every Step** → Run tests after every code change  
**Verify Every Layer** → Validate each module  
**Link Every Stage** → Ensure proper sequencing  
**Protect Every Level** → Implement safeguards at every layer

---

## Development Flow Checklist

### 1. Requirements Analysis
- [ ] Define functional and non-functional requirements
- [ ] Break down tasks into executable subtasks
- [ ] Estimate time and resources
- [ ] Define acceptance criteria

### 2. Code Development
- [ ] Create feature branch `git checkout -b feature/xxx`
- [ ] Write code following coding standards
- [ ] Write unit tests (> 80% coverage target)
- [ ] Run local lint/static analysis
- [ ] Code review

### 3. Build Phase
- [ ] Local build succeeds `npm run build` / `docker build`
- [ ] Run integration tests
- [ ] Security scan `npm audit` / `trivy image`
- [ ] Generate artifacts (Docker image/binary)

### 4. Testing Phase
- [ ] Deploy to staging environment
- [ ] Execute E2E tests
- [ ] Performance testing (latency, concurrency)
- [ ] Regression testing
- [ ] Obtain test report

### 5. Release Phase
- [ ] Create Release Tag
- [ ] Update CHANGELOG
- [ ] Execute canary release (5% → 25% → 100%)
- [ ] Monitor metrics
- [ ] Prepare rollback plan

### 6. Operations & Monitoring Phase
- [ ] Confirm monitoring alerts are active
- [ ] Check log aggregation
- [ ] Verify backup mechanisms
- [ ] Update documentation

---

## Common Commands Reference

### Package Management
```bash
npm install           # Install dependencies
npm run build        # Build project
npm test             # Run tests
npm run lint         # Lint code
npm run audit       # Security audit
```

### Docker
```bash
docker build -t app:v1 .              # Build image
docker run -d app:v1                  # Run container
docker-compose up -d                  # Start service stack
docker logs -f <container>            # View logs
```

### Git Workflow
```bash
git checkout -b feature/xxx            # Create feature branch
git add . && git commit -m "feat: xxx"
git push origin feature/xxx           # Push branch
git merge main                        # Merge main
git tag v1.0.0 && git push --tags     # Create tag
```

### CI/CD Checks
```bash
curl -I http://localhost:PORT/health   # Health check
netstat -tlnp | grep PORT             # Port check
tail -100 /var/log/app.log            # View logs
```

---

## Usage Examples

### Example 1: Develop New Feature
```
User: Help me develop a user registration feature
Agent:
1. Create branch feature/user-registration
2. Write API, database models, unit tests
3. Run tests to ensure passing
4. Build and push image to registry
5. Execute canary release
```

### Example 2: Troubleshoot Deployment Issue
```
User: Production deployment failed
Agent:
1. Check build logs
2. Verify environment variable configuration
3. Test database connectivity
4. Check network/ports
5. Execute rollback if needed
```

---

## Pitfall Risk Matrix

| Risk | Prevention |
|------|------------|
| Insufficient test coverage | Require coverage report |
| Security vulnerabilities | Must run security scan |
| Missing configuration | Use env var template checklist |
| Canary release failure | Prepare and verify rollback script |
| Missing logs | Confirm log aggregation is configured |
| Monitoring blind spots | Verify monitoring alerts before release |

---

## Verification Steps

After each task completion, execute:

1. **Self-Check Checklist** - Verify each item against the checklist
2. **Result Report** - Report key metrics (test coverage, build status, etc.)
3. **Next Steps** - Suggest optimizations or follow-up actions

---

## Automation Scripts

Available scripts in `scripts/checklist.sh`:

| Command | Description |
|---------|-------------|
| `verify-fix <file>` | Verify fix scope (core safety check) |
| `dev-check` | Full development check (lint + test + build) |
| `docker-build [name] [tag]` | Docker build with security scan |
| `health [host] [port] [path]` | Health check HTTP endpoint |
| `canary [image] [stages]` | Canary release (default: 5,25,100%) |
| `rollback [ns] [deploy]` | Rollback to previous stable version |
| `coverage [threshold]` | Check test coverage (default: 80%) |
| `all` | Execute all checks |

---

## Monitoring Templates

Import monitoring rules from `templates/` directory:

### Grafana (grafana-alerts.json)
- Application error rate
- Response latency
- Service availability
- CPU/Memory/Disk usage

### Datadog (datadog-alerts.json)
- Error rate alerts
- Latency alerts
- Health check failures
- Infrastructure metrics
- Log error surge detection


path: templates/datadog-alerts.json
content: {
  "version": 2,
  "created_at": "2026-04-17T00:00:00.000Z",
  "monitors": [
    {
      "id": 999999999,
      "type": "metric alert",
      "name": "[步步为营] 应用错误率过高",
      "message": "应用 5xx 错误率超过 5%，当前值: {{threshold}}%\n\n{{#is_alert}}请检查应用日志并评估是否需要回滚{{/is_alert}}\n\n{{#is_recovery}}错误率已恢复{{/is_recovery}}",
      "tags": ["bu-bu-wei-ying", "app", "error-rate"],
      "query": "min(last_5m):sum:http_requests_total{status:5xx}.as_rate() / sum:http_requests_total.as_rate() * 100 > 5",
      "options": {
        "thresholds": {
          "critical": 5,
          "warning": 2
        },
        "notify_audit": true,
        "notify_no_data": true,
        "no_data_timeframe": 5,
        "renotify_interval": 60,
        "silenced": {}
      },
      "priority": 2
    },
    {
      "id": 999999998,
      "type": "metric alert",
      "name": "[步步为营] 应用响应延迟过高",
      "message": "P95 响应时间超过 1 秒，当前值: {{threshold}}ms\n\n建议检查:\n- 数据库查询性能\n- 外部服务调用\n- 缓存命中情况",
      "tags": ["bu-bu-wei-ying", "app", "latency"],
      "query": "min(last_5m):p95:http_request_duration_seconds{*}.as_count() * 1000 > 1000",
      "options": {
        "thresholds": {
          "critical": 1000,
          "warning": 500
        },
        "notify_audit": true,
        "notify_no_data": true,
        "no_data_timeframe": 5,
        "renotify_interval": 60,
        "silenced": {}
      },
      "priority": 3
    },
    {
      "id": 999999997,
      "type": "metric alert",
      "name": "[步步为营] 服务健康检查失败",
      "message": "服务健康检查端点返回非 200 状态\n\n{{#is_alert}}请立即检查:\n1. 应用进程是否存活\n2. 健康检查端点日志\n3. 相关依赖服务状态{{/is_alert}}",
      "tags": ["bu-bu-wei-ying", "app", "health-check"],
      "query": "min(last_2m):max:health_check{*} by {instance} <= 0",
      "options": {
        "thresholds": {
          "critical": 0
        },
        "notify_audit": true,
        "notify_no_data": true,
        "no_data_timeframe": 2,
        "renotify_interval": 5,
        "silenced": {}
      },
      "priority": 1
    },
    {
      "id": 999999996,
      "type": "metric alert",
      "name": "[步步为营] CPU 使用率过高",
      "message": "CPU 使用率超过 80%，当前值: {{threshold}}%",
      "tags": ["bu-bu-wei-ying", "infra", "cpu"],
      "query": "min(last_10m):max:system.cpu.user{*} by {host} > 80",
      "options": {
        "thresholds": {
          "critical": 80,
          "warning": 70
        },
        "notify_audit": true,
        "notify_no_data": true,
        "no_data_timeframe": 10,
        "renotify_interval": 60,
        "silenced": {}
      },
      "priority": 3
    },
    {
      "id": 999999995,
      "type": "metric alert",
      "name": "[步步为营] 内存使用率过高",
      "message": "内存使用率超过 85%，当前值: {{threshold}}%",
      "tags": ["bu-bu-wei-ying", "infra", "memory"],
      "query": "min(last_10m):max:system.mem.used{*} by {host} / max:system.mem.total{*} by {host} * 100 > 85",
      "options": {
        "thresholds": {
          "critical": 85,
          "warning": 75
        },
        "notify_audit": true,
        "notify_no_data": true,
        "no_data_timeframe": 10,
        "renotify_interval": 60,
        "silenced": {}
      },
      "priority": 3
    },
    {
      "id": 999999994,
      "type": "metric alert",
      "name": "[步步为营] 磁盘使用率过高",
      "message": "磁盘使用率超过 90%，当前值: {{threshold}}%",
      "tags": ["bu-bu-wei-ying", "infra", "disk"],
      "query": "min(last_5m):max:system.disk.in_use{*} by {host,device} > 0.9",
      "options": {
        "thresholds": {
          "critical": 0.9,
          "warning": 0.8
        },
        "notify_audit": true,
        "notify_no_data": true,
        "no_data_timeframe": 5,
        "renotify_interval": 60,
        "silenced": {}
      },
      "priority": 2
    },
    {
      "id": 999999993,
      "type": "metric alert",
      "name": "[步步为营] 日志错误激增",
      "message": "检测到日志中错误数量激增\n\n{{#is_alert}}建议检查最近的代码变更和部署情况{{/is_alert}}",
      "tags": ["bu-bu-wei-ying", "app", "logs"],
      "query": "min(last_5m):sum:log.error{*}.as_count() > 100",
      "options": {
        "thresholds": {
          "critical": 100,
          "warning": 50
        },
        "notify_audit": true,
        "notify_no_data": true,
        "no_data_timeframe": 5,
        "renotify_interval": 30,
        "silenced": {}
      },
      "priority": 2
    }
  ],
  "dashboards": [
    {
      "title": "步步为营 - 应用概览",
      "description": "应用核心指标监控仪表板",
      "widgets": [
        {
          "definition": {
            "type": "timeseries",
            "title": "请求率",
            "requests": [
              {
                "q": "sum:http_requests_total{*}.as_rate()"
              }
            ]
          },
          "layout": {"x": 0, "y": 0, "width": 6, "height": 4}
        },
        {
          "definition": {
            "type": "timeseries",
            "title": "响应延迟 (P95)",
            "requests": [
              {
                "q": "p95:http_request_duration_seconds{*}.as_count() * 1000"
              }
            ]
          },
          "layout": {"x": 6, "y": 0, "width": 6, "height": 4}
        },
        {
          "definition": {
            "type": "timeseries",
            "title": "错误率",
            "requests": [
              {
                "q": "sum:http_requests_total{status:5xx}.as_rate() / sum:http_requests_total.as_rate() * 100"
              }
            ]
          },
          "layout": {"x": 0, "y": 4, "width": 6, "height": 4}
        },
        {
          "definition": {
            "type": "timeseries",
            "title": "活跃连接数",
            "requests": [
              {
                "q": "sum:http_connections_active{*}"
              }
            ]
          },
          "layout": {"x": 6, "y": 4, "width": 6, "height": 4}
        }
      ]
    }
  ]
}


path: templates/grafana-alerts.json
content: {
  "groups": [
    {
      "name": "bu-bu-wei-ying-application",
      "folder": "步步为营",
      "interval": "30s",
      "rules": [
        {
          "uid": "app-error-rate-high",
          "title": "应用错误率过高",
          "condition": "C",
          "data": [
            {
              "refId": "A",
              "datasourceUid": "prometheus",
              "model": {
                "expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m])) * 100",
                "instant": true,
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "A"
              }
            },
            {
              "refId": "B",
              "datasourceUid": "__expr__",
              "model": {
                "conditions": [
                  {
                    "evaluator": {
                      "params": [5],
                      "type": "gt"
                    },
                    "operator": {
                      "type": "and"
                    },
                    "query": {
                      "params": ["A"]
                    },
                    "reducer": {
                      "params": [],
                      "type": "last"
                    },
                    "type": "query"
                  }
                ],
                "datasource": {
                  "type": "__expr__",
                  "uid": "__expr__"
                },
                "expression": "A",
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "reducer": "last",
                "refId": "B",
                "type": "reduce"
              }
            },
            {
              "refId": "C",
              "datasourceUid": "__expr__",
              "model": {
                "conditions": [
                  {
                    "evaluator": {
                      "params": [5],
                      "type": "gt"
                    },
                    "operator": {
                      "type": "and"
                    },
                    "query": {
                      "params": ["B"]
                    },
                    "reducer": {
                      "params": [],
                      "type": "last"
                    },
                    "type": "query"
                  }
                ],
                "datasource": {
                  "type": "__expr__",
                  "uid": "__expr__"
                },
                "expression": "B",
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "C",
                "type": "threshold"
              }
            }
          ],
          "noDataState": "NoData",
          "execErrState": "Error",
          "for": "5m",
          "annotations": {
            "description": "应用 5xx 错误率超过 5%，当前值: {{ $values.B.Value }}%",
            "runbook_url": "https://wiki.example.com/runbooks/high-error-rate",
            "summary": "应用错误率告警"
          },
          "labels": {
            "severity": "critical",
            "team": "backend"
          }
        },
        {
          "uid": "app-latency-high",
          "title": "应用响应延迟过高",
          "condition": "C",
          "data": [
            {
              "refId": "A",
              "datasourceUid": "prometheus",
              "model": {
                "expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le)) * 1000",
                "instant": true,
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "A"
              }
            },
            {
              "refId": "C",
              "datasourceUid": "__expr__",
              "model": {
                "conditions": [
                  {
                    "evaluator": {
                      "params": [1000],
                      "type": "gt"
                    },
                    "operator": {
                      "type": "and"
                    },
                    "query": {
                      "params": ["A"]
                    },
                    "reducer": {
                      "params": [],
                      "type": "last"
                    },
                    "type": "query"
                  }
                ],
                "datasource": {
                  "type": "__expr__",
                  "uid": "__expr__"
                },
                "expression": "A",
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "C",
                "type": "threshold"
              }
            }
          ],
          "noDataState": "NoData",
          "execErrState": "Error",
          "for": "5m",
          "annotations": {
            "description": "P95 响应时间超过 1 秒，当前值: {{ $values.A.Value }}ms",
            "runbook_url": "https://wiki.example.com/runbooks/high-latency",
            "summary": "响应延迟告警"
          },
          "labels": {
            "severity": "warning",
            "team": "backend"
          }
        },
        {
          "uid": "app-down",
          "title": "应用服务不可用",
          "condition": "C",
          "data": [
            {
              "refId": "A",
              "datasourceUid": "prometheus",
              "model": {
                "expr": "up{job=\"app\"}",
                "instant": true,
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "A"
              }
            },
            {
              "refId": "C",
              "datasourceUid": "__expr__",
              "model": {
                "conditions": [
                  {
                    "evaluator": {
                      "params": [0.5],
                      "type": "lt"
                    },
                    "operator": {
                      "type": "and"
                    },
                    "query": {
                      "params": ["A"]
                    },
                    "reducer": {
                      "params": [],
                      "type": "last"
                    },
                    "type": "query"
                  }
                ],
                "datasource": {
                  "type": "__expr__",
                  "uid": "__expr__"
                },
                "expression": "A",
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "C",
                "type": "threshold"
              }
            }
          ],
          "noDataState": "NoData",
          "execErrState": "Alerting",
          "for": "1m",
          "annotations": {
            "description": "应用实例宕机或无法访问",
            "runbook_url": "https://wiki.example.com/runbooks/service-down",
            "summary": "服务不可用告警"
          },
          "labels": {
            "severity": "critical",
            "team": "backend"
          }
        }
      ]
    },
    {
      "name": "bu-bu-wei-ying-infra",
      "folder": "步步为营",
      "interval": "1m",
      "rules": [
        {
          "uid": "cpu-usage-high",
          "title": "CPU 使用率过高",
          "condition": "C",
          "data": [
            {
              "refId": "A",
              "datasourceUid": "prometheus",
              "model": {
                "expr": "100 - (avg by(instance) (rate(node_cpu_seconds_total{mode=\"idle\"}[5m])) * 100)",
                "instant": true,
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "A"
              }
            },
            {
              "refId": "C",
              "datasourceUid": "__expr__",
              "model": {
                "conditions": [
                  {
                    "evaluator": {
                      "params": [80],
                      "type": "gt"
                    },
                    "operator": {
                      "type": "and"
                    },
                    "query": {
                      "params": ["A"]
                    },
                    "reducer": {
                      "params": [],
                      "type": "last"
                    },
                    "type": "query"
                  }
                ],
                "datasource": {
                  "type": "__expr__",
                  "uid": "__expr__"
                },
                "expression": "A",
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "C",
                "type": "threshold"
              }
            }
          ],
          "noDataState": "NoData",
          "execErrState": "Error",
          "for": "10m",
          "annotations": {
            "description": "CPU 使用率超过 80%，当前值: {{ $values.A.Value }}%",
            "summary": "CPU 告警"
          },
          "labels": {
            "severity": "warning",
            "team": "infra"
          }
        },
        {
          "uid": "memory-usage-high",
          "title": "内存使用率过高",
          "condition": "C",
          "data": [
            {
              "refId": "A",
              "datasourceUid": "prometheus",
              "model": {
                "expr": "100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))",
                "instant": true,
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "A"
              }
            },
            {
              "refId": "C",
              "datasourceUid": "__expr__",
              "model": {
                "conditions": [
                  {
                    "evaluator": {
                      "params": [85],
                      "type": "gt"
                    },
                    "operator": {
                      "type": "and"
                    },
                    "query": {
                      "params": ["A"]
                    },
                    "reducer": {
                      "params": [],
                      "type": "last"
                    },
                    "type": "query"
                  }
                ],
                "datasource": {
                  "type": "__expr__",
                  "uid": "__expr__"
                },
                "expression": "A",
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "C",
                "type": "threshold"
              }
            }
          ],
          "noDataState": "NoData",
          "execErrState": "Error",
          "for": "10m",
          "annotations": {
            "description": "内存使用率超过 85%，当前值: {{ $values.A.Value }}%",
            "summary": "内存告警"
          },
          "labels": {
            "severity": "warning",
            "team": "infra"
          }
        },
        {
          "uid": "disk-usage-high",
          "title": "磁盘使用率过高",
          "condition": "C",
          "data": [
            {
              "refId": "A",
              "datasourceUid": "prometheus",
              "model": {
                "expr": "100 - (node_filesystem_avail_bytes{mountpoint=\"/\"} / node_filesystem_size_bytes{mountpoint=\"/\"} * 100)",
                "instant": true,
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "A"
              }
            },
            {
              "refId": "C",
              "datasourceUid": "__expr__",
              "model": {
                "conditions": [
                  {
                    "evaluator": {
                      "params": [90],
                      "type": "gt"
                    },
                    "operator": {
                      "type": "and"
                    },
                    "query": {
                      "params": ["A"]
                    },
                    "reducer": {
                      "params": [],
                      "type": "last"
                    },
                    "type": "query"
                  }
                ],
                "datasource": {
                  "type": "__expr__",
                  "uid": "__expr__"
                },
                "expression": "A",
                "intervalMs": 1000,
                "maxDataPoints": 43200,
                "refId": "C",
                "type": "threshold"
              }
            }
          ],
          "noDataState": "NoData",
          "execErrState": "Error",
          "for": "5m",
          "annotations": {
            "description": "磁盘使用率超过 90%，当前值: {{ $values.A.Value }}%",
            "summary": "磁盘告警"
          },
          "labels": {
            "severity": "critical",
            "team": "infra"
          }
        }
      ]
    }
  ]
}


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)