prps-agentic-engineering

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PRP (Product Requirement Prompts) - Agentic Engineering

PRP(产品需求提示)- Agent化工程

Skill by ara.so — AI Agent Skills collection.
PRP (Product Requirement Prompt) is a methodology and toolset for AI-assisted development that combines traditional PRDs with curated codebase intelligence and autonomous validation loops. It enables AI agents to deliver production-ready code on the first pass by providing complete context, patterns, and validation commands.
Key Innovation: PRP = PRD + codebase intelligence + agent/runbook
ara.so提供的技能——AI Agent技能合集。
PRP(Product Requirement Prompt)是一套用于AI辅助开发的方法论和工具集,它将传统PRD(产品需求文档)与精选的代码库智能、自主验证循环相结合。通过提供完整的上下文、模式和验证命令,它能让AI Agent一次性交付可用于生产环境的代码。
核心创新:PRP = PRD + 代码库智能 + Agent/运行手册

Installation

安装

Option 1: Copy Commands to Existing Project

选项1:将命令复制到现有项目

bash
undefined
bash
undefined

From your project root

从项目根目录执行

git clone https://github.com/Wirasm/PRPs-agentic-eng.git /tmp/prp-temp cp -r /tmp/prp-temp/.claude/commands/prp-core .claude/commands/ rm -rf /tmp/prp-temp
undefined
git clone https://github.com/Wirasm/PRPs-agentic-eng.git /tmp/prp-temp cp -r /tmp/prp-temp/.claude/commands/prp-core .claude/commands/ rm -rf /tmp/prp-temp
undefined

Option 2: Clone Full Repository

选项2:克隆完整仓库

bash
git clone https://github.com/Wirasm/PRPs-agentic-eng.git
cd PRPs-agentic-eng
bash
git clone https://github.com/Wirasm/PRPs-agentic-eng.git
cd PRPs-agentic-eng

Setup Ralph Loop (Optional but Recommended)

设置Ralph循环(可选但推荐)

Create
.claude/settings.local.json
:
json
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/prp-ralph-stop.sh"
          }
        ]
      }
    ]
  }
}
Create
.claude/hooks/prp-ralph-stop.sh
:
bash
#!/bin/bash
if [ -f .claude/prp-ralph.state.md ]; then
    echo "Ralph loop still active - stopping"
    exit 1
fi
exit 0
Make executable:
bash
chmod +x .claude/hooks/prp-ralph-stop.sh
创建
.claude/settings.local.json
json
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/prp-ralph-stop.sh"
          }
        ]
      }
    ]
  }
}
创建
.claude/hooks/prp-ralph-stop.sh
bash
#!/bin/bash
if [ -f .claude/prp-ralph.state.md ]; then
    echo "Ralph loop still active - stopping"
    exit 1
fi
exit 0
设置可执行权限:
bash
chmod +x .claude/hooks/prp-ralph-stop.sh

Project Structure

项目结构

your-project/
├── .claude/
│   ├── commands/prp-core/        # PRP command files
│   ├── hooks/                    # Stop hooks for Ralph
│   ├── PRPs/                     # Generated artifacts
│   │   ├── prds/                 # Product requirement docs
│   │   ├── plans/                # Implementation plans
│   │   │   └── completed/        # Archived plans
│   │   ├── reports/              # Implementation reports
│   │   ├── issues/               # Issue investigations
│   │   │   └── completed/        # Archived investigations
│   │   └── reviews/              # PR reviews
│   └── settings.local.json       # Ralph hook configuration
├── PRPs/
│   ├── templates/                # PRP templates
│   │   ├── prp_base.md
│   │   ├── prp_story_task.md
│   │   └── prp_planning.md
│   └── ai_docs/                  # Curated library docs
└── CLAUDE.md                     # Project guidelines
your-project/
├── .claude/
│   ├── commands/prp-core/        # PRP命令文件
│   ├── hooks/                    # Ralph的停止钩子
│   ├── PRPs/                     # 生成的工件
│   │   ├── prds/                 # 产品需求文档
│   │   ├── plans/                # 实现计划
│   │   │   └── completed/        # 已归档计划
│   │   ├── reports/              # 实现报告
│   │   ├── issues/               # 问题调查
│   │   │   └── completed/        # 已归档调查
│   │   └── reviews/              # PR评审
│   └── settings.local.json       # Ralph钩子配置
├── PRPs/
│   ├── templates/                # PRP模板
│   │   ├── prp_base.md
│   │   ├── prp_story_task.md
│   │   └── prp_planning.md
│   └── ai_docs/                  # 精选库文档
└── CLAUDE.md                     # 项目指南

Core Workflow Commands

核心工作流命令

/prp-prd
- Interactive PRD Generator

/prp-prd
- 交互式PRD生成器

Creates a comprehensive Product Requirement Document with implementation phases.
bash
/prp-prd "user authentication system with JWT"
Output:
.claude/PRPs/prds/user-auth-system.prd.md
PRD Structure:
  • Executive Summary
  • Goals & Success Metrics
  • User Stories
  • Technical Requirements
  • Implementation Phases Table
  • Dependencies & Constraints
Implementation Phases Table:
markdown
| # | Phase | Description | Status | Parallel | Depends | PRP Plan |
|---|-------|-------------|--------|----------|---------|----------|
| 1 | Auth  | JWT tokens  | pending | -       | -       | -        |
| 2 | API   | Auth endpoints | pending | -    | 1       | -        |
| 3 | UI    | Login forms | pending | with 4  | 2       | -        |
| 4 | Tests | Test suite  | pending | with 3  | 2       | -        |
创建包含实现阶段的完整产品需求文档。
bash
/prp-prd "基于JWT的用户认证系统"
输出
.claude/PRPs/prds/user-auth-system.prd.md
PRD结构
  • 执行摘要
  • 目标与成功指标
  • 用户故事
  • 技术要求
  • 实现阶段表格
  • 依赖与约束
