doc-prd-fixer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

doc-prd-fixer

doc-prd-fixer

Purpose

用途

Automated fix skill that reads the latest review report and applies fixes to PRD documents. This skill bridges the gap between
doc-prd-reviewer
(which identifies issues) and the corrected PRD, enabling iterative improvement cycles.
Layer: 2 (PRD Quality Improvement)
Upstream: PRD document, Review Report (
PRD-NN.R_review_report_vNNN.md
), BRD (source requirements)
Downstream: Fixed PRD, Fix Report (
PRD-NN.F_fix_report_vNNN.md
)

这是一款自动化修复工具,可读取最新的评审报告并对PRD文档进行修复。该工具填补了
doc-prd-reviewer
(用于识别问题)与修正后的PRD之间的空白,支持迭代优化循环。
层级:2(PRD质量优化)
上游依赖:PRD文档、评审报告(
PRD-NN.R_review_report_vNNN.md
)、BRD(需求来源)
下游产出:修复后的PRD、修复报告(
PRD-NN.F_fix_report_vNNN.md

When to Use This Skill

适用场景

Use
doc-prd-fixer
when:
  • After Review: Run after
    doc-prd-reviewer
    identifies issues
  • Iterative Improvement: Part of Review -> Fix -> Review cycle
  • Automated Pipeline: CI/CD integration for quality gates
  • Batch Fixes: Apply fixes to multiple PRDs based on review reports
Do NOT use when:
  • No review report exists (run
    doc-prd-reviewer
    first)
  • Creating new PRD (use
    doc-prd
    or
    doc-prd-autopilot
    )
  • Only need validation (use
    doc-prd-validator
    )

当出现以下情况时,使用
doc-prd-fixer
  • 评审后:在
    doc-prd-reviewer
    识别出问题后运行
  • 迭代优化:作为「评审→修复→评审」循环的一部分
  • 自动化流水线:集成到CI/CD中作为质量关卡
  • 批量修复:基于评审报告对多份PRD进行批量修复
以下情况请勿使用
  • 无评审报告(请先运行
    doc-prd-reviewer
  • 创建新PRD(使用
    doc-prd
    doc-prd-autopilot
  • 仅需验证(使用
    doc-prd-validator

Skill Dependencies

工具依赖

SkillPurposeWhen Used
doc-prd-reviewer
Source of issues to fixInput (reads review report)
doc-naming
Element ID standardsFix element IDs
doc-prd
PRD creation rulesCreate missing sections
doc-brd-reviewer
Upstream BRD validationCheck upstream alignment

工具用途使用时机
doc-prd-reviewer
提供待修复的问题来源输入(读取评审报告)
doc-naming
元素ID标准修复元素ID
doc-prd
PRD创建规则创建缺失章节
doc-brd-reviewer
上游BRD验证检查上游一致性

Workflow Overview

工作流概述

mermaid
flowchart TD
    A[Input: PRD Path] --> B[Find Latest Review Report]
    B --> C{Review Found?}
    C -->|No| D[Run doc-prd-reviewer First]
    C -->|Yes| E[Parse Review Report]

    E --> F[Categorize Issues]

    subgraph FixPhases["Fix Phases"]
        F --> F0[Phase 0: Fix Structure Violations]
        F0 --> G[Phase 1: Create Missing Files]
        G --> H[Phase 2: Fix Broken Links]
        H --> I[Phase 3: Fix Element IDs]
        I --> J[Phase 4: Fix Content Issues]
        J --> K[Phase 5: Update References]
        K --> K2[Phase 6: Handle Upstream Drift]
    end

    K2 --> L[Write Fixed PRD]
    L --> M[Generate Fix Report]
    M --> N{Re-run Review?}
    N -->|Yes| O[Invoke doc-prd-reviewer]
    O --> P{Score >= Threshold?}
    P -->|No, iterations < max| F
    P -->|Yes| Q[COMPLETE]
    N -->|No| Q

mermaid
flowchart TD
    A[Input: PRD Path] --> B[Find Latest Review Report]
    B --> C{Review Found?}
    C -->|No| D[Run doc-prd-reviewer First]
    C -->|Yes| E[Parse Review Report]

    E --> F[Categorize Issues]

    subgraph FixPhases["Fix Phases"]
        F --> F0[Phase 0: Fix Structure Violations]
        F0 --> G[Phase 1: Create Missing Files]
        G --> H[Phase 2: Fix Broken Links]
        H --> I[Phase 3: Fix Element IDs]
        I --> J[Phase 4: Fix Content Issues]
        J --> K[Phase 5: Update References]
        K --> K2[Phase 6: Handle Upstream Drift]
    end

    K2 --> L[Write Fixed PRD]
    L --> M[Generate Fix Report]
    M --> N{Re-run Review?}
    N -->|Yes| O[Invoke doc-prd-reviewer]
    O --> P{Score >= Threshold?}
    P -->|No, iterations < max| F
    P -->|Yes| Q[COMPLETE]
    N -->|No| Q

Fix Phases

修复阶段

Phase 0: Fix Structure Violations (CRITICAL)

阶段0:修复结构违规问题(关键)

Fixes PRDs that are not in nested folders. This phase runs FIRST because all subsequent phases depend on correct folder structure.
Nested Folder Rule: ALL PRDs MUST be in nested folders regardless of document size.
Required Structure:
PRD TypeRequired Location
Monolithic
docs/02_PRD/PRD-NN_{slug}/PRD-NN_{slug}.md
Sectioned
docs/02_PRD/PRD-NN_{slug}/PRD-NN.0_index.md
,
PRD-NN.1_*.md
, etc.
Fix Actions:
Issue CodeIssueFix Action
REV-STR001PRD not in nested folderCreate folder, move file, update all links
REV-STR002PRD folder name doesn't match PRD IDRename folder to match
REV-STR004BRD link path incorrect for nested folderUpdate
../01_BRD/
../../01_BRD/
Structure Fix Workflow:
python
def fix_prd_structure(prd_path: str) -> list[Fix]:
    """Fix PRD structure violations."""
    fixes = []

    filename = os.path.basename(prd_path)
    parent_folder = os.path.dirname(prd_path)

    # Extract PRD ID and slug from filename
    match = re.match(r'PRD-(\d+)_([^/]+)\.md', filename)
    if not match:
        return []  # Cannot auto-fix invalid filename

    prd_id = match.group(1)
    slug = match.group(2)
    expected_folder = f"PRD-{prd_id}_{slug}"

    # Check if already in nested folder
    if os.path.basename(parent_folder) != expected_folder:
        # Create nested folder
        new_folder = os.path.join(os.path.dirname(parent_folder), expected_folder)
        os.makedirs(new_folder, exist_ok=True)

        # Move file
        new_path = os.path.join(new_folder, filename)
        shutil.move(prd_path, new_path)
        fixes.append(f"Moved {prd_path} to {new_path}")

        # Update BRD links in moved file
        content = Path(new_path).read_text()
        updated_content = content.replace('../01_BRD/', '../../01_BRD/')
        updated_content = updated_content.replace('../00_REF/', '../../00_REF/')
        Path(new_path).write_text(updated_content)
        fixes.append(f"Updated relative links for nested folder structure")

    return fixes
Link Path Updates After Move:
Original PathUpdated Path
../01_BRD/BRD-00_GLOSSARY.md
../../01_BRD/BRD-00_GLOSSARY.md
../00_REF/domain/spec.md
../../00_REF/domain/spec.md
PRD-00_GLOSSARY.md
../PRD-00_GLOSSARY.md

修复未存储在嵌套文件夹中的PRD。此阶段优先执行,因为后续所有阶段都依赖正确的文件夹结构。
嵌套文件夹规则:所有PRD无论大小,都必须存储在嵌套文件夹中。
要求结构:
PRD类型存储位置要求
单体式
docs/02_PRD/PRD-NN_{slug}/PRD-NN_{slug}.md
分段式
docs/02_PRD/PRD-NN_{slug}/PRD-NN.0_index.md
,
PRD-NN.1_*.md
修复操作:
问题代码问题描述修复动作
REV-STR001PRD未在嵌套文件夹中创建文件夹、移动文件、更新所有链接
REV-STR002PRD文件夹名称与PRD ID不匹配重命名文件夹以匹配ID
REV-STR004嵌套文件夹下的BRD链接路径错误
../01_BRD/
更新为
../../01_BRD/
结构修复工作流:
python
def fix_prd_structure(prd_path: str) -> list[Fix]:
    """Fix PRD structure violations."""
    fixes = []

    filename = os.path.basename(prd_path)
    parent_folder = os.path.dirname(prd_path)

    # Extract PRD ID and slug from filename
    match = re.match(r'PRD-(\d+)_([^/]+)\.md', filename)
    if not match:
        return []  # Cannot auto-fix invalid filename

    prd_id = match.group(1)
    slug = match.group(2)
    expected_folder = f"PRD-{prd_id}_{slug}"

    # Check if already in nested folder
    if os.path.basename(parent_folder) != expected_folder:
        # Create nested folder
        new_folder = os.path.join(os.path.dirname(parent_folder), expected_folder)
        os.makedirs(new_folder, exist_ok=True)

        # Move file
        new_path = os.path.join(new_folder, filename)
        shutil.move(prd_path, new_path)
        fixes.append(f"Moved {prd_path} to {new_path}")

        # Update BRD links in moved file
        content = Path(new_path).read_text()
        updated_content = content.replace('../01_BRD/', '../../01_BRD/')
        updated_content = updated_content.replace('../00_REF/', '../../00_REF/')
        Path(new_path).write_text(updated_content)
        fixes.append(f"Updated relative links for nested folder structure")

    return fixes
移动后的链接路径更新:
原路径更新后路径
../01_BRD/BRD-00_GLOSSARY.md
../../01_BRD/BRD-00_GLOSSARY.md
../00_REF/domain/spec.md
../../00_REF/domain/spec.md
PRD-00_GLOSSARY.md
../PRD-00_GLOSSARY.md

Phase 1: Create Missing Files

阶段1:创建缺失文件

Creates files that are referenced but don't exist.
Scope:
Missing FileActionTemplate Used
PRD-00_GLOSSARY.md
Create PRD glossaryGlossary template
PRD-NN_APPENDIX_*.md
Create appendix placeholderAppendix template
Reference docs (
*_REF_*.md
)
Create placeholderREF template
Feature specsCreate placeholder with TODO sectionsFeature template
PRD Glossary Template:
markdown
---
title: "PRD-00: Product Glossary"
tags:
  - prd
  - glossary
  - reference
custom_fields:
  document_type: glossary
  artifact_type: PRD-REFERENCE
  layer: 2
---
创建被引用但不存在的文件。
范围:
缺失文件动作使用模板
PRD-00_GLOSSARY.md
创建PRD术语表术语表模板
PRD-NN_APPENDIX_*.md
创建附录占位符附录模板
参考文档(
*_REF_*.md
创建占位符REF模板
功能规格创建带TODO章节的占位符功能模板
PRD术语表模板:
markdown
---
title: "PRD-00: Product Glossary"
tags:
  - prd
  - glossary
  - reference
custom_fields:
  document_type: glossary
  artifact_type: PRD-REFERENCE
  layer: 2
---

PRD-00: Product Glossary

PRD-00: Product Glossary

Common terminology used across all Product Requirements Documents.
Common terminology used across all Product Requirements Documents.

Product Terms

Product Terms

TermDefinitionContext
FeatureDiscrete unit of product functionalityScope definition
User StoryUser-centric requirement formatRequirements
Acceptance CriteriaConditions for feature completionValidation
TermDefinitionContext
FeatureDiscrete unit of product functionalityScope definition
User StoryUser-centric requirement formatRequirements
Acceptance CriteriaConditions for feature completionValidation

Technical Terms

Technical Terms

TermDefinitionContext
APIApplication Programming InterfaceIntegration
UIUser InterfaceFrontend
UXUser ExperienceDesign
TermDefinitionContext
APIApplication Programming InterfaceIntegration
UIUser InterfaceFrontend
UXUser ExperienceDesign

Domain Terms

Domain Terms

<!-- Add project-specific terminology below -->
TermDefinitionContext
[Term][Definition][Where used]

**Feature Placeholder Template**:

```markdown
---
title: "Feature Specification: [Feature Name]"
tags:
  - prd
  - feature-spec
  - reference
custom_fields:
  document_type: feature-spec
  status: placeholder
  created_by: doc-prd-fixer
---
<!-- Add project-specific terminology below -->
TermDefinitionContext
[Term][Definition][Where used]

**功能占位符模板**:

```markdown
---
title: "Feature Specification: [Feature Name]"
tags:
  - prd
  - feature-spec
  - reference
custom_fields:
  document_type: feature-spec
  status: placeholder
  created_by: doc-prd-fixer
---

Feature Specification: [Feature Name]

Feature Specification: [Feature Name]

Status: Placeholder - Requires completion
Status: Placeholder - Requires completion

1. Feature Overview

1. Feature Overview

[TODO: Document feature overview]
[TODO: Document feature overview]

2. User Stories

2. User Stories

Story IDAs a...I want to...So that...
US-XX-01[Role][Action][Benefit]
Story IDAs a...I want to...So that...
US-XX-01[Role][Action][Benefit]

3. Acceptance Criteria

3. Acceptance Criteria

[TODO: Document acceptance criteria]
[TODO: Document acceptance criteria]

4. Dependencies

4. Dependencies

[TODO: Document feature dependencies]

Created by doc-prd-fixer as placeholder. Complete this document to resolve broken link issues.

---
[TODO: Document feature dependencies]

Created by doc-prd-fixer as placeholder. Complete this document to resolve broken link issues.

---

Phase 2: Fix Broken Links

阶段2:修复失效链接

Updates links to point to correct locations.
Fix Actions:
Issue CodeIssueFix Action
REV-L001Broken internal linkUpdate path or create target file
REV-L002External link unreachableAdd warning comment, keep link
REV-L003Absolute path usedConvert to relative path
REV-L004Broken BRD referenceUpdate to correct BRD path
Path Resolution Logic:
python
def fix_link_path(prd_location: str, target_path: str) -> str:
    """Calculate correct relative path based on PRD location."""

    # ALL PRDs are in nested folders (mandatory rule):
    # Monolithic PRD: docs/02_PRD/PRD-01_slug/PRD-01_slug.md
    # Sectioned PRD: docs/02_PRD/PRD-01_slug/PRD-01.3_section.md

    # Both types need to go up two levels to reach 01_BRD or 00_REF
    return "../../" + calculate_relative_path(prd_location, target_path)
BRD Link Fix (All PRDs in nested folders):
IssueOriginal LinkFixed Link
After move to nested folder
../01_BRD/BRD-01.md
../../01_BRD/BRD-01_slug/BRD-01_slug.md
Incorrect depth
../../01_BRD/
../../01_BRD/
(already correct)

更新链接以指向正确位置。
修复操作:
问题代码问题描述修复动作
REV-L001内部链接失效更新路径或创建目标文件
REV-L002外部链接无法访问添加警告注释,保留链接
REV-L003使用绝对路径转换为相对路径
REV-L004BRD引用失效更新为正确的BRD路径
路径解析逻辑:
python
def fix_link_path(prd_location: str, target_path: str) -> str:
    """Calculate correct relative path based on PRD location."""

    # ALL PRDs are in nested folders (mandatory rule):
    # Monolithic PRD: docs/02_PRD/PRD-01_slug/PRD-01_slug.md
    # Sectioned PRD: docs/02_PRD/PRD-01_slug/PRD-01.3_section.md

    # Both types need to go up two levels to reach 01_BRD or 00_REF
    return "../../" + calculate_relative_path(prd_location, target_path)
BRD链接修复(所有PRD均在嵌套文件夹中):
问题原链接修复后链接
移动到嵌套文件夹后
../01_BRD/BRD-01.md
../../01_BRD/BRD-01_slug/BRD-01_slug.md
深度错误
../../01_BRD/
../../01_BRD/
(已正确)

Phase 3: Fix Element IDs

阶段3:修复元素ID

Converts invalid element IDs to correct format.
Conversion Rules:
PatternIssueConversion
PRD.NN.25.SS
Code 25 invalid for PRD
PRD.NN.01.SS
(Functional Requirement)
PRD.NN.33.SS
Code 33 invalid for PRD
PRD.NN.22.SS
(Feature Item)
FR-XXX
Legacy pattern
PRD.NN.01.SS
US-XXX
Legacy pattern
PRD.NN.05.SS
AC-XXX
Legacy pattern
PRD.NN.06.SS
Type Code Mapping (PRD-specific valid codes: 01-09, 11, 22, 24):
Invalid CodeValid CodeElement Type
2501Functional Requirement
3322Feature Item
3506Acceptance Criterion
1009Business Rule
1211Interface Requirement
Regex Patterns:
python
undefined
将无效的元素ID转换为正确格式。
转换规则:
格式问题转换结果
PRD.NN.25.SS
代码25对PRD无效
PRD.NN.01.SS
(功能需求)
PRD.NN.33.SS
代码33对PRD无效
PRD.NN.22.SS
(功能项)
FR-XXX
旧版格式
PRD.NN.01.SS
US-XXX
旧版格式
PRD.NN.05.SS
AC-XXX
旧版格式
PRD.NN.06.SS
类型代码映射(PRD专属有效代码:01-09、11、22、24):
无效代码有效代码元素类型
2501功能需求
3322功能项
3506验收标准
1009业务规则
1211接口需求
正则表达式:
python
undefined

Find element IDs with invalid type codes for PRD

Find element IDs with invalid type codes for PRD

invalid_prd_type_25 = r'PRD.(\d{2}).25.(\d{2})' replacement_25 = r'PRD.\1.01.\2'
invalid_prd_type_33 = r'PRD.(\d{2}).33.(\d{2})' replacement_33 = r'PRD.\1.22.\2'
invalid_prd_type_25 = r'PRD.(\d{2}).25.(\d{2})' replacement_25 = r'PRD.\1.01.\2'
invalid_prd_type_33 = r'PRD.(\d{2}).33.(\d{2})' replacement_33 = r'PRD.\1.22.\2'

Find legacy patterns

Find legacy patterns

legacy_fr = r'###\s+FR-(\d+):' legacy_us = r'###\s+US-(\d+):' legacy_ac = r'###\s+AC-(\d+):'

---
legacy_fr = r'###\s+FR-(\d+):' legacy_us = r'###\s+US-(\d+):' legacy_ac = r'###\s+AC-(\d+):'

---

Phase 4: Fix Content Issues

阶段4:修复内容问题

Addresses placeholders and incomplete content.
Fix Actions:
Issue CodeIssueFix Action
REV-P001
[TODO]
placeholder
Flag for manual completion (cannot auto-fix)
REV-P002
[TBD]
placeholder
Flag for manual completion (cannot auto-fix)
REV-P003Template date
YYYY-MM-DD
Replace with current date
REV-P004Template name
[Name]
Replace with metadata author or flag
REV-P005Empty sectionAdd minimum template content
REV-P006Missing user story formatFlag for manual review
Auto-Replacements:
python
replacements = {
    'YYYY-MM-DDTHH:MM:SS': datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
    'YYYY-MM-DD': datetime.now().strftime('%Y-%m-%d'),
    'MM/DD/YYYY': datetime.now().strftime('%m/%d/%Y'),
    '[Current date]': datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
    '[Product Name]': extract_product_name_from_metadata(),
}

处理占位符和不完整内容。
修复操作:
问题代码问题描述修复动作
REV-P001
[TODO]
占位符
标记为需手动完成(无法自动修复)
REV-P002
[TBD]
占位符
标记为需手动完成(无法自动修复)
REV-P003模板日期
YYYY-MM-DD
替换为当前日期
REV-P004模板名称
[Name]
替换为元数据中的作者或标记待处理
REV-P005空章节添加最低限度的模板内容
REV-P006缺失用户故事格式标记为需手动评审
自动替换规则:
python
replacements = {
    'YYYY-MM-DDTHH:MM:SS': datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
    'YYYY-MM-DD': datetime.now().strftime('%Y-%m-%d'),
    'MM/DD/YYYY': datetime.now().strftime('%m/%d/%Y'),
    '[Current date]': datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
    '[Product Name]': extract_product_name_from_metadata(),
}

Phase 5: Update References

阶段5:更新引用

Ensures traceability and cross-references are correct.
Fix Actions:
IssueFix Action
Missing
@ref:
for created files
Add reference tag
Incorrect cross-PRD pathUpdate to correct relative path
Missing BRD traceabilityAdd BRD reference with
@trace: BRD-NN
Missing traceability entryAdd to traceability matrix
Traceability Format:
markdown
<!-- Traceability to BRD -->
@trace: BRD-01.22.01 -> PRD-01.22.01

<!-- Reference to upstream -->
@ref: [BRD-01 Section 3](../01_BRD/BRD-01.md#3-business-requirements)

确保可追溯性和交叉引用正确。
修复操作:
问题修复动作
已创建文件缺失
@ref:
标记
添加引用标签
PRD间路径错误更新为正确的相对路径
缺失BRD可追溯性使用
@trace: BRD-NN
添加BRD引用
缺失可追溯性条目添加到可追溯性矩阵
可追溯性格式:
markdown
<!-- Traceability to BRD -->
@trace: BRD-01.22.01 -> PRD-01.22.01

<!-- Reference to upstream -->
@ref: [BRD-01 Section 3](../01_BRD/BRD-01.md#3-business-requirements)

Phase 6: Handle Upstream Drift (Auto-Merge)

阶段6:处理上游变更(自动合并)

Automatically merges upstream BRD changes into the PRD document based on change percentage thresholds.
Drift Detection Workflow:
mermaid
flowchart TD
    A[Detect Upstream BRD Changes] --> B[Calculate Change %]
    B --> C{Change Analysis}

    C -->|< 5%| D[TIER 1: Auto-Merge]
    C -->|5-15%| E[TIER 2: Auto-Merge + Detailed Log]
    C -->|> 15%| F[TIER 3: Archive + Regenerate]

    D --> D1[Add new requirements]
    D1 --> D2[Update thresholds]
    D2 --> D3[Update references]
    D3 --> D4[Increment patch: 1.0->1.0.1]

    E --> E1[Add new requirements]
    E1 --> E2[Update thresholds]
    E2 --> E3[Update references]
    E3 --> E4[Generate detailed changelog]
    E4 --> E5[Increment minor: 1.0->1.1]

    F --> F1[Mark current as ARCHIVED]
    F1 --> F2[Update status in frontmatter]
    F2 --> F3[Trigger regeneration via autopilot]
    F3 --> F4[Increment major: 1.x->2.0]

    D4 --> G[Update Drift Cache]
    E5 --> G
    F4 --> G
    G --> H[Add to Fix Report]

基于变更百分比阈值,自动将上游BRD的变更合并到PRD文档中。
变更检测工作流:
mermaid
flowchart TD
    A[Detect Upstream BRD Changes] --> B[Calculate Change %]
    B --> C{Change Analysis}

    C -->|< 5%| D[TIER 1: Auto-Merge]
    C -->|5-15%| E[TIER 2: Auto-Merge + Detailed Log]
    C -->|> 15%| F[TIER 3: Archive + Regenerate]

    D --> D1[Add new requirements]
    D1 --> D2[Update thresholds]
    D2 --> D3[Update references]
    D3 --> D4[Increment patch: 1.0->1.0.1]

    E --> E1[Add new requirements]
    E1 --> E2[Update thresholds]
    E2 --> E3[Update references]
    E3 --> E4[Generate detailed changelog]
    E4 --> E5[Increment minor: 1.0->1.1]

    F --> F1[Mark current as ARCHIVED]
    F1 --> F2[Update status in frontmatter]
    F2 --> F3[Trigger regeneration via autopilot]
    F3 --> F4[Increment major: 1.x->2.0]

    D4 --> G[Update Drift Cache]
    E5 --> G
    F4 --> G
    G --> H[Add to Fix Report]

6.1 Change Percentage Calculation

6.1 变更百分比计算

python
def calculate_change_percentage(upstream_old: str, upstream_new: str) -> dict:
    """
    Calculate change percentage between upstream BRD versions.

    Returns:
        {
            'total_change_pct': float,      # Overall change percentage
            'additions_pct': float,          # New content added
            'modifications_pct': float,      # Existing content modified
            'deletions_pct': float,          # Content removed (tracked, not applied)
            'change_type': str               # 'minor' | 'moderate' | 'major'
        }
    """
    old_lines = upstream_old.strip().split('\n')
    new_lines = upstream_new.strip().split('\n')

    # Use difflib for precise change detection
    import difflib
    diff = difflib.unified_diff(old_lines, new_lines)

    additions = sum(1 for line in diff if line.startswith('+') and not line.startswith('+++'))
    deletions = sum(1 for line in diff if line.startswith('-') and not line.startswith('---'))

    total_lines = max(len(old_lines), len(new_lines))
    total_change_pct = ((additions + deletions) / total_lines) * 100 if total_lines > 0 else 0

    return {
        'total_change_pct': round(total_change_pct, 2),
        'additions_pct': round((additions / total_lines) * 100, 2) if total_lines > 0 else 0,
        'modifications_pct': round((min(additions, deletions) / total_lines) * 100, 2) if total_lines > 0 else 0,
        'deletions_pct': round((deletions / total_lines) * 100, 2) if total_lines > 0 else 0,
        'change_type': 'minor' if total_change_pct < 5 else 'moderate' if total_change_pct < 15 else 'major'
    }

python
def calculate_change_percentage(upstream_old: str, upstream_new: str) -> dict:
    """
    Calculate change percentage between upstream BRD versions.

    Returns:
        {
            'total_change_pct': float,      # Overall change percentage
            'additions_pct': float,          # New content added
            'modifications_pct': float,      # Existing content modified
            'deletions_pct': float,          # Content removed (tracked, not applied)
            'change_type': str               # 'minor' | 'moderate' | 'major'
        }
    """
    old_lines = upstream_old.strip().split('\n')
    new_lines = upstream_new.strip().split('\n')

    # Use difflib for precise change detection
    import difflib
    diff = difflib.unified_diff(old_lines, new_lines)

    additions = sum(1 for line in diff if line.startswith('+') and not line.startswith('+++'))
    deletions = sum(1 for line in diff if line.startswith('-') and not line.startswith('---'))

    total_lines = max(len(old_lines), len(new_lines))
    total_change_pct = ((additions + deletions) / total_lines) * 100 if total_lines > 0 else 0

    return {
        'total_change_pct': round(total_change_pct, 2),
        'additions_pct': round((additions / total_lines) * 100, 2) if total_lines > 0 else 0,
        'modifications_pct': round((min(additions, deletions) / total_lines) * 100, 2) if total_lines > 0 else 0,
        'deletions_pct': round((deletions / total_lines) * 100, 2) if total_lines > 0 else 0,
        'change_type': 'minor' if total_change_pct < 5 else 'moderate' if total_change_pct < 15 else 'major'
    }

6.2 Tier 1: Auto-Merge (< 5% Change)

6.2 第一级:自动合并(变更<5%)

Trigger: Total change percentage < 5%
Actions:
Change TypeAuto-ActionExample
New requirement addedAppend with generated ID
PRD.01.01.13
Threshold value changedFind & replace value
timeout: 30 -> 45
Reference updatedUpdate
@ref:
path
Path correction
Version incrementedUpdate version reference
v1.2 -> v1.3
ID Generation for New Requirements:
python
def generate_next_id(doc_type: str, doc_num: str, element_type: str, existing_ids: list) -> str:
    """
    Generate next sequential ID for new requirement.

    Args:
        doc_type: 'PRD', 'BRD', etc.
        doc_num: '01', '02', etc.
        element_type: '01' (Functional), '05' (User Story), etc.
        existing_ids: List of existing IDs in document

    Returns:
        Next available ID (e.g., 'PRD.01.01.13')
    """
    pattern = f"{doc_type}.{doc_num}.{element_type}."
    matching = [id for id in existing_ids if id.startswith(pattern)]

    if not matching:
        return f"{pattern}01"

    max_seq = max(int(id.split('.')[-1]) for id in matching)
    return f"{pattern}{str(max_seq + 1).zfill(2)}"
ID Pattern for PRD:
PRD.NN.TT.SS
where:
  • NN
    = Document number (01, 02, etc.)
  • TT
    = Type code (01=Functional, 05=User Story, 06=Acceptance Criterion, etc.)
  • SS
    = Sequence number (01, 02, etc.)
Auto-Merge Template for New Requirements:
markdown
undefined
触发条件:总变更百分比<5%
操作:
变更类型自动动作示例
新增需求附加生成的ID
PRD.01.01.13
阈值变更查找并替换值
timeout: 30 -> 45
引用更新更新
@ref:
路径
路径修正
版本升级更新版本引用
v1.2 -> v1.3
新增需求的ID生成:
python
def generate_next_id(doc_type: str, doc_num: str, element_type: str, existing_ids: list) -> str:
    """
    Generate next sequential ID for new requirement.

    Args:
        doc_type: 'PRD', 'BRD', etc.
        doc_num: '01', '02', etc.
        element_type: '01' (Functional), '05' (User Story), etc.
        existing_ids: List of existing IDs in document

    Returns:
        Next available ID (e.g., 'PRD.01.01.13')
    """
    pattern = f"{doc_type}.{doc_num}.{element_type}."
    matching = [id for id in existing_ids if id.startswith(pattern)]

    if not matching:
        return f"{pattern}01"

    max_seq = max(int(id.split('.')[-1]) for id in matching)
    return f"{pattern}{str(max_seq + 1).zfill(2)}"
PRD的ID格式
PRD.NN.TT.SS
,其中:
  • NN
    = 文档编号(01、02等)
  • TT
    = 类型代码(01=功能需求、05=用户故事、06=验收标准等)
  • SS
    = 序列号(01、02等)
新增需求的自动合并模板:
markdown
undefined

{GENERATED_ID}: {Requirement Title}

{GENERATED_ID}: {Requirement Title}

Source: Auto-merged from {upstream_brd} ({change_date})
Requirement: {requirement_text}
User Stories: {user_stories}
Acceptance Criteria: {acceptance_criteria}
Priority: {priority}
<!-- AUTO-MERGED: {timestamp} from {upstream_brd}#{section} -->

**Version Update**:
- Increment patch version: `1.0` -> `1.0.1`
- Update `last_updated` in frontmatter
- Add changelog entry

---
Source: Auto-merged from {upstream_brd} ({change_date})
Requirement: {requirement_text}
User Stories: {user_stories}
Acceptance Criteria: {acceptance_criteria}
Priority: {priority}
<!-- AUTO-MERGED: {timestamp} from {upstream_brd}#{section} -->

**版本更新**:
- 升级补丁版本:`1.0` -> `1.0.1`
- 更新前置元数据中的`last_updated`
- 添加变更日志条目

---

6.3 Tier 2: Auto-Merge with Detailed Log (5-15% Change)

6.3 第二级:自动合并+详细日志(变更5-15%)

Trigger: Total change percentage between 5% and 15%
Actions: Same as Tier 1, plus:
Additional ActionDescription
Detailed changelogSection-by-section change log
Impact analysisWhich downstream artifacts affected (EARS, BDD)
Merge markers
<!-- MERGED: ... -->
comments
Version historyDetailed version history entry
Changelog Entry Format:
markdown
undefined
触发条件:总变更百分比在5%-15%之间
操作:与第一级相同,额外增加:
附加操作描述
详细变更日志按章节记录的变更日志
影响分析受影响的下游工件(EARS、BDD)
合并标记
<!-- MERGED: ... -->
注释
版本历史详细的版本历史条目
变更日志条目格式:
markdown
undefined

Changelog

Changelog

Version 1.1 (2026-02-10T16:00:00)

Version 1.1 (2026-02-10T16:00:00)

Upstream Sync: Auto-merged 8.5% changes from upstream BRD documents
ChangeSourceSectionDescription
AddedBRD-01.1_core.md3.5New passkey authentication requirement
UpdatedBRD-01.2_requirements.md4.2Session timeout changed 30->45 min
AddedBRD-01.3_quality_ops.md7.2New performance requirement
New Requirements Added:
  • PRD.01.01.13: Passkey Authentication Support
  • PRD.01.01.14: WebAuthn Fallback Mechanism
Thresholds Updated:
  • PRD.01.02.05: session_idle_timeout: 30->45 min
Impact: EARS-01, BDD-01, ADR-01 may require review

**Version Update**:
- Increment minor version: `1.0` -> `1.1`
- Update `last_updated` in frontmatter
- Add detailed changelog entry

---
Upstream Sync: Auto-merged 8.5% changes from upstream BRD documents
ChangeSourceSectionDescription
AddedBRD-01.1_core.md3.5New passkey authentication requirement
UpdatedBRD-01.2_requirements.md4.2Session timeout changed 30->45 min
AddedBRD-01.3_quality_ops.md7.2New performance requirement
New Requirements Added:
  • PRD.01.01.13: Passkey Authentication Support
  • PRD.01.01.14: WebAuthn Fallback Mechanism
Thresholds Updated:
  • PRD.01.02.05: session_idle_timeout: 30->45 min
Impact: EARS-01, BDD-01, ADR-01 may require review

**版本更新**:
- 升级次要版本:`1.0` -> `1.1`
- 更新前置元数据中的`last_updated`
- 添加详细变更日志条目

---

6.4 Tier 3: Archive and Regenerate (> 15% Change)

6.4 第三级:归档并重新生成(变更>15%)

Trigger: Total change percentage > 15%
Actions:
StepActionResult
1Mark current version as ARCHIVEDStatus update in frontmatter
2Create archive copy
PRD-01_v1.0_archived.md
3Update frontmatter status
status: archived
4Trigger autopilot regenerationNew version generated
5Increment major version
1.x
->
2.0
Archive Frontmatter Update:
yaml
---
title: "PRD-01: F1 Identity & Access Management"
custom_fields:
  version: "1.2"
  status: "archived"                    # Changed from 'current'
  archived_date: "2026-02-10T16:00:00"
  archived_reason: "upstream_drift_major"
  superseded_by: "PRD-01_v2.0"
  upstream_change_pct: 18.5
---
Archive File Naming:
docs/02_PRD/PRD-01_f1_iam/
├── PRD-01.0_index.md              # Current (v2.0)
├── PRD-01.1_core.md               # Current (v2.0)
├── .archive/
│   ├── v1.2/
│   │   ├── PRD-01.0_index.md      # Archived v1.2
│   │   ├── PRD-01.1_core.md
│   │   └── ARCHIVE_MANIFEST.md    # Archive metadata
ARCHIVE_MANIFEST.md:
markdown
undefined
触发条件:总变更百分比>15%
操作:
步骤动作结果
1将当前版本标记为ARCHIVED前置元数据中的状态更新
2创建归档副本
PRD-01_v1.0_archived.md
3更新前置元数据状态
status: archived
4触发自动生成工具重新生成生成新版本
5升级主版本
1.x
->
2.0
归档前置元数据更新:
yaml
---
title: "PRD-01: F1 Identity & Access Management"
custom_fields:
  version: "1.2"
  status: "archived"                    # Changed from 'current'
  archived_date: "2026-02-10T16:00:00"
  archived_reason: "upstream_drift_major"
  superseded_by: "PRD-01_v2.0"
  upstream_change_pct: 18.5
---
归档文件命名:
docs/02_PRD/PRD-01_f1_iam/
├── PRD-01.0_index.md              # Current (v2.0)
├── PRD-01.1_core.md               # Current (v2.0)
├── .archive/
│   ├── v1.2/
│   │   ├── PRD-01.0_index.md      # Archived v1.2
│   │   ├── PRD-01.1_core.md
│   │   └── ARCHIVE_MANIFEST.md    # Archive metadata
ARCHIVE_MANIFEST.md:
markdown
undefined

Archive Manifest: PRD-01 v1.2

Archive Manifest: PRD-01 v1.2

FieldValue
Archived Version1.2
Archived Date2026-02-10T16:00:00
ReasonUpstream drift > 15% (18.5%)
Superseded Byv2.0
Upstream ChangesBRD-01 (major revision)
FieldValue
Archived Version1.2
Archived Date2026-02-10T16:00:00
ReasonUpstream drift > 15% (18.5%)
Superseded Byv2.0
Upstream ChangesBRD-01 (major revision)

Change Summary

Change Summary

Upstream DocumentChange %Key Changes
BRD-01.1_core.md18.5%New auth methods, revised security model
Upstream DocumentChange %Key Changes
BRD-01.1_core.md18.5%New auth methods, revised security model

Downstream Impact

Downstream Impact

Documents requiring update after regeneration:
  • EARS-01 (derived from PRD-01)
  • BDD-01 (test scenarios)
  • ADR-01 (architecture decisions)

**No Deletion Policy**:

- Upstream content marked as deleted is **NOT** removed from document
- Instead, marked with `[DEPRECATED]` status:

```markdown
Documents requiring update after regeneration:
  • EARS-01 (derived from PRD-01)
  • BDD-01 (test scenarios)
  • ADR-01 (architecture decisions)

**不删除策略**:

- 上游标记为删除的内容**不会**从文档中移除
- 而是标记为`[DEPRECATED]`状态:

```markdown

PRD.01.01.05: Legacy Authentication Method [DEPRECATED]

PRD.01.01.05: Legacy Authentication Method [DEPRECATED]

Status: DEPRECATED (upstream removed 2026-02-10T16:00:00) Reason: Replaced by PRD.01.01.13 (Passkey Authentication) Action: Retain for traceability; do not implement
Original Requirement: {original_text}

---
Status: DEPRECATED (upstream removed 2026-02-10T16:00:00) Reason: Replaced by PRD.01.01.13 (Passkey Authentication) Action: Retain for traceability; do not implement
Original Requirement: {original_text}

---

6.5 Drift Cache Update

6.5 更新变更缓存

After processing drift, update
.drift_cache.json
:
json
{
  "document_version": "1.1",
  "last_synced": "2026-02-10T16:00:00",
  "sync_status": "auto-merged",
  "upstream_state": {
    "../01_BRD/BRD-01.1_core.md": {
      "hash": "sha256:a1b2c3d4e5f6...",
      "version": "2.3",
      "last_modified": "2026-02-10T15:30:00",
      "change_pct": 4.2,
      "sync_action": "tier1_auto_merge"
    },
    "../01_BRD/BRD-01.2_requirements.md": {
      "hash": "sha256:g7h8i9j0k1l2...",
      "version": "1.5",
      "last_modified": "2026-02-10T14:00:00",
      "change_pct": 8.7,
      "sync_action": "tier2_auto_merge_detailed"
    }
  },
  "merge_history": [
    {
      "date": "2026-02-10T16:00:00",
      "tier": 1,
      "change_pct": 4.2,
      "items_added": 1,
      "items_updated": 2,
      "version_before": "1.0",
      "version_after": "1.0.1"
    }
  ],
  "deprecated_items": [
    {
      "id": "PRD.01.01.05",
      "deprecated_date": "2026-02-10T16:00:00",
      "reason": "Upstream removal",
      "replaced_by": "PRD.01.01.13"
    }
  ]
}

处理完变更后,更新
.drift_cache.json
:
json
{
  "document_version": "1.1",
  "last_synced": "2026-02-10T16:00:00",
  "sync_status": "auto-merged",
  "upstream_state": {
    "../01_BRD/BRD-01.1_core.md": {
      "hash": "sha256:a1b2c3d4e5f6...",
      "version": "2.3",
      "last_modified": "2026-02-10T15:30:00",
      "change_pct": 4.2,
      "sync_action": "tier1_auto_merge"
    },
    "../01_BRD/BRD-01.2_requirements.md": {
      "hash": "sha256:g7h8i9j0k1l2...",
      "version": "1.5",
      "last_modified": "2026-02-10T14:00:00",
      "change_pct": 8.7,
      "sync_action": "tier2_auto_merge_detailed"
    }
  },
  "merge_history": [
    {
      "date": "2026-02-10T16:00:00",
      "tier": 1,
      "change_pct": 4.2,
      "items_added": 1,
      "items_updated": 2,
      "version_before": "1.0",
      "version_after": "1.0.1"
    }
  ],
  "deprecated_items": [
    {
      "id": "PRD.01.01.05",
      "deprecated_date": "2026-02-10T16:00:00",
      "reason": "Upstream removal",
      "replaced_by": "PRD.01.01.13"
    }
  ]
}

6.6 Fix Report: Drift Section

6.6 修复报告:变更章节

Drift Summary in Fix Report:
markdown
undefined
修复报告中的变更摘要:
markdown
undefined

Phase 6: Upstream Drift Resolution

Phase 6: Upstream Drift Resolution

Drift Analysis Summary

Drift Analysis Summary

Upstream DocumentChange %TierAction Taken
BRD-01.1_core.md4.2%1Auto-merged
BRD-01.2_requirements.md8.7%2Auto-merged (detailed)
BRD-01.3_quality_ops.md18.5%3Archived + Regenerated
Upstream DocumentChange %TierAction Taken
BRD-01.1_core.md4.2%1Auto-merged
BRD-01.2_requirements.md8.7%2Auto-merged (detailed)
BRD-01.3_quality_ops.md18.5%3Archived + Regenerated

Tier 1 Auto-Merges (< 5%)

Tier 1 Auto-Merges (< 5%)

IDTypeSourceDescription
PRD.01.01.13AddedBRD-01.1:3.5Passkey authentication support
PRD.01.02.05UpdatedBRD-01.1:4.2Session timeout 30->45 min
IDTypeSourceDescription
PRD.01.01.13AddedBRD-01.1:3.5Passkey authentication support
PRD.01.02.05UpdatedBRD-01.1:4.2Session timeout 30->45 min

Tier 2 Auto-Merges (5-15%)

Tier 2 Auto-Merges (5-15%)

IDTypeSourceDescription
PRD.01.01.14AddedBRD-01.2:5.3WebAuthn fallback mechanism
PRD.01.07.04AddedBRD-01.2:7.2New risk: credential phishing
IDTypeSourceDescription
PRD.01.01.14AddedBRD-01.2:5.3WebAuthn fallback mechanism
PRD.01.07.04AddedBRD-01.2:7.2New risk: credential phishing

Tier 3 Archives (> 15%)

Tier 3 Archives (> 15%)

DocumentPrevious VersionNew VersionReason
PRD-01.2_requirements.md1.22.018.5% upstream change
Archive Location:
docs/02_PRD/PRD-01_f1_iam/.archive/v1.2/
DocumentPrevious VersionNew VersionReason
PRD-01.2_requirements.md1.22.018.5% upstream change
Archive Location:
docs/02_PRD/PRD-01_f1_iam/.archive/v1.2/

Deprecated Items (No Deletion)

Deprecated Items (No Deletion)

IDDeprecated DateReasonReplaced By
PRD.01.01.052026-02-10T16:00:00Upstream removedPRD.01.01.13
IDDeprecated DateReasonReplaced By
PRD.01.01.052026-02-10T16:00:00Upstream removedPRD.01.01.13

Version Changes

Version Changes

FileBeforeAfterChange Type
PRD-01.1_core.md1.01.0.1Patch (Tier 1)
PRD-01.2_requirements.md1.01.1Minor (Tier 2)
PRD-01.3_features.md1.22.0Major (Tier 3)

---
FileBeforeAfterChange Type
PRD-01.1_core.md1.01.0.1Patch (Tier 1)
PRD-01.2_requirements.md1.01.1Minor (Tier 2)
PRD-01.3_features.md1.22.0Major (Tier 3)

---

Command Usage

命令使用

Basic Usage

基础用法

bash
undefined
bash
undefined

Fix PRD based on latest review

Fix PRD based on latest review

/doc-prd-fixer PRD-01
/doc-prd-fixer PRD-01

Fix with explicit review report

Fix with explicit review report

/doc-prd-fixer PRD-01 --review-report PRD-01.R_review_report_v001.md
/doc-prd-fixer PRD-01 --review-report PRD-01.R_review_report_v001.md

Fix and re-run review

Fix and re-run review

/doc-prd-fixer PRD-01 --revalidate
/doc-prd-fixer PRD-01 --revalidate

Fix with iteration limit

Fix with iteration limit

/doc-prd-fixer PRD-01 --revalidate --max-iterations 3
undefined
/doc-prd-fixer PRD-01 --revalidate --max-iterations 3
undefined

Options

选项

OptionDefaultDescription
--review-report
latestSpecific review report to use
--revalidate
falseRun reviewer after fixes
--max-iterations
3Max fix-review cycles
--fix-types
allSpecific fix types (comma-separated)
--create-missing
trueCreate missing reference files
--backup
trueBackup PRD before fixing
--dry-run
falsePreview fixes without applying
--acknowledge-drift
falseInteractive drift acknowledgment mode
--update-drift-cache
trueUpdate .drift_cache.json after fixes
选项默认值描述
--review-report
latest指定要使用的评审报告
--revalidate
false修复后运行评审工具
--max-iterations
3最大修复-评审循环次数
--fix-types
all指定修复类型(逗号分隔)
--create-missing
true创建缺失的参考文件
--backup
true修复前备份PRD
--dry-run
false预览修复内容但不实际应用
--acknowledge-drift
false交互式变更确认模式
--update-drift-cache
true修复后更新.drift_cache.json

Fix Types

修复类型

TypeDescription
missing_files
Create missing glossary, appendix, feature docs
broken_links
Fix link paths
element_ids
Convert invalid/legacy element IDs
content
Fix placeholders, dates, names
references
Update traceability and cross-references
drift
Handle upstream drift detection issues
all
All fix types (default)

类型描述
missing_files
创建缺失的术语表、附录、功能文档
broken_links
修复链接路径
element_ids
转换无效/旧版元素ID
content
修复占位符、日期、名称
references
更新可追溯性和交叉引用
drift
处理上游变更检测问题
all
所有修复类型(默认)

Output Artifacts

输出工件

Fix Report

修复报告

Nested Folder Rule: ALL PRDs use nested folders (
PRD-NN_{slug}/
) regardless of size. Fix reports are stored alongside the PRD document in the nested folder.
File Naming:
PRD-NN.F_fix_report_vNNN.md
Location: Inside the PRD nested folder:
docs/02_PRD/PRD-NN_{slug}/
Structure:
markdown
---
title: "PRD-NN.F: Fix Report v001"
tags:
  - prd
  - fix-report
  - quality-assurance
custom_fields:
  document_type: fix-report
  artifact_type: PRD-FIX
  layer: 2
  parent_doc: PRD-NN
  source_review: PRD-NN.R_review_report_v001.md
  fix_date: "YYYY-MM-DDTHH:MM:SS"
  fix_tool: doc-prd-fixer
  fix_version: "2.0"
---
嵌套文件夹规则:所有PRD无论大小,均使用嵌套文件夹(
PRD-NN_{slug}/
)。修复报告与PRD文档一同存储在嵌套文件夹中。
文件命名
PRD-NN.F_fix_report_vNNN.md
存储位置:PRD嵌套文件夹内:
docs/02_PRD/PRD-NN_{slug}/
结构:
markdown
---
title: "PRD-NN.F: Fix Report v001"
tags:
  - prd
  - fix-report
  - quality-assurance
custom_fields:
  document_type: fix-report
  artifact_type: PRD-FIX
  layer: 2
  parent_doc: PRD-NN
  source_review: PRD-NN.R_review_report_v001.md
  fix_date: "YYYY-MM-DDTHH:MM:SS"
  fix_tool: doc-prd-fixer
  fix_version: "2.0"
---

PRD-NN Fix Report v001

PRD-NN Fix Report v001

Summary

Summary

MetricValue
Source ReviewPRD-NN.R_review_report_v001.md
Issues in Review12
Issues Fixed10
Issues Remaining2 (manual review required)
Files Created2
Files Modified4
MetricValue
Source ReviewPRD-NN.R_review_report_v001.md
Issues in Review12
Issues Fixed10
Issues Remaining2 (manual review required)
Files Created2
Files Modified4

Files Created

Files Created

FileTypeLocation
PRD-00_GLOSSARY.mdProduct Glossarydocs/02_PRD/
PRD-01_APPENDIX_A.mdAppendix Placeholderdocs/02_PRD/
FileTypeLocation
PRD-00_GLOSSARY.mdProduct Glossarydocs/02_PRD/
PRD-01_APPENDIX_A.mdAppendix Placeholderdocs/02_PRD/

Fixes Applied

Fixes Applied

#Issue CodeIssueFix AppliedFile
1REV-L001Broken glossary linkCreated PRD-00_GLOSSARY.mdPRD-01.3_features.md
2REV-L004Broken BRD referenceUpdated path to ../01_BRD/BRD-01.mdPRD-01.1_core.md
3REV-N004Element type 25 invalidConverted to type 01PRD-01.1_core.md
4REV-L003Absolute path usedConverted to relativePRD-01.2_requirements.md
#Issue CodeIssueFix AppliedFile
1REV-L001Broken glossary linkCreated PRD-00_GLOSSARY.mdPRD-01.3_features.md
2REV-L004Broken BRD referenceUpdated path to ../01_BRD/BRD-01.mdPRD-01.1_core.md
3REV-N004Element type 25 invalidConverted to type 01PRD-01.1_core.md
4REV-L003Absolute path usedConverted to relativePRD-01.2_requirements.md

Issues Requiring Manual Review

Issues Requiring Manual Review

#Issue CodeIssueLocationReason
1REV-P001[TODO] placeholderPRD-01.2:L45Product decision needed
2REV-P006Missing user story formatPRD-01.2:L120Story refinement required
#Issue CodeIssueLocationReason
1REV-P001[TODO] placeholderPRD-01.2:L45Product decision needed
2REV-P006Missing user story formatPRD-01.2:L120Story refinement required

Validation After Fix

Validation After Fix

MetricBeforeAfterDelta
Review Score9297+5
Errors20-2
Warnings41-3
MetricBeforeAfterDelta
Review Score9297+5
Errors20-2
Warnings41-3

Next Steps

Next Steps

  1. Complete PRD-01_APPENDIX_A.md placeholder
  2. Address remaining [TODO] placeholders
  3. Run
    /doc-prd-reviewer PRD-01
    to verify fixes

---
  1. Complete PRD-01_APPENDIX_A.md placeholder
  2. Address remaining [TODO] placeholders
  3. Run
    /doc-prd-reviewer PRD-01
    to verify fixes

---

Integration with Autopilot

与自动生成工具的集成

This skill is invoked by
doc-prd-autopilot
in the Review -> Fix cycle:
mermaid
flowchart LR
    subgraph Phase5["Phase 5: Review & Fix Cycle"]
        A[doc-prd-reviewer] --> B{Score >= 90?}
        B -->|No| C[doc-prd-fixer]
        C --> D{Iteration < Max?}
        D -->|Yes| A
        D -->|No| E[Flag for Manual Review]
        B -->|Yes| F[PASS]
    end
Autopilot Integration Points:
PhaseActionSkill
Phase 5aRun initial review
doc-prd-reviewer
Phase 5bApply fixes if issues found
doc-prd-fixer
Phase 5cRe-run review
doc-prd-reviewer
Phase 5dRepeat until pass or max iterationsLoop

该工具在「评审→修复」循环中被
doc-prd-autopilot
调用:
mermaid
flowchart LR
    subgraph Phase5["Phase 5: Review & Fix Cycle"]
        A[doc-prd-reviewer] --> B{Score >= 90?}
        B -->|No| C[doc-prd-fixer]
        C --> D{Iteration < Max?}
        D -->|Yes| A
        D -->|No| E[Flag for Manual Review]
        B -->|Yes| F[PASS]
    end
自动生成工具集成点:
阶段动作工具
阶段5a运行初始评审
doc-prd-reviewer
阶段5b发现问题后应用修复
doc-prd-fixer
阶段5c重新运行评审
doc-prd-reviewer
阶段5d重复直到通过或达到最大迭代次数循环

Error Handling

错误处理

Recovery Actions

恢复操作

ErrorAction
Review report not foundPrompt to run
doc-prd-reviewer
first
Cannot create file (permissions)Log error, continue with other fixes
Cannot parse review reportAbort with clear error message
Max iterations exceededGenerate report, flag for manual review
BRD not foundLog warning, skip BRD-dependent fixes
错误动作
未找到评审报告提示先运行
doc-prd-reviewer
无法创建文件(权限问题)记录错误,继续其他修复
无法解析评审报告终止并显示清晰的错误信息
达到最大迭代次数生成报告,标记为需手动评审
未找到BRD记录警告,跳过依赖BRD的修复

Backup Strategy

备份策略

Before applying any fixes:
  1. Create backup in
    tmp/backup/PRD-NN_YYYYMMDD_HHMMSS/
  2. Copy all PRD files to backup location
  3. Apply fixes to original files
  4. If error during fix, restore from backup

应用任何修复前:
  1. tmp/backup/PRD-NN_YYYYMMDD_HHMMSS/
    创建备份
  2. 将所有PRD文件复制到备份位置
  3. 对原始文件应用修复
  4. 修复过程中出错时,从备份恢复

Related Skills

相关工具

SkillRelationship
doc-prd-reviewer
Provides review report (input)
doc-prd-autopilot
Orchestrates Review -> Fix cycle
doc-prd-validator
Structural validation
doc-naming
Element ID standards
doc-prd
PRD creation rules
doc-brd-reviewer
Upstream BRD validation

工具关系
doc-prd-reviewer
提供评审报告(输入)
doc-prd-autopilot
编排「评审→修复」循环
doc-prd-validator
结构验证
doc-naming
元素ID标准
doc-prd
PRD创建规则
doc-brd-reviewer
上游BRD验证

Version History

版本历史

VersionDateChanges
2.12026-02-11Structure Compliance: Added Phase 0 for nested folder rule enforcement (REV-STR001-STR004); Fixed all path comments to use nested folders for both monolithic and sectioned PRDs; Updated link path calculations for mandatory nested structure
2.02026-02-10T16:00:00Major: Implemented tiered auto-merge system - Tier 1 (<5%): auto-merge additions/updates with patch version increment; Tier 2 (5-15%): auto-merge with detailed changelog and minor version increment; Tier 3 (>15%): archive current version and trigger regeneration with major version increment; No deletion policy (mark as DEPRECATED instead); Auto-generated IDs for new requirements (PRD.NN.TT.SS format); Archive manifest creation; Enhanced drift cache with merge history
1.02026-02-10T15:00:00Initial skill creation; 6-phase fix workflow; Glossary and feature file creation; Element ID conversion for PRD codes (01-09, 11, 22, 24); Broken link fixes; BRD drift detection; Integration with autopilot Review->Fix cycle
版本日期变更
2.12026-02-11结构合规性:新增阶段0用于强制实施嵌套文件夹规则(REV-STR001-STR004);修复所有路径注释,使单体式和分段式PRD均使用嵌套文件夹;更新强制嵌套结构下的链接路径计算
2.02026-02-10T16:00:00重大更新:实现分级自动合并系统 - 第一级(<5%):自动合并新增/更新内容并升级补丁版本;第二级(5-15%):自动合并并生成详细变更日志,升级次要版本;第三级(>15%):归档当前版本并触发重新生成,升级主版本;不删除策略(标记为DEPRECATED而非删除);为新增需求自动生成ID(PRD.NN.TT.SS格式);创建归档清单;增强变更缓存,添加合并历史
1.02026-02-10T15:00:00初始版本创建;6阶段修复工作流;术语表和功能文件创建;PRD代码的元素ID转换(01-09、11、22、24);失效链接修复;BRD变更检测;与自动生成工具的「评审→修复」循环集成