extract-requirements

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Extract Requirements Workflow

需求提取工作流

Purpose

目的

Systematic process for extracting business requirements from undocumented or poorly documented codebases.
从无文档或文档不完善的代码库中系统化提取业务需求的流程。

When to Use

适用场景

  • ✅ Legacy system with no documentation
  • ✅ Planning migration (need requirements baseline)
  • ✅ M&A due diligence (understand acquired system)
  • ✅ Compliance audit (document what system does)
  • ✅ Knowledge transfer (developers leaving)
  • ✅ 无配套文档的遗留系统
  • ✅ 系统迁移规划(需要需求基准)
  • ✅ 并购尽职调查(了解被收购系统)
  • ✅ 合规审计(记录系统实际功能)
  • ✅ 知识转移(核心开发人员离职)

Prerequisites

前置条件

Codebase Indexed

代码库已索引

bash
codecompass batch:index <path>
bash
codecompass batch:index <path>

Infrastructure Running

基础设施正常运行

bash
codecompass health
bash
codecompass health

Extraction Workflow

提取工作流

Phase 1: Automated Extraction

阶段1:自动化提取

Step 1.1: Run Requirements Extractor
bash
codecompass requirements:extract --project-id <id> --output requirements.md
What this extracts:
  1. Validation Rules → Business constraints
  2. Controller Actions → Use cases
  3. Database Constraints → Data integrity rules
  4. RBAC/Authorization → Access requirements
  5. Business Logic → Domain rules
Step 1.2: Review Output Check generated
requirements.md
:
  • Completeness (coverage of major features)
  • Accuracy (rules match actual behavior)
  • Gaps (missing business logic)
步骤1.1:运行需求提取工具
bash
codecompass requirements:extract --project-id <id> --output requirements.md
提取内容:
  1. 验证规则 → 业务约束
  2. 控制器动作 → 用例
  3. 数据库约束 → 数据完整性规则
  4. RBAC/授权机制 → 访问需求
  5. 业务逻辑 → 领域规则
步骤1.2:审核输出结果 检查生成的
requirements.md
  • 完整性(覆盖主要功能)
  • 准确性(规则与实际行为匹配)
  • 遗漏点(缺失的业务逻辑)

Phase 2: Validation Rule Analysis

阶段2:验证规则分析

From Models/Entities:
php
// Yii2 Model example
public function rules() {
  return [
    [['email', 'password'], 'required'],
    ['email', 'email'],
    ['password', 'string', 'min' => 8],
    ['age', 'integer', 'min' => 18],
  ];
}
Extracted Requirements:
markdown
undefined
从模型/实体中提取:
php
// Yii2 Model示例
public function rules() {
  return [
    [['email', 'password'], 'required'],
    ['email', 'email'],
    ['password', 'string', 'min' => 8],
    ['age', 'integer', 'min' => 18],
  ];
}
提取的需求:
markdown
undefined

User Registration Requirements

用户注册需求

  • REQ-001: Email address is mandatory
  • REQ-002: Email must be valid format
  • REQ-003: Password is mandatory
  • REQ-004: Password minimum length: 8 characters
  • REQ-005: User must be at least 18 years old
undefined
  • REQ-001:邮箱地址为必填项
  • REQ-002:邮箱格式必须合法
  • REQ-003:密码为必填项
  • REQ-004:密码最小长度为8个字符
  • REQ-005:用户年龄必须至少18岁
undefined

Phase 3: Use Case Extraction

阶段3:用例提取

From Controllers:
php
// Controller actions → Use cases
public function actionCreate() {
  // Use Case: Create New Order
}

public function actionApprove($id) {
  // Use Case: Approve Order (with authorization check)
}

public function actionCancel($id) {
  // Use Case: Cancel Order (business rules apply)
}
Extracted Use Cases:
markdown
undefined
从控制器中提取:
php
// 控制器动作 → 用例
public function actionCreate() {
  // 用例:创建新订单
}

public function actionApprove($id) {
  // 用例:审批订单(含授权校验)
}

public function actionCancel($id) {
  // 用例:取消订单(需遵循业务规则)
}
提取的用例:
markdown
undefined

Order Management Use Cases

订单管理用例

UC-001: Create New Order

UC-001:创建新订单

Actor: Customer Preconditions: User authenticated Steps:
  1. User selects products
  2. System validates inventory
  3. User provides shipping address
  4. System calculates total
  5. Order created in pending status