实现阶段表格
markdown
| # | 阶段 | 描述 | 状态 | 并行 | 依赖 | PRP计划 |
|---|-------|-------------|--------|----------|---------|----------|
| 1 | 认证 | JWT令牌 | pending | -       | -       | -        |
| 2 | API | 认证端点 | pending | -    | 1       | -        |
| 3 | UI | 登录表单 | pending | with 4  | 2       | -        |
| 4 | 测试 | 测试套件 | pending | with 3  | 2       | -        |

/prp-plan
- Create Implementation Plan

/prp-plan
- 创建实现计划

Generates detailed implementation plan from PRD phase or free-form description.
From PRD:
bash
/prp-plan .claude/PRPs/prds/user-auth-system.prd.md
Auto-selects next pending phase from PRD.
From Description:
bash
/prp-plan "add pagination to the users API endpoint"
Plan Structure:
markdown
undefined
根据PRD阶段或自由格式描述生成详细的实现计划。
基于PRD
bash
/prp-plan .claude/PRPs/prds/user-auth-system.prd.md
自动从PRD中选择下一个待处理阶段。
基于描述
bash
/prp-plan "为用户API端点添加分页功能"
计划结构
markdown
undefined

Implementation Plan: Feature Name

实现计划:功能名称

Context

上下文

  • Relevant files
  • Dependencies
  • Existing patterns
  • 相关文件
  • 依赖项
  • 现有模式

Tasks

任务

  1. Task description
    • Subtask details
    • Files to modify
  1. 任务描述
    • 子任务细节
    • 需要修改的文件

Validation Commands

验证命令

npm run type-check npm run lint npm test npm run build
npm run type-check npm run lint npm test npm run build

Success Criteria

成功标准

  • All tests pass
  • No type errors
  • Follows existing patterns
undefined
  • 所有测试通过
  • 无类型错误
  • 遵循现有模式
undefined

/prp-implement
- Execute Plan

/prp-implement
- 执行计划

Implements plan with validation loops.
bash
/prp-implement .claude/PRPs/plans/add-pagination.plan.md
Process:
  1. Reads plan and context
  2. Executes tasks in order
  3. Runs validation commands
  4. Creates implementation report
  5. Updates PRD status (if from PRD)
  6. Archives plan to
    completed/
Implementation Report (
.claude/PRPs/reports/feature-name.report.md
):
markdown
undefined
通过验证循环实现计划。
bash
/prp-implement .claude/PRPs/plans/add-pagination.plan.md
流程
  1. 读取计划和上下文
  2. 按顺序执行任务
  3. 运行验证命令
  4. 创建实现报告
  5. 更新PRD状态(若来自PRD)
  6. 将计划归档到
    completed/
实现报告
.claude/PRPs/reports/feature-name.report.md
):
markdown
undefined

Implementation Report: Feature Name

实现报告:功能名称

Summary

摘要

Brief overview of changes
变更的简要概述

Changes Made

已做变更

  • File modifications
  • New files created
  • Dependencies added
  • 文件修改
  • 新建文件
  • 添加的依赖

Validation Results

验证结果

✓ Type check passed ✓ Linting passed ✓ Tests passed (42 passing) ✓ Build successful
✓ 类型检查通过 ✓ 代码检查通过 ✓ 测试通过(42项通过) ✓ 构建成功

Challenges & Solutions

挑战与解决方案

  • Challenge faced
  • Solution applied
  • 遇到的挑战
  • 应用的解决方案

Next Steps

下一步

  • Suggested follow-ups
undefined
  • 建议的后续工作
undefined

Issue & Debug Workflow

问题与调试工作流

/prp-issue-investigate
- Analyze GitHub Issue

/prp-issue-investigate
- 分析GitHub问题

Creates investigation artifact for bug fixes or feature requests.
bash
/prp-issue-investigate 123
Investigation Artifact (
.claude/PRPs/issues/issue-123-investigation.md
):
markdown
undefined
为bug修复或功能请求创建调查工件。
bash
/prp-issue-investigate 123
调查工件
.claude/PRPs/issues/issue-123-investigation.md
):
markdown
undefined

Issue Investigation: #123

问题调查:#123

Issue Summary

问题摘要

[Auto-fetched from GitHub]
[从GitHub自动获取]

Root Cause Analysis

根本原因分析

  • What's happening
  • Why it's happening
  • Where in codebase
  • 当前现象
  • 问题原因
  • 代码中的位置

Proposed Solution

提议的解决方案

  1. Change X in file Y
  2. Add validation Z
  1. 修改文件Y中的X
  2. 添加验证Z

Implementation Plan

实现计划

  • Fix core issue
  • Add tests
  • Update docs
  • 修复核心问题
  • 添加测试
  • 更新文档

Validation

验证

npm test -- issue-123 npm run lint
undefined
npm test -- issue-123 npm run lint
undefined

/prp-issue-fix
- Execute Fix

/prp-issue-fix
- 执行修复

Implements fix from investigation artifact.
bash
/prp-issue-fix 123
Reads investigation, executes plan, creates PR-ready changes.
根据调查工件实现修复。
bash
/prp-issue-fix 123
读取调查内容,执行计划,创建可提交PR的变更。

/prp-debug
- Root Cause Analysis

/prp-debug
- 根本原因分析

