---
name: prd-writing
description: "Write PRD (Product Requirements Documents) by analyzing existing codebases, then gather decisions interactively. Use when user asks for a requirements doc, feature spec, or technical design document for a new feature."
version: 1.0.0
author: Hermes Agent
metadata:
  hermes:
    tags: [prd, requirements, product, design, planning, specification]
    related_skills: [plan, writing-plans, dogfood, content-ops-agent]
---

# PRD Writing

Write Product Requirements Documents for new features by analyzing the existing codebase first, then interactively gathering user decisions on open design questions.

## When to Use

- User asks to write a requirements doc, PRD, feature spec, or technical design
- User wants to add a new feature and needs a structured specification
- User says "写需求文档", "写PRD", "design doc", "feature spec"

## Workflow

### Phase 0: Independent Analysis & Recommendations (when user asks)

When the user asks for your opinion, suggestions, or "你觉得呢" / "有什么建议":
- **Do NOT just praise the plan** — give genuine critical analysis
- Identify over-engineering, unnecessary complexity, or design flaws
- Propose alternative approaches with concrete reasoning
- Present as a discussion, not a verdict — the user makes the final call
- This happens BEFORE drafting the PRD, not after

Example: User wants per-profile temperature settings → suggest global parameters instead, because switching providers rarely requires changing generation params. Reduce UI complexity.

### Phase 1: Codebase Analysis (silent, before asking anything)

Gather context by reading the relevant code. Do NOT ask the user to explain their codebase — read it yourself.

1. **Project structure**: `find` to enumerate files, identify tech stack
2. **Data models**: Read database schema, model definitions, migrations
3. **API routes**: Read route files to understand existing endpoints
4. **Frontend templates**: Read HTML/JS to understand current UI patterns
5. **Config**: Read config files for environment variables, service architecture
6. **API specs**: Check if any API specification docs exist
7. **Related docs**: README, implementation reports, existing specs

Report findings to the user before proceeding to Phase 2.

### Phase 2: Structured Planning (execution map)

After codebase analysis, produce a structured plan before drafting the PRD. This phase decomposes the feature into addressable components, identifies decision points, and defines completion criteria.

**Planning steps**:

1. **Lock goal**: From user requirements, extract the single sentence this PRD serves.
2. **Define scope**: Write clear boundaries — what's in, what's out, assumptions, constraints.
3. **Decompose components**: Break the feature into independent, addressable modules. Each component should:
   - Have clear boundaries with other components
   - Contribute to the final feature
   - Be independently implementable
4. **Identify decision points**: List all design decisions that need user input. Mark which ones block other decisions.
5. **Map dependencies**: Which components depend on others? What's the implementation order?
6. **Define completion criteria**: What conditions must be met before this PRD is ready for implementation?

**Output**: A structured plan (inline or in `/tmp/prd_plan.json`) that serves as the execution map for drafting:

```json
{
  "feature_goal": "一句话目标",
  "scope": {
    "in_scope": ["包含的功能"],
    "out_of_scope": ["明确不做的"],
    "assumptions": ["执行假设"],
    "constraints": ["技术/资源约束"]
  },
  "components": [
    {
      "id": "c1",
      "name": "组件名称",
      "description": "职责和边界",
      "changes_required": ["需要改动的文件或模块"],
      "depends_on": [],
      "decision_points": ["需要用户确认的设计决策"]
    }
  ],
  "decision_points": [
    {
      "id": "dp1",
      "question": "需要用户确认的问题",
      "options": ["A: 选项1", "B: 选项2"],
      "recommendation": "推荐选项及理由",
      "blocks": ["dp2"],
      "blocks_components": ["c2"]
    }
  ],
  "execution_order": ["c1", "c2"],
  "completion_criteria": ["所有决策点已确认", "所有组件有明确方案"]
}
```

**Why this phase matters**: Without structured planning, PRDs tend to miss dependencies, repeat decisions, or have inconsistent component designs. The plan forces explicit thinking before writing.

### Phase 3: Draft PRD

Write the document covering:

1. **Background & Motivation**: Current state analysis, what's missing
2. **User Stories**: "As a [role], I want [feature] so that [benefit]"
3. **Interaction Design**: Wireframes (ASCII art), user flows
4. **API Design**: Request/response schemas, error handling
5. **Data Model**: New tables/fields, migrations needed
6. **Security & Limits**: Auth requirements, rate limiting, input validation
7. **Technical Risks**: What could go wrong, mitigation strategies
8. **Implementation Priority**: Phased approach with time estimates
9. **Appendix**: File inventory, competitor analysis

### Phase 4: Decision Gathering (interactive)

Extract all open design decisions from the draft. Present them **one by one**:

- Ask each decision as a separate message
- Include your recommendation with brief reasoning
- Wait for user's answer before asking the next
- If user asks for your recommendation, give one clearly
- After all decisions are collected, update the document in one batch

### Phase 5: Finalize

Write the decisions back into the document as a "Decision Record" table.

## PRD Structure Template