参与者:客户 前置条件:用户已认证 步骤:
  1. 用户选择商品
  2. 系统校验库存
  3. 用户提供收货地址
  4. 系统计算订单总额
  5. 订单创建为待处理状态

UC-002: Approve Order

UC-002:审批订单

Actor: Manager Preconditions:
  • Order in pending status
  • User has 'manager' role Steps:
  1. Manager reviews order details
  2. System validates business rules
  3. Order status changed to approved
  4. Notification sent to customer
undefined
参与者:管理员 前置条件:
  • 订单处于待处理状态
  • 用户拥有「管理员」角色 步骤:
  1. 管理员查看订单详情
  2. 系统校验业务规则
  3. 订单状态变更为已审批
  4. 向客户发送通知
undefined

Phase 4: Business Rule Discovery

阶段4:业务规则发现

Semantic Search for Rules:
bash
codecompass search:semantic "business validation rules for order approval"
codecompass search:semantic "conditions for discount calculation"
codecompass search:semantic "authorization checks for admin actions"
Common Patterns to Find:
  1. Conditional Logic → Business rules
  2. Status Transitions → Workflow states
  3. Calculations → Business formulas
  4. Validations → Constraints
  5. Authorization Checks → Access rules
规则语义搜索:
bash
codecompass search:semantic "business validation rules for order approval"
codecompass search:semantic "conditions for discount calculation"
codecompass search:semantic "authorization checks for admin actions"
需查找的常见模式:
  1. 条件逻辑 → 业务规则
  2. 状态转换 → 工作流状态
  3. 计算逻辑 → 业务公式
  4. 校验逻辑 → 约束规则
  5. 授权校验 → 访问规则

Phase 5: Data Model Requirements

阶段5:数据模型需求