Deep debugging with 5 Whys methodology.
bash
/prp-debug "users can't login after password reset"
Output:
markdown
undefined
使用5个为什么方法论进行深度调试。
bash
/prp-debug "用户重置密码后无法登录"
输出
markdown
undefined

Debug Report: Issue Description

调试报告:问题描述

5 Whys Analysis

5个为什么分析

  1. Why? Users see "invalid token" error
  2. Why? Token expired before email delivered
  3. Why? Email queue has 5min delay
  4. Why? Queue worker throttled
  5. Why? Rate limit too conservative
  1. 为什么?用户看到"无效令牌"错误
  2. 为什么?令牌在邮件送达前已过期
  3. 为什么?邮件队列有5分钟延迟
  4. 为什么?队列工作进程被限流
  5. 为什么?速率限制过于保守

Root Cause

根本原因

Queue worker rate limit set to 10/min, should be 100/min
队列工作进程速率限制设为10次/分钟,应改为100次/分钟

Fix

修复方案

Update
config/queue.js
rate limit configuration
更新
config/queue.js
中的速率限制配置

Validation

验证

  • Test password reset flow
  • Check email delivery time
undefined
  • 测试密码重置流程
  • 检查邮件送达时间
undefined

Git & Review Commands

Git与评审命令

/prp-commit
- Smart Commit

/prp-commit
- 智能提交

Natural language file targeting for commits.
bash
/prp-commit "fix validation bug in user registration" --files "auth, validation"
Auto-detects files matching keywords, creates semantic commit.
Commit Message Format:
fix(auth): fix validation bug in user registration

- Updated UserValidator.validate() to check email format
- Added test coverage for edge cases
- Fixes #123
用于提交的自然语言文件定位。
bash
/prp-commit "修复用户注册中的验证bug" --files "auth, validation"
自动检测匹配关键词的文件,创建语义化提交信息。
提交信息格式
fix(auth): fix validation bug in user registration

- Updated UserValidator.validate() to check email format
- Added test coverage for edge cases
- Fixes #123

/prp-pr
- Create Pull Request

/prp-pr
- 创建拉取请求(PR)

Generates PR with template support.
bash
/prp-pr "Add user authentication" --base main --head feature/auth
PR Template (if
.github/pull_request_template.md
exists):
markdown
undefined
生成支持模板的PR。
bash
/prp-pr "添加用户认证" --base main --head feature/auth
PR模板(若存在
.github/pull_request_template.md
):
markdown
undefined

Description

描述

Added JWT-based authentication system
添加了基于JWT的认证系统

Changes

变更

  • Implemented JWT token generation
  • Added auth middleware
  • Created login/logout endpoints
  • 实现了JWT令牌生成
  • 添加了认证中间件
  • 创建了登录/登出端点

Testing

测试

  • Unit tests pass
  • Integration tests pass
  • Manual testing completed
  • 单元测试通过
  • 集成测试通过
  • 手动测试完成

Checklist

检查清单

  • Code follows style guide
  • Self-review completed
  • Documentation updated
undefined
  • 代码遵循风格指南
  • 已完成自评审
  • 文档已更新
undefined

/prp-review
- PR Code Review

/prp-review
- PR代码评审

Comprehensive code review with best practices.
bash
/prp-review 456
Review Report (
.claude/PRPs/reviews/pr-456-review.md
):
markdown
undefined
结合最佳实践进行全面代码评审。
bash
/prp-review 456
评审报告
.claude/PRPs/reviews/pr-456-review.md
):
markdown
undefined

PR Review: #456

PR评审:#456

Summary

摘要

Well-structured implementation with minor suggestions
实现结构良好,仅有少量建议

Security Issues

安全问题

⚠️ HIGH: API key exposed in config file
  • Move to environment variable
⚠️ 高风险:配置文件中暴露了API密钥
  • 迁移到环境变量

Performance Concerns

性能问题

💡 MEDIUM: N+1 query in user list
  • Use eager loading
💡 中等:用户列表存在N+1查询
  • 使用预加载

Code Quality

代码质量

✓ GOOD: Clean separation of concerns ✓ GOOD: Comprehensive test coverage (94%) ⚠️ MINOR: Missing JSDoc for exported functions
✓ 良好:关注点分离清晰 ✓ 良好:测试覆盖率全面(94%) ⚠️ 次要:导出函数缺少JSDoc注释

Architecture

架构

✓ Follows existing patterns ✓ Proper error handling
✓ 遵循现有模式 ✓ 错误处理得当

Suggestions

建议

  1. Add input validation for email field
  2. Consider caching user lookup
  3. Extract magic numbers to constants
  1. 为邮箱字段添加输入验证
  2. 考虑缓存用户查询
  3. 将魔法数字提取为常量

Verdict

结论

✅ APPROVE with minor changes requested
undefined
✅ 批准,仅需少量变更
undefined

Ralph Loop - Autonomous Execution

Ralph Loop - 自主执行

Based on Geoffrey Huntley's "Ralph Wiggum" technique - self-referential loop that iterates until ALL validations pass.
基于Geoffrey Huntley的"Ralph Wiggum"技术——自引用循环,会迭代直到所有验证通过。

/prp-ralph
- Start Autonomous Loop

/prp-ralph
- 启动自主循环

bash
/prp-ralph .claude/PRPs/plans/add-user-auth.plan.md --max-iterations 20
Process:
  1. Implements plan tasks
  2. Runs ALL validation commands
  3. If any fail → analyzes, fixes, re-validates
  4. Repeats until ALL pass
  5. Outputs
    <promise>COMPLETE</promise>
  6. Exits gracefully