```markdown
# {Feature Name} 需求文档

> **版本**: v1.0
> **日期**: {date}
> **状态**: 📝 待评审

---

## 一、背景与动机
### 1.1 现状分析 (table: what exists)
### 1.2 缺失的能力 (table: current vs ideal)

## 二、功能定义
### 2.1 功能描述
### 2.2 用户故事
### 2.3 交互设计 (ASCII wireframes)
### 2.4 API 设计
### 2.5 数据模型 (SQL DDL)
### 2.6 安全与限制 (table)

## 三、技术方案
### 架构图
### 环境变量
### 前端实现

## 四、优先级与排期 (phased table)

## 五、技术风险与决策点
### 5.1 决策记录 (table: decision → result → notes)
### 5.2 技术风险 (table: risk → impact → mitigation)

## 六、附录
### A. 相关文件清单
### B. 参考竞品
```

## Phase 6: PRD Review (after user says "评审"/"review")

When asked to review a PRD, use this checklist to find gaps before the user does. Read the full document, then produce a structured review with severity-rated findings.

### Review Checklist

**Data Model** (most common source of 🔴 issues):
- [ ] Are all referenced tables actually defined? (e.g., "settings table" mentioned but no schema)
- [ ] Do display values map to actual identifiers? (e.g., "Claude" in DB → `claude-sonnet-4-20250514` for API)
- [ ] Are placeholder/syntax conventions defined? (e.g., template variable syntax `{{var}}`)
- [ ] Do FK cascades match intended deletion behavior?
- [ ] Are there namespace collisions? (e.g., two tables using `key` as URL slug)

**API Design**:
- [ ] Are error response schemas defined for all failure modes?
- [ ] For streaming (SSE/WS): are error events defined? What happens on mid-stream failure?
- [ ] Is the auth mechanism explicitly stated? (not just "需登录" — which cookie/header?)
- [ ] Are rate limits realistic? Include cost estimation for external API calls.

**Security**:
- [ ] Injection risks for any user input that reaches an LLM or shell
- [ ] Are permission checks specified (not just "仅作者可操作" — how to verify authorship?)
- [ ] CSP compatibility for new client-server patterns

**Consistency**:
- [ ] Do code examples match the decisions? (e.g., decision says "Anthropic only" but code lists 3 providers)
- [ ] Do phase descriptions match the timeline table?

**Completeness**:
- [ ] Cost estimation for external services (LLM APIs, etc.)
- [ ] Timeout handling for long-running operations
- [ ] Mobile/responsive considerations if applicable

### Review Output Format

```markdown
## 评审意见

**🔴 必须修改（N 项）**
1. **{issue}** — {why it's critical}

**🟡 建议修改（N 项）**
N. {issue} — {impact}

**整体结论**：🟢/🟡/🔴 — {summary}
```

## Phase 7: Optimize PRD (after review findings)