From Database Schema:
sql
CREATE TABLE orders (
  id INT PRIMARY KEY,
  status ENUM('pending', 'approved', 'shipped', 'cancelled'),
  total DECIMAL(10,2) NOT NULL CHECK (total >= 0),
  customer_id INT NOT NULL FOREIGN KEY REFERENCES customers(id),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Extracted Requirements:
markdown
undefined
从数据库架构中提取:
sql
CREATE TABLE orders (
  id INT PRIMARY KEY,
  status ENUM('pending', 'approved', 'shipped', 'cancelled'),
  total DECIMAL(10,2) NOT NULL CHECK (total >= 0),
  customer_id INT NOT NULL FOREIGN KEY REFERENCES customers(id),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
提取的需求:
markdown
undefined

Data Requirements

数据需求

  • REQ-010: Order must have unique identifier
  • REQ-011: Order status: pending, approved, shipped, or cancelled
  • REQ-012: Order total must be non-negative
  • REQ-013: Order must be associated with a customer
  • REQ-014: Order creation timestamp must be recorded
undefined
  • REQ-010:订单必须拥有唯一标识符
  • REQ-011:订单状态可选值:pending、approved、shipped、cancelled
  • REQ-012:订单总额必须非负
  • REQ-013:订单必须关联至某个客户
  • REQ-014:必须记录订单创建时间戳
undefined

Phase 6: Workflow Mapping

阶段6:工作流映射

Identify State Machines:
Order Status Flow:
pending → approved → shipped → delivered
         cancelled
Extract Transitions:
markdown
undefined
识别状态机:
订单状态流转:
pending → approved → shipped → delivered
         cancelled
提取状态转换规则:
markdown
undefined

Order Workflow

订单工作流

States: pending, approved, shipped, cancelled, delivered
Transitions:
  • pending → approved (requires: manager approval)
  • approved → shipped (requires: items in stock)
  • shipped → delivered (requires: delivery confirmation)
  • pending|approved → cancelled (requires: cancellation reason)
Business Rules:
  • Cannot cancel after shipped
  • Cannot approve if out of stock
  • Refund required if cancelled after payment
undefined
状态:pending、approved、shipped、cancelled、delivered
转换规则:
  • pending → approved(要求:管理员审批)
  • approved → shipped(要求:商品有库存)
  • shipped → delivered(要求:确认送达)
  • pending|approved → cancelled(要求:提供取消原因)
业务规则:
  • 订单发货后无法取消
  • 库存不足时无法审批订单
  • 付款后取消订单需办理退款
undefined

Extraction Techniques

提取技巧

Technique 1: Code Reading Patterns

技巧1:代码阅读模式

Look for:
  • if
    statements → Business conditions
  • switch/case
    → State transitions
  • Loops → Bulk operations
  • Exceptions → Error handling requirements
  • Comments → Intent (when present)
重点关注:
  • if
    语句 → 业务条件
  • switch/case
    → 状态转换
  • 循环 → 批量操作
  • 异常处理 → 错误处理需求
  • 注释 → 代码意图(如果存在)

Technique 2: Test Analysis

技巧2:测试用例分析

Tests reveal:
  • Expected behavior (what should happen)
  • Edge cases (what shouldn't happen)
  • Valid input ranges
  • Error scenarios
bash
codecompass search:semantic "test cases for order validation"
测试用例可揭示:
  • 预期行为(应该发生的操作)
  • 边缘场景(不应该发生的操作)
  • 合法输入范围
  • 错误场景
bash
codecompass search:semantic "test cases for order validation"

Technique 3: Configuration Analysis

技巧3:配置文件分析

Config files contain:
  • Feature flags → Optional requirements
  • Limits/thresholds → Business constraints
  • Integration settings → External dependencies
配置文件包含:
  • 功能开关 → 可选需求
  • 限制阈值 → 业务约束
  • 集成设置 → 外部依赖

Technique 4: Semantic Clustering

技巧4:语义聚类

Find related code:
bash
undefined
查找关联代码:
bash
undefined

Find all code related to "discount calculation"

查找所有与「折扣计算」相关的代码

codecompass search:semantic "discount calculation logic"
codecompass search:semantic "discount calculation logic"

Find all code related to "inventory management"

查找所有与「库存管理」相关的代码

codecompass search:semantic "inventory stock management"

Group results by business capability
codecompass search:semantic "inventory stock management"

按业务能力对结果进行分组

Output Formats

输出格式

Format 1: Requirements Document (Markdown)

格式1:需求文档(Markdown)

markdown
undefined
markdown
undefined

Business Requirements - [System Name]

业务需求 - [系统名称]

Functional Requirements

功能需求

FR-001: User Authentication

FR-001:用户认证

Priority: High Description: System must authenticate users via email and password Acceptance Criteria:
  • Email validation follows RFC 5322
  • Password minimum 8 characters
  • Account locked after 5 failed attempts Source: UserController::actionLogin(), User::validatePassword()
优先级: 高 描述: 系统必须支持通过邮箱和密码验证用户身份 验收标准:
  • 邮箱验证遵循RFC 5322标准
  • 密码长度至少8个字符
  • 连续5次验证失败后锁定账户 来源: UserController::actionLogin(), User::validatePassword()

FR-002: Order Approval Workflow

FR-002:订单审批工作流

...
undefined
...
undefined

Format 2: Capability Map (Structured)

格式2:能力图谱(结构化)

json
{
  "capabilities": {
    "user_management": {
      "features": ["register", "login", "reset_password"],
      "rules": ["email_unique", "password_complexity"],
      "roles": ["user", "admin"]
    },
    "order_processing": {
      "features": ["create", "approve", "cancel", "ship"],
      "rules": ["approval_required", "inventory_check"],
      "workflow": "pending→approved→shipped→delivered"
    }
  }
}
json
{
  "capabilities": {
    "user_management": {
      "features": ["register", "login", "reset_password"],
      "rules": ["email_unique", "password_complexity"],
      "roles": ["user", "admin"]
    },
    "order_processing": {
      "features": ["create", "approve", "cancel", "ship"],
      "rules": ["approval_required", "inventory_check"],
      "workflow": "pending→approved→shipped→delivered"
    }
  }
}

Format 3: Use Case Catalog

格式3:用例目录

markdown
| UC ID | Use Case Name | Actor | Complexity |
|-------|---------------|-------|------------|
| UC-001 | Create Order | Customer | Medium |
| UC-002 | Approve Order | Manager | Low |
| UC-003 | Cancel Order | Customer/Manager | High |
markdown
| 用例ID | 用例名称 | 参与者 | 复杂度 |
|-------|---------------|-------|------------|
| UC-001 | 创建订单 | 客户 | 中等 |
| UC-002 | 审批订单 | 管理员 ||
| UC-003 | 取消订单 | 客户/管理员 ||

Validation Steps

验证步骤

Step 1: Cross-Check with Tests

步骤1:与测试用例交叉校验

Compare extracted requirements with test cases:
  • Tests validate requirements
  • Missing tests → Undocumented behavior
  • Failing tests → Requirements changed
将提取的需求与测试用例对比:
  • 测试用例验证需求是否正确
  • 缺失测试用例 → 无文档记录的行为
  • 测试用例失败 → 需求已变更

Step 2: Semantic Verification

步骤2:语义验证

bash
undefined
bash
undefined

For each requirement, verify in code

针对每个需求,在代码中验证

codecompass search:semantic "password must be at least 8 characters"

Should find validator implementation
codecompass search:semantic "password must be at least 8 characters"

应能找到对应的校验实现

Step 3: Interview Stakeholders (if available)

步骤3: stakeholder访谈(若可行)

  • Validate extracted requirements
  • Fill gaps in documentation
  • Clarify ambiguous logic
  • 验证提取的需求准确性
  • 填补文档空白
  • 澄清模糊逻辑

Step 4: Traceability Matrix

步骤4:可追溯性矩阵

Map requirements to code:
markdown
| Requirement | Source Files | Tests |
|-------------|--------------|-------|
| REQ-001 | User.php:45, UserController.php:102 | UserTest.php:23 |
| REQ-002 | Order.php:78 | OrderTest.php:56 |
将需求与代码关联映射:
markdown
| 需求ID | 来源文件 | 测试用例 |
|-------------|--------------|-------|
| REQ-001 | User.php:45, UserController.php:102 | UserTest.php:23 |
| REQ-002 | Order.php:78 | OrderTest.php:56 |

Common Patterns

常见模式

Pattern 1: Implicit Requirements

模式1:隐含需求

Code:
php
if ($order->total < 1000) {
  // No approval needed
}
Requirement:
markdown
REQ: Orders under $1000 do not require manager approval
代码:
php
if ($order->total < 1000) {
  // 无需审批
}
需求:
markdown
REQ:订单金额低于1000美元无需管理员审批

Pattern 2: Embedded Business Logic

模式2:嵌入式业务逻辑

Code:
php
$discount = ($customer->vip) ? 0.20 : 0.10;
Requirement:
markdown
REQ: VIP customers receive 20% discount, regular customers 10%
代码:
php
$discount = ($customer->vip) ? 0.20 : 0.10;
需求:
markdown
REQ:VIP客户享受20%折扣,普通客户享受10%折扣

Pattern 3: Temporal Constraints

模式3:时间约束

Code:
php
if (strtotime($order->created_at) > strtotime('-30 days')) {
  // Can cancel
}
Requirement:
markdown
REQ: Orders can only be cancelled within 30 days of creation
代码:
php
if (strtotime($order->created_at) > strtotime('-30 days')) {
  // 可取消
}
需求:
markdown
REQ:订单仅可在创建后30天内取消

Best Practices

最佳实践

✅ Do

✅ 建议

  • Extract from multiple sources (code, tests, configs)
  • Use semantic search for concept discovery
  • Validate with tests
  • Document sources for traceability
  • Prioritize by business impact
  • Include non-functional requirements (performance, security)
  • 从多来源提取需求(代码、测试用例、配置文件)
  • 使用语义搜索发现业务概念
  • 结合测试用例验证需求
  • 记录需求来源以保证可追溯性
  • 按业务影响优先级排序需求
  • 包含非功能需求(性能、安全)

❌ Don't

❌ 禁忌

  • Rely solely on comments (often outdated)
  • Assume standard behavior without verification
  • Skip edge cases
  • Ignore error handling logic
  • Document technical implementation instead of business requirements
  • 仅依赖注释(通常已过时)
  • 未验证就假设标准行为
  • 忽略边缘场景
  • 忽略错误处理逻辑
  • 记录技术实现细节而非业务需求

Related Skills

相关技能

  • 0-discover-capabilities.md
    - Find relevant modules
  • semantic-search.md
    - Search for business logic
  • analyze-yii2-project.md
    - Framework-specific extraction
  • 0-discover-capabilities.md
    - 查找相关模块
  • semantic-search.md
    - 业务逻辑语义搜索
  • analyze-yii2-project.md
    - 框架专属提取方法

Related Modules

相关模块

From
.ai/capabilities.json
:
  • requirements
    - RequirementsExtractionService
  • business-analyzer
    - CapabilityCatalogService
  • search
    - Semantic code search
  • analyzers
    - Code analysis for extraction

Remember: Requirements are what the system must do, not how it does it. Focus on business value, not technical implementation.
来自
.ai/capabilities.json
:
  • requirements
    - RequirementsExtractionService
  • business-analyzer
    - CapabilityCatalogService
  • search
    - 语义代码搜索
  • analyzers
    - 提取用代码分析器

注意:需求是指系统必须实现的功能,而非实现方式。应聚焦业务价值,而非技术实现细节。