State Tracking (
.claude/prp-ralph.state.md
):
markdown
undefined
bash
/prp-ralph .claude/PRPs/plans/add-user-auth.plan.md --max-iterations 20
流程
  1. 执行计划任务
  2. 运行所有验证命令
  3. 若有失败→分析、修复、重新验证
  4. 重复直到全部通过
  5. 输出
    <promise>COMPLETE</promise>
  6. 优雅退出
状态跟踪
.claude/prp-ralph.state.md
):
markdown
undefined

Ralph Loop State

Ralph Loop状态

Plan: .claude/PRPs/plans/add-user-auth.plan.md Max Iterations: 20 Current Iteration: 7
计划:.claude/PRPs/plans/add-user-auth.plan.md 最大迭代次数:20 当前迭代次数:7

Last Validation Results

上次验证结果

✓ npm run type-check ✗ npm run lint (3 errors) ✓ npm test ✗ npm run build (compilation error)
✓ npm run type-check ✗ npm run lint (3个错误) ✓ npm test ✗ npm run build (编译错误)

Current Focus

当前重点

Fixing lint errors in src/auth/jwt.ts Resolving build error in import path
修复src/auth/jwt.ts中的lint错误 解决导入路径的构建错误

Learnings

经验总结

  • Arrow functions need explicit return types
  • Barrel imports must use .js extension
undefined
  • 箭头函数需要显式返回类型
  • 桶导入必须使用.js扩展名
undefined

/prp-ralph-cancel
- Stop Ralph Loop

/prp-ralph-cancel
- 停止Ralph循环

bash
/prp-ralph-cancel
Removes state file, allowing stop hook to exit gracefully.
bash
/prp-ralph-cancel
删除状态文件,允许停止钩子优雅退出。

Configuration

配置

CLAUDE.md - Project Guidelines

CLAUDE.md - 项目指南

Create
CLAUDE.md
in your project root:
markdown
undefined
在项目根目录创建
CLAUDE.md
markdown
undefined

Project Context for Claude Code

Claude Code的项目上下文

Tech Stack

技术栈

  • Node.js 20
  • TypeScript 5.3
  • Express 4.18
  • PostgreSQL 15
  • Node.js 20
  • TypeScript 5.3
  • Express 4.18
  • PostgreSQL 15

Code Patterns

代码模式

File Structure

文件结构

src/ features/ <feature>/ <feature>.controller.ts <feature>.service.ts <feature>.model.ts <feature>.test.ts
src/ features/ <feature>/ <feature>.controller.ts <feature>.service.ts <feature>.model.ts <feature>.test.ts

Naming Conventions

命名约定

  • Controllers:
    XController
  • Services:
    XService
  • Models:
    XModel
  • Files: kebab-case
  • 控制器:
    XController
  • 服务:
    XService
  • 模型:
    XModel
  • 文件:短横线命名法(kebab-case)

Error Handling

错误处理

typescript
try {
  await service.method();
} catch (error) {
  logger.error('Context', { error });
  throw new AppError('User message', 500);
}
typescript
try {
  await service.method();
} catch (error) {
  logger.error('Context', { error });
  throw new AppError('User message', 500);
}

Testing

测试

  • Use Jest
  • Mock external dependencies
  • Test edge cases
  • 使用Jest
  • 模拟外部依赖
  • 测试边缘情况

Validation Commands

验证命令

npm run type-check npm run lint npm test npm run build
npm run type-check npm run lint npm test npm run build

Environment Variables

环境变量

DATABASE_URL=${DATABASE_URL} JWT_SECRET=${JWT_SECRET} SMTP_HOST=${SMTP_HOST}
undefined
DATABASE_URL=${DATABASE_URL} JWT_SECRET=${JWT_SECRET} SMTP_HOST=${SMTP_HOST}
undefined

PRP Templates

PRP模板

Base Template (
PRPs/templates/prp_base.md
):
markdown
undefined
基础模板
PRPs/templates/prp_base.md
):
markdown
undefined

[Feature Name]

[功能名称]

Context

上下文

Current State

当前状态

  • Describe existing implementation
  • List relevant files
  • 描述现有实现
  • 列出相关文件

Goal

目标

  • What we're building
  • Why it's needed
  • 我们要构建的内容
  • 构建原因

Technical Approach

技术方案

Architecture

架构

  • Component structure
  • Data flow
  • 组件结构
  • 数据流

Implementation

实现步骤

  1. Step 1
  2. Step 2
  1. 步骤1
  2. 步骤2

Validation

验证

bash
npm run type-check
npm test
bash
npm run type-check
npm test

Success Criteria

成功标准

  • Criterion 1
  • Criterion 2
undefined
  • 标准1
  • 标准2
undefined

Real-World Examples

实际案例

Example 1: Adding API Pagination

案例1:添加API分页

Step 1: Create Plan
bash
/prp-plan "add cursor-based pagination to /api/users endpoint"
Generated Plan:
markdown
undefined
步骤1:创建计划
bash
/prp-plan "为/api/users端点添加基于游标分页"
生成的计划
markdown
undefined

Implementation Plan: API Users Pagination

实现计划:API用户分页

Context

上下文

  • File:
    src/features/users/users.controller.ts
  • Current: Returns all users (no pagination)
  • Pattern: Other endpoints use
    PaginationParams
    from
    src/utils/pagination.ts
  • 文件:
    src/features/users/users.controller.ts
  • 当前:返回所有用户(无分页)
  • 模式:其他端点使用
    src/utils/pagination.ts
    中的
    PaginationParams

Tasks