When asked to optimize/修改 the PRD based on review:
1. Read the full document first (don't work from memory)
2. Make all 🔴 fixes first, then 🟡
3. Update version number and status
4. Commit and push if in a git repo
5. Report a summary of changes (not the full diff)

## Pitfalls

- **When user says "全部做完" or "做完", execute fully.** Don't just give recommendations and wait. The user expects you to complete all the work, not stop at analysis. If you identify optimizations, implement them immediately.
- **Do NOT skip structured planning.** After codebase analysis and before drafting, produce the structured plan (Phase 2). It catches missing dependencies, inconsistent designs, and unasked decision points before you write 500 lines of PRD. The plan is short (one JSON block) but forces explicit thinking.
- **Do NOT dump all decisions at once.** Ask one at a time. User explicitly corrected this.
- **Confirm understanding before writing PRD.** For architectural changes, the user expects you to first restate your understanding of the requirement, then wait for explicit confirmation before writing. The user said: "你先理解并复述一遍我的意思，我确认之后再编写PRD". This may take 2-4 rounds of refinement — be patient. Each round you restate, the user corrects or adds nuance. Don't rush to writing.
- **Use subagent for independent architectural analysis.** When the user says "可以用子代理独立分析" or asks for objective analysis, use `delegate_task` with file/terminal toolsets to have a subagent read the codebase and produce analysis. This gives the user confidence the analysis is unbiased. Summarize the subagent's findings, then add your own critique before presenting.
- **Present your own critique alongside subagent findings.** When the user asks "你有什么更好的方案吗" or "客观来看，你还有什么建议吗", they don't just want the subagent's analysis — they want YOUR independent evaluation. After summarizing the subagent's proposal, add a section with your own critique: what's over-designed, what's missing, what a simpler approach would look like. The user values honest disagreement over agreement.
- **Clarify intent before acting.** When user asks to "check" or "analyze" an issue, they may want a PRD/analysis document, NOT a direct code fix. If you start deploying fixes before confirming, the user will correct you with "只需要写需求文档". Always confirm: "需要我直接修复，还是写需求文档？"
- **PRD delivery via Gitea.** For this user, PRDs are pushed to `Elaina/ephron-ren-qa` repo on Gitea (https://gitea.ephron.ren/Elaina/ephron-ren-qa). Commit message format: `docs: {简短描述} PRD`. The user pulls from Gitea locally.
- **Do NOT ask the user to explain their codebase.** Read the code yourself first.
- **Include your recommendation** when presenting options. Don't just list choices neutrally.
- **ASCII wireframes > text descriptions** for UI/UX. Show, don't tell.
- **Don't skip the competitor analysis** — even a quick 2x2 table adds value.
- **Read API spec docs if they exist** — the project may already have a partial specification you should extend rather than start from scratch.
- **Check CSP/security headers** when the feature involves client-server communication (SSE, WebSocket, etc.)
- **Define placeholder syntax explicitly.** Template variables, config templates, etc. — never assume the reader knows the convention.
- **Map display values to identifiers.** If the DB stores "Claude" but the API needs `claude-sonnet-4-20250514`, define the mapping.
- **Always include cost estimation** when the feature calls external paid APIs (LLM, vision, etc.).
- **Don't list 3 providers in code when the decision says "only use 1."** Keep code examples consistent with decisions.
- **Pull latest code before analysis.** When working with ephron.ren, always `git pull` first — the user may have pushed fixes via OpenCode since last session. `cd /home/ubuntu/projects/ephron.ren && git pull`.
- **Bug-fix PRDs are shorter than feature PRDs.** For bug fixes, focus on: problem description, root cause analysis, fix options with trade-offs, and implementation details. Skip user stories, data models, and competitor analysis. See `references/bug-fix-prd-pattern.md`.
- **Communication style: state what YOU will do next.** After replying, if there's a next step, say "接下来我会..." and end with a colon (not period). Example: "PRD 已完成，接下来我会推送到 gitea：". Use period only when everything is done.

## References

- `references/example-prompt-service-prd.md` — Full PRD example (Prompt service)
- `references/prd-review-example.md` — PRD review output with common findings and fix patterns
- `references/example-settings-refactor-prd.md` — Settings/config refactoring PRD patterns (profile-based storage, migration, isolation)
- `sn-research-planning` — SenseNova 的结构化规划流程，Phase 2 的设计参考来源

## Bug-Fix PRD 模板

对于 bug 修复类 PRD，使用简化模板：

```markdown
# {Bug 描述} 修复方案

> **版本**: v1.0
> **日期**: {date}
> **状态**: 📝 待评审
> **严重程度**: 🔴 高 / 🟡 中 / 🟢 低

---

## 一、问题描述

### 1.1 现象
- 用户操作步骤
- 预期行为
- 实际行为

### 1.2 影响范围
- 受影响的用户群体
- 受影响的功能模块
- 业务影响程度

### 1.3 复现条件
- 必要条件
- 触发条件
- 环境要求

---

## 二、根因分析

### 2.1 直接原因
- 代码层面的问题
- 配置层面的问题

### 2.2 根本原因
- 设计缺陷
- 流程缺陷
- 监控缺失

### 2.3 代码定位
- 相关文件
- 关键代码段
- 问题代码行号

---

## 三、修复方案

### 3.1 方案概述
- 修复思路
- 技术选型
- 实现难度

### 3.2 代码修改
```python
# 修改前
problematic_code()

# 修改后
fixed_code()
```

### 3.3 配置变更
- 需要修改的配置项
- 新增的配置项
- 删除的配置项

### 3.4 数据迁移
- 需要执行的 SQL
- 数据修复脚本
- 回滚方案

---

## 四、验证方法

### 4.1 测试用例
- 功能测试
- 边界测试
- 异常测试

### 4.2 验证步骤
1. 步骤 1
2. 步骤 2
3. 步骤 3

### 4.3 预期结果
- 修复后的正常行为
- 边界条件的行为
- 异常条件的行为

---

## 五、风险评估

### 5.1 修改风险
- 可能影响的其他功能
- 性能影响
- 兼容性影响

### 5.2 回滚方案
- 回滚步骤
- 回滚影响
- 回滚验证

---

## 六、决策记录

| 决策点 | 选项 | 选择 | 理由 |
|--------|------|------|------|
| 方案选择 | A: 快速修复 / B: 根本修复 | A | 业务急需 |
| 测试范围 | A: 仅本模块 / B: 全量回归 | A | 影响范围小 |

---

## 七、时间估算

| 阶段 | 预计时间 | 负责人 |
|------|----------|--------|
| 代码修改 | 2 小时 | - |
| 单元测试 | 1 小时 | - |
| 集成测试 | 2 小时 | - |
| 部署上线 | 0.5 小时 | - |
| 总计 | 5.5 小时 | - |
```

## Decision Gathering Format

Present each decision as:

```
**决策点 {N}/{Total}: {Title}**
- A. {option}（{brief pros}）
- B. {option}（{brief pros}）

推荐 A，因为 {reason}。你选？
```

After user answers, move to next. Don't re-ask already answered questions.