任务

  1. Update UsersController.list() signature
    • Add
      @Query() params: PaginationParams
    • Return
      PaginatedResponse<User>
  2. Modify UsersService.findAll()
    • Accept cursor and limit params
    • Use cursor-based query
    • Return hasMore flag
  3. Add tests
    • Test pagination edge cases
    • Test cursor validation
  1. 更新UsersController.list()签名
    • 添加
      @Query() params: PaginationParams
    • 返回
      PaginatedResponse<User>
  2. 修改UsersService.findAll()
    • 接受游标和限制参数
    • 使用基于游标的查询
    • 返回hasMore标志
  3. 添加测试
    • 测试分页边缘情况
    • 测试游标验证

Files to Modify

需要修改的文件

  • src/features/users/users.controller.ts
  • src/features/users/users.service.ts
  • src/features/users/users.test.ts
  • src/features/users/users.controller.ts
  • src/features/users/users.service.ts
  • src/features/users/users.test.ts

Validation Commands

验证命令

npm run type-check npm run lint npm test -- users npm run build
npm run type-check npm run lint npm test -- users npm run build

Success Criteria

成功标准

  • Endpoint accepts cursor and limit params
  • Returns paginated results with hasMore
  • All tests pass
  • No type errors

**Step 2: Implement with Ralph**
```bash
/prp-ralph .claude/PRPs/plans/api-users-pagination.plan.md --max-iterations 10
Ralph will:
  1. Update controller, service, tests
  2. Run validations
  3. Fix any type errors or test failures
  4. Re-validate until all pass
  5. Complete autonomously
  • 端点接受游标和限制参数
  • 返回包含hasMore的分页结果
  • 所有测试通过
  • 无类型错误

**步骤2:使用Ralph实现**
```bash
/prp-ralph .claude/PRPs/plans/api-users-pagination.plan.md --max-iterations 10
Ralph会:
  1. 更新控制器、服务和测试
  2. 运行验证
  3. 修复任何类型错误或测试失败
  4. 重新验证直到全部通过
  5. 自主完成

Example 2: Bug Fix Workflow

案例2:Bug修复工作流

GitHub Issue #789:
Title: Email notifications not sent for password reset
Labels: bug, priority:high

Users report not receiving password reset emails. 
Checked spam folders - emails aren't being sent at all.
Step 1: Investigate
bash
/prp-issue-investigate 789
Generated Investigation:
markdown
undefined
GitHub问题#789
标题:密码重置的邮件通知未发送
标签:bug, priority:high

用户反馈未收到密码重置邮件。
已检查垃圾邮件文件夹——邮件根本没有发送。
步骤1:调查
bash
/prp-issue-investigate 789
生成的调查结果
markdown
undefined

Issue Investigation: #789 - Email notifications not sent

问题调查:#789 - 邮件通知未发送

Issue Summary

问题摘要

Password reset emails not being sent to users
密码重置邮件未发送给用户

Code Analysis

代码分析

File:
src/features/auth/auth.service.ts
typescript
async resetPassword(email: string) {
  const token = generateToken();
  await this.userRepo.saveResetToken(email, token);
  
  // BUG: emailService.send() is async but not awaited
  this.emailService.send({
    to: email,
    subject: 'Password Reset',
    template: 'reset-password',
    data: { token }
  });
  
  return { success: true };
}
文件:
src/features/auth/auth.service.ts
typescript
async resetPassword(email: string) {
  const token = generateToken();
  await this.userRepo.saveResetToken(email, token);
  
  // BUG: emailService.send()是异步函数但未使用await
  this.emailService.send({
    to: email,
    subject: 'Password Reset',
    template: 'reset-password',
    data: { token }
  });
  
  return { success: true };
}

Root Cause

根本原因

Email sending is fire-and-forget. If it fails, no error is thrown and method returns success.
邮件发送是“即发即弃”模式。如果发送失败,不会抛出错误,方法直接返回成功。

Proposed Solution

提议的解决方案

  1. Await email sending
  2. Add error handling
  3. Add retry logic for transient failures
  1. 等待邮件发送完成(添加await)
  2. 添加错误处理
  3. 为临时故障添加重试逻辑

Implementation Plan

实现计划

  • Add
    await
    to emailService.send()
  • Wrap in try-catch with specific error
  • Add integration test for email sending
  • Update resetPassword to return email status
  • 为emailService.send()添加
    await
  • 用try-catch包裹并处理特定错误
  • 添加邮件发送的集成测试
  • 更新resetPassword以返回邮件发送状态

Validation

验证

npm test -- auth.service npm run type-check

**Step 2: Fix**
```bash
/prp-issue-fix 789
Step 3: Commit & PR
bash
/prp-commit "fix password reset email sending" --files auth
/prp-pr "Fix password reset email sending" --closes 789
npm test -- auth.service npm run type-check

**步骤2:修复**
```bash
/prp-issue-fix 789
步骤3:提交与创建PR
bash
/prp-commit "修复密码重置邮件发送问题" --files auth
/prp-pr "Fix password reset email sending" --closes 789

Example 3: Large Feature with Phases

案例3:分阶段的大型功能

Step 1: Create PRD
bash
/prp-prd "real-time chat system with websockets"
Generated PRD (excerpt):
markdown
undefined
步骤1:创建PRD
bash
/prp-prd "基于WebSocket的实时聊天系统"
生成的PRD(节选):
markdown
undefined

PRD: Real-time Chat System

PRD:实时聊天系统

Implementation Phases

实现阶段

#PhaseDescriptionStatusParallelDependsPRP Plan
1InfrastructureWebSocket server setuppending---
2Data ModelChat schema & migrationspending-1-
3Backend APIMessage CRUD endpointspending-2-
4WebSocket HandlersReal-time event handlerspending-3-
5Frontend UIChat interfacependingwith 64-
6Frontend StateRedux/state managementpendingwith 54-
7TestsE2E and unit testspending-5,6-

**Step 2: Implement Phase 1**
```bash
/prp-plan .claude/PRPs/prds/real-time-chat-system.prd.md
#阶段描述状态并行依赖PRP计划
1基础设施WebSocket服务器搭建pending---
2数据模型聊天模式与迁移pending-1-
3后端API消息CRUD端点pending-2-
4WebSocket处理器实时事件处理器pending-3-
5前端UI聊天界面pendingwith 64-
6前端状态Redux/状态管理pendingwith 54-
7测试E2E与单元测试pending-5,6-

**步骤2:实现阶段1**
```bash
/prp-plan .claude/PRPs/prds/real-time-chat-system.prd.md

Selects Phase 1 (first pending with no dependencies)

选择阶段1(第一个无依赖的待处理阶段)

/prp-ralph .claude/PRPs/plans/real-time-chat-phase-1.plan.md --max-iterations 15

**Step 3: Repeat for Each Phase**
```bash
/prp-plan .claude/PRPs/prds/real-time-chat-system.prd.md  # Phase 2
/prp-ralph .claude/PRPs/plans/real-time-chat-phase-2.plan.md
/prp-ralph .claude/PRPs/plans/real-time-chat-phase-1.plan.md --max-iterations 15

**步骤3:重复执行每个阶段**
```bash
/prp-plan .claude/PRPs/prds/real-time-chat-system.prd.md  # 阶段2
/prp-ralph .claude/PRPs/plans/real-time-chat-phase-2.plan.md

... continue through all phases

... 继续完成所有阶段


**Step 4: Parallel Phases (5 & 6)**

Use git worktrees for concurrent development:

```bash

**步骤4:并行阶段(5 & 6)**

使用git工作树进行并发开发:

```bash

Current branch has phases 1-4 complete

当前分支已完成阶段1-4

git worktree add -b phase-5-ui ../chat-phase-5 git worktree add -b phase-6-state ../chat-phase-6
git worktree add -b phase-5-ui ../chat-phase-5 git worktree add -b phase-6-state ../chat-phase-6

Terminal 1

终端1

cd ../chat-phase-5 /prp-plan .claude/PRPs/prds/real-time-chat-system.prd.md /prp-ralph .claude/PRPs/plans/real-time-chat-phase-5.plan.md
cd ../chat-phase-5 /prp-plan .claude/PRPs/prds/real-time-chat-system.prd.md /prp-ralph .claude/PRPs/plans/real-time-chat-phase-5.plan.md

Terminal 2

终端2

cd ../chat-phase-6 /prp-plan .claude/PRPs/prds/real-time-chat-system.prd.md /prp-ralph .claude/PRPs/plans/real-time-chat-phase-6.plan.md
cd ../chat-phase-6 /prp-plan .claude/PRPs/prds/real-time-chat-system.prd.md /prp-ralph .claude/PRPs/plans/real-time-chat-phase-6.plan.md

After both complete, merge both branches

两者完成后,合并两个分支

undefined
undefined

Common Patterns

常见模式

Pattern 1: Iterative Refinement

模式1:迭代优化

bash
undefined
bash
undefined

Create initial plan

创建初始计划

/prp-plan "add file upload feature"
/prp-plan "添加文件上传功能"

Review generated plan, add details to plan file manually

评审生成的计划,手动向计划文件添加细节

Then implement

然后执行实现

/prp-implement .claude/PRPs/plans/add-file-upload.plan.md
undefined
/prp-implement .claude/PRPs/plans/add-file-upload.plan.md
undefined

Pattern 2: Plan-Review-Implement

模式2:计划-评审-实现

bash
undefined
bash
undefined

Generate plan

生成计划

/prp-plan "refactor user service to use repository pattern"
/prp-plan "将用户服务重构为仓库模式"

Review plan artifact, discuss with team

评审计划工件,与团队讨论

Modify plan file if needed

如有需要修改计划文件

Then execute with validation

然后带验证执行

/prp-ralph .claude/PRPs/plans/refactor-user-service.plan.md
undefined
/prp-ralph .claude/PRPs/plans/refactor-user-service.plan.md
undefined

Pattern 3: Investigation-Driven Development

模式3:调查驱动开发

bash
undefined
bash
undefined

Investigate issue first

先调查问题

/prp-issue-investigate 456
/prp-issue-investigate 456

Review investigation

评审调查结果

Edit investigation artifact to add context

编辑调查工件添加上下文

Then fix

然后修复

/prp-issue-fix 456
undefined
/prp-issue-fix 456
undefined

Pattern 4: Validation-First Planning

模式4:验证优先规划

When creating plans, always include comprehensive validation:
markdown
undefined
创建计划时,始终包含全面的验证:
markdown
undefined

Validation Commands

验证命令

Type safety

类型安全

npm run type-check
npm run type-check

Code quality

代码质量

npm run lint npm run format:check
npm run lint npm run format:check

Functionality

功能

npm test npm run test:integration npm run test:e2e
npm test npm run test:integration npm run test:e2e

Build

构建

npm run build
npm run build

Runtime

运行时

npm run dev # Manual verification checklist
undefined
npm run dev # 手动验证清单
undefined

Troubleshooting

故障排除

Ralph Loop Not Stopping

Ralph Loop无法停止

Symptom: Ralph continues after
<promise>COMPLETE</promise>
Solution:
bash
undefined
症状:输出
<promise>COMPLETE</promise>
后Ralph仍继续运行
解决方案
bash
undefined

Verify hook is configured

验证钩子配置

cat .claude/settings.local.json
cat .claude/settings.local.json

Verify hook script exists and is executable

验证钩子脚本存在且可执行

ls -la .claude/hooks/prp-ralph-stop.sh chmod +x .claude/hooks/prp-ralph-stop.sh
ls -la .claude/hooks/prp-ralph-stop.sh chmod +x .claude/hooks/prp-ralph-stop.sh

Manual cancel

手动取消

/prp-ralph-cancel
undefined
/prp-ralph-cancel
undefined

Plans Not Archiving

计划未归档

Symptom: Completed plans stay in
plans/
directory
Solution: Ensure
.claude/PRPs/plans/completed/
directory exists:
bash
mkdir -p .claude/PRPs/plans/completed
症状:已完成的计划仍留在
plans/
目录中
解决方案: 确保
.claude/PRPs/plans/completed/
目录存在:
bash
mkdir -p .claude/PRPs/plans/completed

Validation Commands Fail

验证命令失败

Symptom: Ralph loop gets stuck on failing validation
Solution 1: Check validation commands are correct
bash
undefined
症状:Ralph循环卡在失败的验证上
解决方案1:检查验证命令是否正确
bash
undefined

Test commands manually

手动测试命令

npm run type-check npm run lint npm test

**Solution 2**: Add more specific validation
```markdown
npm run type-check npm run lint npm test

**解决方案2**:添加更具体的验证
```markdown

Validation Commands

验证命令

npm run type-check npm run lint -- --fix # Auto-fix lint issues npm test -- --testPathPattern=users # Only relevant tests
undefined
npm run type-check npm run lint -- --fix # 自动修复lint问题 npm test -- --testPathPattern=users # 仅运行相关测试
undefined

PRD Phase Selection Issues

PRD阶段选择问题

Symptom:
/prp-plan
doesn't auto-select next phase
Solution: Verify PRD table format is exact:
markdown
| # | Phase | Description | Status | Parallel | Depends | PRP Plan |
|---|-------|-------------|--------|----------|---------|----------|
Status must be exactly:
pending
,
in-progress
, or
complete
症状
/prp-plan
无法自动选择下一个阶段
解决方案:验证PRD表格格式是否准确:
markdown
| # | Phase | Description | Status | Parallel | Depends | PRP Plan |
|---|-------|-------------|--------|----------|---------|----------|
状态必须严格为:
pending
in-progress
complete

Missing Context in Plans

计划缺少上下文

Symptom: Plans lack necessary codebase context
Solution: Enhance
CLAUDE.md
with more patterns:
markdown
undefined
症状:计划缺少必要的代码库上下文
解决方案:在
CLAUDE.md
中添加更多模式:
markdown
undefined

Code Patterns

代码模式

Authentication

认证

Always use
AuthMiddleware.verify()
before protected routes
受保护路由前必须使用
AuthMiddleware.verify()

Database Queries

数据库查询

Use repository pattern from
src/repositories/base.repository.ts
使用
src/repositories/base.repository.ts
中的仓库模式

Error Responses

错误响应

typescript
throw new AppError(
  'User-facing message',
  HttpStatus.BAD_REQUEST,
  { details: 'debug info' }
);
undefined
typescript
throw new AppError(
  '面向用户的消息',
  HttpStatus.BAD_REQUEST,
  { details: '调试信息' }
);
undefined

Ralph Exceeds Max Iterations

Ralph超过最大迭代次数

Symptom: Ralph hits max iterations without completing
Solution 1: Increase iterations
bash
/prp-ralph plan.md --max-iterations 50
Solution 2: Break plan into smaller chunks
bash
undefined
症状:Ralph达到最大迭代次数仍未完成
解决方案1:增加迭代次数
bash
/prp-ralph plan.md --max-iterations 50
解决方案2:将计划拆分为更小的模块
bash
undefined

Instead of one large plan, create multiple focused plans

不要创建一个大型计划,而是创建多个聚焦的计划

/prp-plan "add user model and migration" /prp-plan "add user service layer" /prp-plan "add user API endpoints"
undefined
/prp-plan "添加用户模型与迁移" /prp-plan "添加用户服务层" /prp-plan "添加用户API端点"
undefined

Best Practices

最佳实践

1. Context is King

1. 上下文为王

Provide maximum relevant context in every artifact:
  • File paths (exact)
  • Existing code patterns
  • Dependencies and versions
  • Related documentation
在每个工件中提供尽可能多的相关上下文:
  • 精确的文件路径
  • 现有代码模式
  • 依赖与版本
  • 相关文档

2. Validation Loops

2. 验证循环

Every plan must have executable validation commands:
markdown
undefined
每个计划必须包含可执行的验证命令:
markdown
undefined

Validation Commands

验证命令

npm run type-check npm run lint npm test npm run build npm run e2e # if applicable
undefined
npm run type-check npm run lint npm test npm run build npm run e2e # 若适用
undefined

3. Bounded Scope

3. 范围边界

Each plan should be completable in one Ralph loop (< 20 iterations):
  • Small: Single function/component
  • Medium: Feature with tests
  • Large: Use PRD phases
每个计划应能在一个Ralph循环内完成(<20次迭代):
  • 小型:单个函数/组件
  • 中型:带测试的功能
  • 大型:使用PRD阶段

4. Information Density

4. 信息密度

Use keywords from codebase, not generic terms:
  • ✅ "Use
    UserRepository.findByEmail()
    "
  • ❌ "Query database for user"
使用代码库中的关键词,而非通用术语:
  • ✅ "使用
    UserRepository.findByEmail()
    "
  • ❌ "查询数据库获取用户"

5. Git Hygiene

5. Git规范

Commit after each completed plan:
bash
/prp-implement plan.md
/prp-commit "descriptive message" --files "relevant-keywords"
每个计划完成后提交:
bash
/prp-implement plan.md
/prp-commit "描述性消息" --files "相关关键词"

6. Review Before Merge

6. 合并前评审

Always review implementation reports:
bash
cat .claude/PRPs/reports/feature-name.report.md
始终评审实现报告:
bash
cat .claude/PRPs/reports/feature-name.report.md

Review changes, validation results, challenges

评审变更、验证结果、挑战

undefined
undefined

7. Curate AI Documentation

7. 整理AI文档

Keep
PRPs/ai_docs/
updated with relevant library docs:
PRPs/ai_docs/
├── express-best-practices.md
├── typescript-patterns.md
├── jest-testing.md
└── postgresql-queries.md
保持
PRPs/ai_docs/
更新相关库文档:
PRPs/ai_docs/
├── express-best-practices.md
├── typescript-patterns.md
├── jest-testing.md
└── postgresql-queries.md

8. Template Customization

8. 模板定制

Adapt templates to your project needs:
bash
undefined
根据项目需求调整模板:
bash
undefined

Create project-specific template

创建项目特定模板

cp PRPs/templates/prp_base.md PRPs/templates/prp_api_endpoint.md
cp PRPs/templates/prp_base.md PRPs/templates/prp_api_endpoint.md

Edit to include API-specific patterns

编辑以包含API特定模式

undefined
undefined

Advanced Usage

高级用法

Custom Subagents

自定义子Agent

Create specialized agents in
.claude/agents/
:
markdown
undefined
.claude/agents/
中创建专业Agent:
markdown
undefined

.claude/agents/database-expert.md

.claude/agents/database-expert.md

You are a database optimization expert.
When analyzing queries:
  1. Check for N+1 issues
  2. Verify indexes exist
  3. Suggest query optimizations
  4. Estimate query performance
Use EXPLAIN ANALYZE for all queries.

Reference in plans:
```markdown
你是一位数据库优化专家。
分析查询时:
  1. 检查N+1问题
  2. 验证索引是否存在
  3. 建议查询优化方案
  4. 估算查询性能
对所有查询使用EXPLAIN ANALYZE。

在计划中引用:
```markdown

Special Instructions

特殊说明

@database-expert review all queries in this implementation
undefined
@database-expert 评审本实现中的所有查询
undefined

PRD Templates for Domains

领域专用PRD模板

markdown
undefined
markdown
undefined

PRPs/templates/prp_prd_api.md

PRPs/templates/prp_prd_api.md

API Feature PRD Template

API功能PRD模板

API Specification

API规范

Endpoints

端点

  • GET /api/resource
  • POST /api/resource
  • GET /api/resource
  • POST /api/resource

Request/Response Schemas

请求/响应模式

typescript
interface CreateResourceRequest {
  name: string;
  description: string;
}
typescript
interface CreateResourceRequest {
  name: string;
  description: string;
}

Authentication

认证

  • Required: JWT token
  • Permissions:
    resource:create
  • 必填:JWT令牌
  • 权限:
    resource:create

Implementation Phases

实现阶段

#PhaseDescriptionStatusParallelDependsPRP Plan
1SchemaDatabase schemapending---
2RepositoryData access layerpending-1-
3ServiceBusiness logicpending-2-
4ControllerAPI endpointspending-3-
5TestsIntegration testspending-4-
undefined
#PhaseDescriptionStatusParallelDependsPRP Plan
1Schema数据库模式pending---
2Repository数据访问层pending-1-
3Service业务逻辑pending-2-
4ControllerAPI端点pending-3-
5Tests集成测试pending-4-
undefined

Metrics and Observability

指标与可观测性

Add to validation commands:
markdown
undefined
添加到验证命令:
markdown
undefined

Validation Commands

验证命令

npm run type-check npm run lint npm test npm run build
npm run type-check npm run lint npm test npm run build

Performance Validation

性能验证

npm run benchmark -- feature-name npm run lighthouse -- http://localhost:3000/feature
npm run benchmark -- feature-name npm run lighthouse -- http://localhost:3000/feature

Observability

可观测性

  • Check logs for errors
  • Verify metrics exported
  • Confirm traces captured
undefined
  • 检查日志中的错误
  • 验证指标已导出
  • 确认追踪已捕获
undefined

Integration with CI/CD

与CI/CD集成

Create validation script
.github/workflows/prp-validate.yml
:
yaml
name: PRP Validation

on:
  pull_request:
    paths:
      - '.claude/PRPs/plans/**'
      - '.claude/PRPs/reports/**'

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 20
      
      - name: Install dependencies
        run: npm ci
      
      - name: Run PRP validations
        run: |
          npm run type-check
          npm run lint
          npm test
          npm run build
      
      - name: Check for incomplete plans
        run: |
          if ls .claude/PRPs/plans/*.plan.md 2>/dev/null; then
            echo "❌ Incomplete plans found - all plans should be archived"
            exit 1
          fi

The goal is one-pass implementation success through comprehensive context.
For support and workshops: https://www.rasmuswiding.com/
创建验证脚本
.github/workflows/prp-validate.yml
yaml
name: PRP Validation

on:
  pull_request:
    paths:
      - '.claude/PRPs/plans/**'
      - '.claude/PRPs/reports/**'

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 20
      
      - name: Install dependencies
        run: npm ci
      
      - name: Run PRP validations
        run: |
          npm run type-check
          npm run lint
          npm test
          npm run build
      
      - name: Check for incomplete plans
        run: |
          if ls .claude/PRPs/plans/*.plan.md 2>/dev/null; then
            echo "❌ Incomplete plans found - all plans should be archived"
            exit 1
          fi

目标是通过全面的上下文实现一次性成功交付。
获取支持与培训:https://www.rasmuswiding.com/