feat: implement feature-driven artifact architecture for brainstorm-plan-execute pipeline

Restructure brainstorm artifacts from role-dimension to feature-dimension
to eliminate information loss at the brainstorm→plan boundary. Key changes:

- artifacts.md: Add Phase 4.5 Feature Decomposition in guidance-specification
- conceptual-planning-agent.md: Name sub-docs by feature (analysis-F-{id}-{slug}.md)
- role-analysis.md: Pass feature list to Phase 3 agent prompts
- synthesis.md: Add Phase 6 parallel feature spec generation + feature-index.json
- task-generate-agent.md: Inject feature-index.json path into agent prompts
- context-search-agent.md: Flatten brainstorm_artifacts structure (feature_index,
  feature_specs, cross_cutting_specs as top-level fields)
- action-planning-agent.md: Add feature-index driven on-demand loading, plan-time
  expansion for pre_analysis commands, fix cross_cutting_specs string array access
This commit is contained in:
catlog22
2026-02-11 16:32:30 +08:00
parent 8475a724ae
commit 5a4350beb4
7 changed files with 891 additions and 74 deletions

View File

@@ -82,9 +82,17 @@ color: yellow
4. Load brainstorming artifacts (in priority order) 4. Load brainstorming artifacts (in priority order)
a. guidance-specification.md (Highest Priority) a. guidance-specification.md (Highest Priority)
→ Overall design framework and architectural decisions → Overall design framework and architectural decisions
b. Role analyses (progressive loading: load incrementally by priority) b. Feature specs (on-demand via feature-index.json)
→ If .brainstorming/feature-specs/feature-index.json exists:
1. Load feature-index.json → get feature catalog (id, slug, priority, spec_path)
2. Load only feature-specs referenced by current task (1-2 per task)
3. Load cross-cutting specs only when task touches shared concerns
→ Reason: On-demand loading reduces per-task context from 40K+ to 3-5K words
→ Backward compatibility: If feature-index.json does NOT exist →
Fall back to role analyses (progressive loading by priority, see 4b-fallback)
b-fallback. Role analyses (legacy, only when feature-index.json absent)
→ Load role analysis files one at a time as needed → Load role analysis files one at a time as needed
Reason: Each analysis.md is long; progressive loading prevents token overflow Progressive loading prevents token overflow
c. Synthesis output (if exists) c. Synthesis output (if exists)
→ Integrated view with clarifications → Integrated view with clarifications
d. Conflict resolution (if conflict_risk ≥ medium) d. Conflict resolution (if conflict_risk ≥ medium)
@@ -140,8 +148,21 @@ mcp__exa__get_code_context_exa(
- `brainstorm_artifacts.guidance_specification`: Overall design framework (if exists) - `brainstorm_artifacts.guidance_specification`: Overall design framework (if exists)
- Check: `brainstorm_artifacts?.guidance_specification?.exists === true` - Check: `brainstorm_artifacts?.guidance_specification?.exists === true`
- Content: Use `content` field if present, else load from `path` - Content: Use `content` field if present, else load from `path`
- `brainstorm_artifacts.role_analyses[]`: Role-specific analyses (if array not empty) - `brainstorm_artifacts.feature_index`: Feature catalog index (if feature-mode brainstorming)
- Check: `brainstorm_artifacts?.feature_index?.exists === true`
- Content: JSON with `{features[], cross_cutting_specs[]}` - load from `path`
- **When present**: Use feature-index as primary entry point for on-demand spec loading
- `brainstorm_artifacts.feature_specs[]`: Individual feature specification files (from context-package)
- Each spec: `feature_specs[i]` has `path` and `content`
- **Load on-demand**: Only load specs referenced by current task's feature mapping
- **Note**: For structured metadata (`feature_id`, `slug`, `priority`), use `feature_index.features[]` instead
- `brainstorm_artifacts.cross_cutting_specs[]`: Cross-cutting concern specifications (from context-package)
- Each spec: `cross_cutting_specs[i]` has `path` and `content`
- **Load on-demand**: Only load when task touches shared/cross-cutting concerns
- **Note**: In feature-index.json, `cross_cutting_specs[]` is a plain string array (relative paths)
- `brainstorm_artifacts.role_analyses[]`: Role-specific analyses (legacy fallback, if array not empty)
- Each role: `role_analyses[i].files[j]` has `path` and `content` - Each role: `role_analyses[i].files[j]` has `path` and `content`
- **Only used when**: `feature_index` does not exist (backward compatibility)
- `brainstorm_artifacts.synthesis_output`: Synthesis results (if exists) - `brainstorm_artifacts.synthesis_output`: Synthesis results (if exists)
- Check: `brainstorm_artifacts?.synthesis_output?.exists === true` - Check: `brainstorm_artifacts?.synthesis_output?.exists === true`
- Content: Use `content` field if present, else load from `path` - Content: Use `content` field if present, else load from `path`
@@ -160,8 +181,31 @@ if (contextPackage.brainstorm_artifacts?.guidance_specification?.exists) {
const content = spec.content || Read(spec.path); const content = spec.content || Read(spec.path);
} }
if (contextPackage.brainstorm_artifacts?.role_analyses?.length > 0) { // Feature-index driven loading (PREFERRED - on-demand)
// Progressive loading: load role analyses incrementally by priority if (contextPackage.brainstorm_artifacts?.feature_index?.exists) {
// Step 1: Load feature-index.json for catalog
const featureIndex = JSON.parse(Read(contextPackage.brainstorm_artifacts.feature_index.path));
// Step 2: Load only task-relevant feature specs (1-2 per task)
const taskFeatureIds = task.context.artifacts
.filter(a => a.type === 'feature_spec')
.map(a => a.feature_id);
featureIndex.features
.filter(f => taskFeatureIds.includes(f.id))
.forEach(f => {
const specContent = Read(f.spec_path); // On-demand: only what this task needs
});
// Step 3: Load cross-cutting specs only when needed
// Note: cross_cutting_specs in feature-index.json is a string array (relative paths)
featureIndex.cross_cutting_specs
.filter(cs => task.context.artifacts.some(a => a.type === 'cross_cutting_spec' && a.path === cs))
.forEach(cs => {
const crossCuttingContent = Read(cs);
});
} else if (contextPackage.brainstorm_artifacts?.role_analyses?.length > 0) {
// FALLBACK: Legacy role analysis progressive loading (when feature-index absent)
contextPackage.brainstorm_artifacts.role_analyses.forEach(role => { contextPackage.brainstorm_artifacts.role_analyses.forEach(role => {
role.files.forEach(file => { role.files.forEach(file => {
const analysis = file.content || Read(file.path); // Load one at a time const analysis = file.content || Read(file.path); // Load one at a time
@@ -376,12 +420,13 @@ userConfig.executionMethod → meta.execution_config
}, },
"artifacts": [ "artifacts": [
{ {
"type": "synthesis_specification|topic_framework|individual_role_analysis", "type": "feature_spec|cross_cutting_spec|synthesis_specification|topic_framework|individual_role_analysis",
"source": "brainstorm_clarification|brainstorm_framework|brainstorm_roles", "source": "brainstorm_feature_specs|brainstorm_cross_cutting|brainstorm_clarification|brainstorm_framework|brainstorm_roles",
"path": "{from artifacts_inventory}", "path": "{from feature-index.json or artifacts_inventory}",
"feature_id": "F-NNN (feature_spec only)",
"priority": "highest|high|medium|low", "priority": "highest|high|medium|low",
"usage": "Architecture decisions and API specifications", "usage": "Feature requirements and design specifications",
"contains": "role_specific_requirements_and_design" "contains": "feature_specific_requirements_and_design"
} }
] ]
} }
@@ -398,12 +443,27 @@ userConfig.executionMethod → meta.execution_config
- `artifacts`: Referenced brainstorming outputs with detailed metadata - `artifacts`: Referenced brainstorming outputs with detailed metadata
**Artifact Mapping** (from context package): **Artifact Mapping** (from context package):
- Use `artifacts_inventory` from context package - **Feature-index mode** (when `feature_index` exists): Use feature-index.json as primary catalog
- **Priority levels**: - **Legacy mode** (fallback): Use `artifacts_inventory` from context package
- **Highest**: synthesis_specification (integrated view with clarifications)
- **High**: topic_framework (guidance-specification.md) - **Artifact Types & Priority**:
- **Medium**: individual_role_analysis (system-architect, subject-matter-expert, etc.) - **`feature_spec`** (Highest): Feature specification from feature-index.json
- **Low**: supporting documentation - `{type: "feature_spec", source: "brainstorm_feature_specs", path: "<spec_path>", feature_id: "<F-NNN>", priority: "highest", usage: "<task-specific usage>", contains: "<feature scope description>"}`
- Each task references 1-2 feature specs based on task scope
- **`cross_cutting_spec`** (High): Cross-cutting concern specification
- `{type: "cross_cutting_spec", source: "brainstorm_cross_cutting", path: "<spec_path>", priority: "high", usage: "<why this task needs it>", contains: "<cross-cutting scope>"}`
- Load only when task touches shared concerns (auth, logging, error handling, etc.)
- **`synthesis_specification`** (High): Integrated view with clarifications
- **`topic_framework`** (High): guidance-specification.md
- **`individual_role_analysis`** (Medium): Legacy role analyses (system-architect, etc.)
- **Low**: Supporting documentation
- **Task-Feature Mapping Rules** (feature-index mode):
1. Read feature-index.json `features[]` array
2. For each task, identify 1-2 primary features by matching task scope to feature `name`/`slug`
3. Add matching feature specs as `feature_spec` artifacts with `feature_id` field
4. Check `cross_cutting_refs` in matched features; add referenced cross-cutting specs as `cross_cutting_spec` artifacts
5. Result: Each task's `context.artifacts[]` contains only the specs it needs (not all specs)
#### Flow Control Object #### Flow Control Object
@@ -448,7 +508,7 @@ userConfig.executionMethod → meta.execution_config
##### Pre-Analysis Patterns ##### Pre-Analysis Patterns
**Dynamic Step Selection Guidelines**: **Dynamic Step Selection Guidelines**:
- **Context Loading**: Always include context package and role analysis loading - **Context Loading**: Always include context package and feature spec loading (or role analysis fallback)
- **Architecture Analysis**: Add module structure analysis for complex projects - **Architecture Analysis**: Add module structure analysis for complex projects
- **Pattern Discovery**: Use CLI tools (gemini/qwen/bash) based on task complexity and available tools - **Pattern Discovery**: Use CLI tools (gemini/qwen/bash) based on task complexity and available tools
- **Tech-Specific Analysis**: Add language/framework-specific searches for specialized tasks - **Tech-Specific Analysis**: Add language/framework-specific searches for specialized tasks
@@ -465,19 +525,51 @@ userConfig.executionMethod → meta.execution_config
"on_error": "fail" "on_error": "fail"
}, },
{ {
"step": "load_role_analysis_artifacts", "step": "load_brainstorm_artifacts",
"action": "Load role analyses from context-package.json (progressive loading by priority)", "action": "Load brainstorm artifacts referenced by this task's context.artifacts[]",
"commands": [ "commands": "<<PLAN-TIME EXPANSION: Replace with concrete Read() commands>>",
"Read({{context_package_path}})", "output_to": "brainstorm_context",
"Extract(brainstorm_artifacts.role_analyses[].files[].path)",
"Read(extracted paths progressively)"
],
"output_to": "role_analysis_artifacts",
"on_error": "skip_optional" "on_error": "skip_optional"
} }
] ]
``` ```
**Plan-Time Expansion Rule for `load_brainstorm_artifacts`**:
When generating each task JSON, agent MUST expand this template step into concrete `Read()` commands based on the task's `context.artifacts[]` array. Since the agent writes both `context.artifacts[]` and `flow_control.pre_analysis[]` simultaneously, the artifact paths are known at plan time.
**Expansion Algorithm**:
```javascript
function expandArtifactLoadStep(taskArtifacts) {
const commands = [];
// Expand each artifact reference into a concrete Read() command
for (const artifact of taskArtifacts) {
commands.push(`Read(${artifact.path})`);
}
// Fallback: if no artifacts, load role analyses from context-package
if (commands.length === 0) {
commands.push("Read(brainstorm_artifacts.role_analyses[0].files[0].path)");
}
return commands;
}
```
**Example** - Task with 1 feature spec + 1 cross-cutting spec:
```json
{
"step": "load_brainstorm_artifacts",
"action": "Load feature spec F-001 and cross-cutting architecture spec",
"commands": [
"Read(.brainstorming/feature-specs/F-001-auth.md)",
"Read(.brainstorming/system-architect/analysis-cross-cutting.md)"
],
"output_to": "brainstorm_context",
"on_error": "skip_optional"
}
```
**Key**: `pre_analysis.commands[]` must only contain tool-call formats that code-developer can parse: `Read(path)`, `bash(cmd)`, `Search(pattern,path)`, `Glob(pattern)`, `mcp__xxx__yyy(args)`.
**Optional Steps** (Select and adapt based on task needs): **Optional Steps** (Select and adapt based on task needs):
```json ```json
@@ -528,7 +620,7 @@ The examples above demonstrate **patterns**, not fixed requirements. Agent MUST:
1. **Always Include** (Required): 1. **Always Include** (Required):
- `load_context_package` - Essential for all tasks - `load_context_package` - Essential for all tasks
- `load_role_analysis_artifacts` - Critical for accessing brainstorming insights - `load_brainstorm_artifacts` - Load brainstorm artifacts referenced by task's `context.artifacts[]`; falls back to role analysis progressive loading when no feature_spec artifacts
2. **Progressive Addition of Analysis Steps**: 2. **Progressive Addition of Analysis Steps**:
Include additional analysis steps as needed for comprehensive planning: Include additional analysis steps as needed for comprehensive planning:

View File

@@ -220,23 +220,35 @@ Generate documents according to loaded role template specifications:
**Output Location**: `.workflow/WFS-[session]/.brainstorming/[assigned-role]/` **Output Location**: `.workflow/WFS-[session]/.brainstorming/[assigned-role]/`
**Output Files**: **Output Files** (feature-point organization when `feature_list` available):
- **analysis.md**: Index document with overview (optionally with `@` references to sub-documents) - **analysis.md**: Role overview index document with feature point listing and cross-cutting summary (< 1500 words)
- Contains: role perspective overview, feature point index with `@` references, cross-cutting summary
- **FORBIDDEN**: Never create `recommendations.md` or any file not starting with `analysis` prefix - **FORBIDDEN**: Never create `recommendations.md` or any file not starting with `analysis` prefix
- **analysis-{slug}.md**: Section content documents (slug from section heading: lowercase, hyphens) - **analysis-cross-cutting.md**: Cross-feature architectural decisions, technology choices, shared patterns (< 2000 words)
- Maximum 5 sub-documents (merge related sections if needed) - Contains: decisions/patterns that span multiple features, shared constraints, role-wide recommendations
- **Content**: Analysis AND recommendations sections - **analysis-F-{id}-{slug}.md**: Per-feature analysis documents (< 2000 words each)
- `{id}` and `{slug}` come from `guidance-specification.md` Feature Decomposition table
- Example: `analysis-F-001-real-time-sync.md`, `analysis-F-002-user-auth.md`
- Contains: role-specific analysis, recommendations, and considerations for that feature
- Generate one sub-document per feature in the feature list
**File Structure Example**: **Backward Compatibility** (when `feature_list` is NOT available):
- Fall back to existing organization: `analysis-{slug}.md` with arbitrary topic slugs
- Maximum 5 sub-documents (merge related sections if needed)
- analysis.md remains the main document with overview
**File Structure Example** (feature-point mode):
``` ```
.workflow/WFS-[session]/.brainstorming/system-architect/ .workflow/WFS-[session]/.brainstorming/system-architect/
├── analysis.md # Index with overview + @references ├── analysis.md # Role overview index (< 1500 words)
├── analysis-architecture-assessment.md # Section content ├── analysis-cross-cutting.md # Cross-feature decisions (< 2000 words)
├── analysis-technology-evaluation.md # Section content ├── analysis-F-001-real-time-sync.md # Per-feature analysis (< 2000 words)
├── analysis-integration-strategy.md # Section content ├── analysis-F-002-user-auth.md # Per-feature analysis (< 2000 words)
└── analysis-recommendations.md # Section content (max 5 sub-docs total) └── analysis-F-003-data-pipeline.md # Per-feature analysis (< 2000 words)
NOTE: ALL files MUST start with 'analysis' prefix. Max 5 sub-documents. NOTE: ALL files MUST start with 'analysis' prefix.
Feature-point mode: 1 index + 1 cross-cutting + N feature docs (N = feature count, max 8).
Fallback mode: 1 index + max 5 arbitrary sub-docs.
``` ```
## Role-Specific Planning Process ## Role-Specific Planning Process
@@ -256,6 +268,16 @@ NOTE: ALL files MUST start with 'analysis' prefix. Max 5 sub-documents.
- **Validate Against Template**: Ensure analysis meets role template requirements and standards - **Validate Against Template**: Ensure analysis meets role template requirements and standards
### 3. Brainstorming Documentation Phase ### 3. Brainstorming Documentation Phase
**Feature-point mode** (when `feature_list` is available from guidance-specification.md):
- **Read Feature List**: Extract Feature Decomposition table from guidance-specification.md
- **Create analysis.md**: Role overview index (< 1500 words) with feature point listing and `@` references to sub-documents
- **Create analysis-cross-cutting.md**: Cross-feature decisions, shared patterns, role-wide recommendations (< 2000 words)
- **Create analysis-F-{id}-{slug}.md**: One per feature point, using ID and slug from feature list (< 2000 words each)
- **Validate Output Structure**: Ensure all files saved to correct `.brainstorming/[role]/` directory
- **Naming Validation**: Verify ALL files start with `analysis` prefix, feature docs match `analysis-F-{id}-{slug}.md` pattern
**Fallback mode** (when `feature_list` is NOT available):
- **Create analysis.md**: Main document with overview (optionally with `@` references) - **Create analysis.md**: Main document with overview (optionally with `@` references)
- **Create sub-documents**: `analysis-{slug}.md` for major sections (max 5) - **Create sub-documents**: `analysis-{slug}.md` for major sections (max 5)
- **Validate Output Structure**: Ensure all files saved to correct `.brainstorming/[role]/` directory - **Validate Output Structure**: Ensure all files saved to correct `.brainstorming/[role]/` directory
@@ -311,6 +333,14 @@ When analysis is complete, ensure:
## Output Size Limits ## Output Size Limits
**Per-role limits** (prevent context overflow): **Per-role limits** (prevent context overflow):
**Feature-point mode** (when `feature_list` available):
- `analysis.md` (index): < 1500 words
- `analysis-cross-cutting.md`: < 2000 words
- `analysis-F-{id}-{slug}.md`: < 2000 words each (one per feature, max 8 features)
- Total: < 15000 words per role
**Fallback mode** (when `feature_list` NOT available):
- `analysis.md`: < 3000 words - `analysis.md`: < 3000 words
- `analysis-*.md`: < 2000 words each (max 5 sub-documents) - `analysis-*.md`: < 2000 words each (max 5 sub-documents)
- Total: < 15000 words per role - Total: < 15000 words per role

View File

@@ -339,7 +339,25 @@ if (dir_exists(brainstormDir)) {
path: `${brainstormDir}/synthesis-specification.md`, path: `${brainstormDir}/synthesis-specification.md`,
exists: file_exists(`${brainstormDir}/synthesis-specification.md`), exists: file_exists(`${brainstormDir}/synthesis-specification.md`),
content: Read(`${brainstormDir}/synthesis-specification.md`) || null content: Read(`${brainstormDir}/synthesis-specification.md`) || null
} },
// Feature index (optional - top level, matches action-planning-agent expected access pattern)
feature_index: file_exists(`${brainstormDir}/feature-specs/feature-index.json`) ? {
path: `${brainstormDir}/feature-specs/feature-index.json`,
exists: true,
content: Read(`${brainstormDir}/feature-specs/feature-index.json`) || null
} : undefined,
// Feature spec files (optional - individual feature specifications)
feature_specs: dir_exists(`${brainstormDir}/feature-specs`)
? glob(`${brainstormDir}/feature-specs/F-*-*.md`).map(file => ({
path: file,
content: Read(file)
}))
: undefined,
// Cross-cutting specs (optional - cross-cutting concern analyses from roles)
cross_cutting_specs: glob(`${brainstormDir}/*/analysis-cross-cutting.md`).map(file => ({
path: file,
content: Read(file)
}))
}; };
} }
``` ```
@@ -462,7 +480,24 @@ Calculate risk level based on:
"path": ".workflow/WFS-xxx/.brainstorming/synthesis-specification.md", "path": ".workflow/WFS-xxx/.brainstorming/synthesis-specification.md",
"exists": true, "exists": true,
"content": "# Synthesis Specification\n\n## Cross-Role Integration\n..." "content": "# Synthesis Specification\n\n## Cross-Role Integration\n..."
} },
"feature_index": {
"path": ".workflow/WFS-xxx/.brainstorming/feature-specs/feature-index.json",
"exists": true,
"content": "{\"version\":\"1.0\",\"features\":[...]}"
},
"feature_specs": [
{
"path": ".workflow/WFS-xxx/.brainstorming/feature-specs/F-001-auth.md",
"content": "# Feature Spec: F-001 - Auth\n..."
}
],
"cross_cutting_specs": [
{
"path": ".workflow/WFS-xxx/.brainstorming/system-architect/analysis-cross-cutting.md",
"content": "# Cross-Cutting: Architecture Decisions\n..."
}
]
}, },
"conflict_detection": { "conflict_detection": {
"risk_level": "medium", "risk_level": "medium",

View File

@@ -36,7 +36,7 @@ All user interactions use AskUserQuestion tool (max 4 questions per call, multi-
| 2 | Role selection | 1 multi-select | selected_roles | | 2 | Role selection | 1 multi-select | selected_roles |
| 3 | Role questions | 3-4 per role | role_decisions[role] | | 3 | Role questions | 3-4 per role | role_decisions[role] |
| 4 | Conflict resolution | max 4 per round | cross_role_decisions | | 4 | Conflict resolution | max 4 per round | cross_role_decisions |
| 4.5 | Final check | progressive rounds | additional_decisions | | 4.5 | Final check + Feature decomposition | progressive rounds | additional_decisions, feature_list |
| 5 | Generate spec | - | guidance-specification.md | | 5 | Generate spec | - | guidance-specification.md |
### AskUserQuestion Pattern ### AskUserQuestion Pattern
@@ -102,7 +102,7 @@ for (let i = 0; i < allQuestions.length; i += BATCH_SIZE) {
{"content": "Phase 2: Role selection", "status": "pending", "activeForm": "Phase 2"}, {"content": "Phase 2: Role selection", "status": "pending", "activeForm": "Phase 2"},
{"content": "Phase 3: Role questions (per role)", "status": "pending", "activeForm": "Phase 3"}, {"content": "Phase 3: Role questions (per role)", "status": "pending", "activeForm": "Phase 3"},
{"content": "Phase 4: Conflict resolution", "status": "pending", "activeForm": "Phase 4"}, {"content": "Phase 4: Conflict resolution", "status": "pending", "activeForm": "Phase 4"},
{"content": "Phase 4.5: Final clarification", "status": "pending", "activeForm": "Phase 4.5"}, {"content": "Phase 4.5: Final clarification + Feature decomposition", "status": "pending", "activeForm": "Phase 4.5"},
{"content": "Phase 5: Generate specification", "status": "pending", "activeForm": "Phase 5"} {"content": "Phase 5: Generate specification", "status": "pending", "activeForm": "Phase 5"}
] ]
``` ```
@@ -313,10 +313,66 @@ AskUserQuestion({
**Progressive Pattern**: Questions interconnected, each round informs next, continue until resolved. **Progressive Pattern**: Questions interconnected, each round informs next, continue until resolved.
#### Feature Decomposition
After final clarification, extract implementable feature units from all Phase 1-4 decisions.
**Steps**:
1. Analyze all accumulated decisions (`intent_context` + `role_decisions` + `cross_role_decisions` + `additional_decisions`)
2. Extract candidate features: each must be an independently implementable unit with clear boundaries
3. Generate candidate list (max 8 features) with structured format:
- Feature ID: `F-{3-digit}` (e.g., F-001)
- Name: kebab-case slug (e.g., `real-time-sync`, `user-auth`)
- Description: one-sentence summary of the feature's scope
- Related roles: which roles' decisions drive this feature
- Priority: High / Medium / Low
4. Present candidate list to user for confirmation:
```javascript
AskUserQuestion({
questions: [{
question: "以下是从讨论中提取的功能点清单:\n\nF-001: [name] - [description]\nF-002: [name] - [description]\n...\n\n是否需要调整",
header: "功能点确认",
multiSelect: false,
options: [
{ label: "确认无误", description: "功能点清单完整且合理,继续生成规范" },
{ label: "需要调整", description: "需要增加、删除或修改功能点" }
]
}]
})
```
5. If "需要调整": Collect adjustments and re-present until user confirms
6. Store confirmed list to `session.feature_list`
**Constraints**:
- Maximum 8 features (if more candidates, merge related items)
- Each feature MUST be independently implementable (no implicit cross-feature dependencies)
- Feature ID format: `F-{3-digit}` (F-001, F-002, ...)
- Feature slug: kebab-case, descriptive of the feature scope
**Granularity Guidelines** (用于验证功能点粒度是否合适):
| Signal | Too Coarse | Just Right | Too Fine |
|--------|-----------|------------|----------|
| 实现范围 | 需要 5+ 个独立模块协同 | 1-3 个模块,边界清晰 | 单个函数或单个 API 端点 |
| 角色关注 | 所有角色都深度涉及 | 2-4 个角色有实质贡献 | 仅 1 个角色关注 |
| 可测试性 | 无法写出清晰的验收标准 | 可定义 3-5 条可测量验收标准 | 验收标准等同于单元测试 |
| 依赖关系 | 与其他功能点循环依赖 | 依赖关系单向且可识别 | 无任何外部依赖(可能遗漏) |
**Quality Validation** (Step 3 提取候选功能点后,逐条验证):
1. **独立性检查**: 该功能点是否可以在其他功能点未完成时独立交付?若否 → 考虑合并或重新划分
2. **完整性检查**: 该功能点是否覆盖了一个用户可感知的完整价值?若否 → 可能太细,考虑合并
3. **粒度均衡检查**: 各功能点之间的复杂度是否大致均衡(最大不超过最小的 3 倍)?若否 → 拆分过大的或合并过小的
4. **边界清晰检查**: 是否能用一句话描述该功能点的输入和输出?若否 → 边界模糊,需重新定义
**Handling Vague Requirements** (当用户需求模糊时的额外步骤):
- 如果 Phase 1-4 的决策不足以支撑功能点分解(如缺少具体业务场景、技术选型未定),在 Step 4 确认时**主动告知用户**哪些功能点的粒度可能不够精确
- 对不确定的功能点标注 `Priority: TBD`,在后续 synthesis 阶段通过跨角色分析进一步明确
- 如果候选功能点 ≤ 2 个,可能是需求过于抽象 → 提示用户补充更多具体场景后再分解
### Phase 5: Generate Specification ### Phase 5: Generate Specification
**Steps**: **Steps**:
1. Load all decisions: `intent_context` + `selected_roles` + `role_decisions` + `cross_role_decisions` + `additional_decisions` 1. Load all decisions: `intent_context` + `selected_roles` + `role_decisions` + `cross_role_decisions` + `additional_decisions` + `feature_list`
2. Transform Q&A to declarative: Questions → Headers, Answers → CONFIRMED/SELECTED statements 2. Transform Q&A to declarative: Questions → Headers, Answers → CONFIRMED/SELECTED statements
3. Generate `guidance-specification.md` 3. Generate `guidance-specification.md`
4. Update `workflow-session.json` (metadata only) 4. Update `workflow-session.json` (metadata only)
@@ -394,6 +450,15 @@ AskUserQuestion({
- Each selected role gets conceptual-planning-agent - Each selected role gets conceptual-planning-agent
- Agents read this guidance-specification.md for context - Agents read this guidance-specification.md for context
## Feature Decomposition
**Constraints**: Max 8 features | Each independently implementable | ID format: F-{3-digit}
| Feature ID | Name | Description | Related Roles | Priority |
|------------|------|-------------|---------------|----------|
| F-001 | [kebab-case-slug] | [One-sentence scope description] | [role1, role2] | High/Medium/Low |
| F-002 | [kebab-case-slug] | [One-sentence scope description] | [role1] | High/Medium/Low |
## Appendix: Decision Tracking ## Appendix: Decision Tracking
| Decision ID | Category | Question | Selected | Phase | Rationale | | Decision ID | Category | Question | Selected | Phase | Rationale |
|-------------|----------|----------|----------|-------|-----------| |-------------|----------|----------|----------|-------|-----------|

View File

@@ -85,15 +85,23 @@ ELSE:
VALIDATE brainstorm_dir EXISTS VALIDATE brainstorm_dir EXISTS
``` ```
**Step 1.3: Framework Detection** **Step 1.3: Framework Detection & Feature List Extraction**
```bash ```bash
framework_file = {brainstorm_dir}/guidance-specification.md framework_file = {brainstorm_dir}/guidance-specification.md
IF framework_file EXISTS: IF framework_file EXISTS:
framework_mode = true framework_mode = true
LOAD framework_content LOAD framework_content
# Extract Feature Decomposition table from guidance-specification.md
feature_list = EXTRACT_TABLE(framework_content, "Feature Decomposition")
# feature_list format: [{id: "F-001", slug: "real-time-sync", description: "...", roles: [...], priority: "High"}, ...]
IF feature_list NOT EMPTY:
feature_mode = true # Use feature-point organization for sub-documents
ELSE:
feature_mode = false # Fall back to arbitrary-topic organization
ELSE: ELSE:
WARN: "No framework found - will create standalone analysis" WARN: "No framework found - will create standalone analysis"
framework_mode = false framework_mode = false
feature_mode = false
``` ```
**Step 1.4: Update Mode Detection** **Step 1.4: Update Mode Detection**
@@ -296,6 +304,8 @@ const agentContext = {
role_config: roleConfig[role_name], role_config: roleConfig[role_name],
output_location: `${brainstorm_dir}/${role_name}/`, output_location: `${brainstorm_dir}/${role_name}/`,
framework_mode: framework_mode, framework_mode: framework_mode,
feature_mode: feature_mode,
feature_list: feature_mode ? feature_list : null, // From guidance-spec Feature Decomposition
framework_path: framework_mode ? `${brainstorm_dir}/guidance-specification.md` : null, framework_path: framework_mode ? `${brainstorm_dir}/guidance-specification.md` : null,
update_mode: update_mode, update_mode: update_mode,
user_context: user_context, user_context: user_context,
@@ -308,6 +318,24 @@ const agentContext = {
**Framework-Based Analysis** (when guidance-specification.md exists): **Framework-Based Analysis** (when guidance-specification.md exists):
```javascript ```javascript
// Build feature list injection block (only when feature_mode is true)
const featureListBlock = feature_mode ? `
## Feature Point List (from guidance-specification.md Feature Decomposition)
${feature_list.map(f => `- **${f.id}** (${f.slug}): ${f.description} [Priority: ${f.priority}]`).join('\n')}
**IMPORTANT - Feature-Point Output Organization**:
- Generate ONE sub-document per feature: analysis-F-{id}-{slug}.md (e.g., analysis-${feature_list[0].id}-${feature_list[0].slug}.md)
- Generate ONE cross-cutting document: analysis-cross-cutting.md
- analysis.md is a role overview INDEX only (< 1500 words), NOT a full analysis
- Each feature sub-document < 2000 words, cross-cutting < 2000 words
- Total across all files < 15000 words
` : `
## Output Organization (fallback: no feature list available)
- Generate analysis.md as main document (< 3000 words)
- Optionally split into analysis-{slug}.md sub-documents (max 5, < 2000 words each)
- Total < 15000 words
`;
Task( Task(
subagent_type="conceptual-planning-agent", subagent_type="conceptual-planning-agent",
run_in_background=false, run_in_background=false,
@@ -321,6 +349,7 @@ Execute ${role_name} analysis for existing topic framework
ASSIGNED_ROLE: ${role_name} ASSIGNED_ROLE: ${role_name}
OUTPUT_LOCATION: ${agentContext.output_location} OUTPUT_LOCATION: ${agentContext.output_location}
ANALYSIS_MODE: ${framework_mode ? "framework_based" : "standalone"} ANALYSIS_MODE: ${framework_mode ? "framework_based" : "standalone"}
FEATURE_MODE: ${feature_mode}
UPDATE_MODE: ${update_mode} UPDATE_MODE: ${update_mode}
## Flow Control Steps ## Flow Control Steps
@@ -351,18 +380,30 @@ UPDATE_MODE: ${update_mode}
- Output: existing_analysis_content - Output: existing_analysis_content
` : ''} ` : ''}
${featureListBlock}
## Analysis Requirements ## Analysis Requirements
**Primary Reference**: Original user prompt from workflow-session.json is authoritative **Primary Reference**: Original user prompt from workflow-session.json is authoritative
**Framework Source**: Address all discussion points in guidance-specification.md from ${role_name} perspective **Framework Source**: Address all discussion points in guidance-specification.md from ${role_name} perspective
**User Context Integration**: Incorporate interactive Q&A responses into analysis **User Context Integration**: Incorporate interactive Q&A responses into analysis
**Role Focus**: ${roleConfig[role_name].focus_area} **Role Focus**: ${roleConfig[role_name].focus_area}
**Template Integration**: Apply role template guidelines within framework structure **Template Integration**: Apply role template guidelines within framework structure
${feature_mode ? `**Feature Organization**: Organize analysis by feature points - each feature gets its own sub-document. Cross-cutting concerns (architecture decisions, tech choices, shared patterns spanning multiple features) go into analysis-cross-cutting.md.` : ''}
## Expected Deliverables ## Expected Deliverables
${feature_mode ? `
1. **analysis.md** - Role overview index (< 1500 words): role perspective summary, feature point index with @-references to sub-documents, cross-cutting summary
2. **analysis-cross-cutting.md** - Cross-feature decisions (< 2000 words): architecture decisions, technology choices, shared patterns that span multiple features
3. **analysis-F-{id}-{slug}.md** - One per feature (< 2000 words each): role-specific analysis, recommendations, considerations for that feature
4. **Framework Reference**: @../guidance-specification.md (if framework_mode)
5. **User Context Reference**: @./${role_name}-context.md (if user context exists)
6. **User Intent Alignment**: Validate against session_context
` : `
1. **analysis.md** (main document, optionally with analysis-{slug}.md sub-documents) 1. **analysis.md** (main document, optionally with analysis-{slug}.md sub-documents)
2. **Framework Reference**: @../guidance-specification.md (if framework_mode) 2. **Framework Reference**: @../guidance-specification.md (if framework_mode)
3. **User Context Reference**: @./${role_name}-context.md (if user context exists) 3. **User Context Reference**: @./${role_name}-context.md (if user context exists)
4. **User Intent Alignment**: Validate against session_context 4. **User Intent Alignment**: Validate against session_context
`}
## Update Requirements (if UPDATE_MODE) ## Update Requirements (if UPDATE_MODE)
- **Preserve Structure**: Maintain existing analysis structure - **Preserve Structure**: Maintain existing analysis structure
@@ -374,6 +415,9 @@ UPDATE_MODE: ${update_mode}
- Address each discussion point from guidance-specification.md with ${role_name} expertise - Address each discussion point from guidance-specification.md with ${role_name} expertise
- Provide actionable recommendations from ${role_name} perspective within analysis files - Provide actionable recommendations from ${role_name} perspective within analysis files
- All output files MUST start with "analysis" prefix (no recommendations.md or other naming) - All output files MUST start with "analysis" prefix (no recommendations.md or other naming)
${feature_mode ? `- Each feature from the feature list has a corresponding analysis-F-{id}-{slug}.md file
- analysis-cross-cutting.md exists with cross-feature decisions
- analysis.md serves as index (< 1500 words), NOT a full analysis document` : ''}
- Reference framework document using @ notation for integration - Reference framework document using @ notation for integration
- Update workflow-session.json with completion status - Update workflow-session.json with completion status
` `
@@ -479,6 +523,20 @@ TodoWrite({
### Directory Layout ### Directory Layout
**Feature-point mode** (when `feature_list` available):
```
.workflow/active/WFS-{session}/.brainstorming/
├── guidance-specification.md # Framework with Feature Decomposition
└── {role-name}/
├── {role-name}-context.md # Interactive Q&A responses
├── analysis.md # Role overview INDEX (< 1500 words)
├── analysis-cross-cutting.md # Cross-feature decisions (< 2000 words)
├── analysis-F-001-{slug}.md # Per-feature analysis (< 2000 words)
├── analysis-F-002-{slug}.md # Per-feature analysis (< 2000 words)
└── analysis-F-00N-{slug}.md # One per feature (max 8)
```
**Fallback mode** (when `feature_list` NOT available):
``` ```
.workflow/active/WFS-{session}/.brainstorming/ .workflow/active/WFS-{session}/.brainstorming/
├── guidance-specification.md # Framework (if exists) ├── guidance-specification.md # Framework (if exists)
@@ -488,7 +546,69 @@ TodoWrite({
└── analysis-{slug}.md # Section documents (optional, max 5) └── analysis-{slug}.md # Section documents (optional, max 5)
``` ```
### Analysis Document Structure (New Generation) ### Analysis Document Structure - Feature-Point Mode (New Generation)
**analysis.md** (Role Overview Index, < 1500 words):
```markdown
# ${roleConfig[role_name].title} Analysis: [Topic from Framework]
## Framework Reference
**Topic Framework**: @../guidance-specification.md
**Role Focus**: ${roleConfig[role_name].focus_area}
**User Context**: @./${role_name}-context.md
## Role Perspective Overview
[Brief summary of this role's perspective on the overall project]
## Feature Point Index
| Feature | Sub-document | Key Insight |
|---------|-------------|-------------|
| F-001: [name] | @./analysis-F-001-{slug}.md | [One-line summary] |
| F-002: [name] | @./analysis-F-002-{slug}.md | [One-line summary] |
## Cross-Cutting Summary
**Full analysis**: @./analysis-cross-cutting.md
[Brief overview of cross-feature decisions and shared patterns]
---
*Generated by ${role_name} analysis addressing structured framework*
```
**analysis-cross-cutting.md** (< 2000 words):
```markdown
# Cross-Cutting Analysis: ${roleConfig[role_name].title}
## Architecture Decisions
[Decisions that span multiple features]
## Technology Choices
[Shared technology selections and rationale]
## Shared Patterns
[Common patterns, constraints, and conventions across features]
## ${roleConfig[role_name].title} Recommendations
[Role-wide strategic recommendations]
```
**analysis-F-{id}-{slug}.md** (< 2000 words each):
```markdown
# Feature ${id}: [Feature Name] - ${roleConfig[role_name].title} Analysis
## Feature Overview
[Role-specific perspective on this feature's scope and goals]
## Analysis
[Detailed role-specific analysis for this feature]
## Recommendations
[Actionable recommendations for this feature from role perspective]
## Dependencies & Risks
[Cross-feature dependencies and risks from role viewpoint]
```
### Analysis Document Structure - Fallback Mode (New Generation)
```markdown ```markdown
# ${roleConfig[role_name].title} Analysis: [Topic from Framework] # ${roleConfig[role_name].title} Analysis: [Topic from Framework]
@@ -581,6 +701,10 @@ ${Object.entries(user_context).map(([q, a]) => `
- [ ] Output files follow naming convention (analysis*.md only) - [ ] Output files follow naming convention (analysis*.md only)
- [ ] Framework reference using @ notation - [ ] Framework reference using @ notation
- [ ] Session metadata updated - [ ] Session metadata updated
- [ ] Feature-point organization used when feature_list available (if feature_mode)
- [ ] analysis.md is index only (< 1500 words) when in feature_mode
- [ ] analysis-cross-cutting.md exists when in feature_mode
- [ ] One analysis-F-{id}-{slug}.md per feature when in feature_mode
### Context Quality ### Context Quality
- [ ] Questions in Chinese with business context - [ ] Questions in Chinese with business context

View File

@@ -11,19 +11,22 @@ When `--yes` or `-y`: Auto-select all enhancements, skip clarification questions
## Overview ## Overview
Six-phase workflow to eliminate ambiguities and enhance conceptual depth in role analyses: Eight-phase workflow to eliminate ambiguities, enhance conceptual depth, and generate per-feature specifications:
**Phase 1-2**: Session detection → File discovery → Path preparation **Phase 1-2**: Session detection → File discovery → Path preparation
**Phase 3A**: Cross-role analysis agent → Generate recommendations **Phase 3A**: Cross-role analysis agent → Generate recommendations + feature_conflict_map
**Phase 4**: User selects enhancements → User answers clarifications (via AskUserQuestion) **Phase 4**: User selects enhancements → User answers clarifications (via AskUserQuestion)
**Phase 5**: Parallel update agents (one per role) **Phase 5**: Parallel update agents (one per role)
**Phase 6**: Context package update → Metadata update → Completion report **Phase 6**: Parallel feature spec generation (one agent per feature) [feature_mode only]
**Phase 6.5**: Feature index generation (feature-index.json) [feature_mode only]
**Phase 7**: Context package update → Metadata update → Completion report
All user interactions use AskUserQuestion tool (max 4 questions per call, multi-round). All user interactions use AskUserQuestion tool (max 4 questions per call, multi-round).
**Document Flow**: **Document Flow**:
- Input: `[role]/analysis*.md`, `guidance-specification.md`, session metadata - Input: `[role]/analysis.md` (index files), `guidance-specification.md`, session metadata
- Output: Updated `[role]/analysis*.md` with Enhancements + Clarifications sections - Output: Updated `[role]/analysis*.md` with Enhancements + Clarifications sections
- Output (feature_mode): `feature-specs/F-{id}-{slug}.md` per feature + `feature-index.json`
--- ---
@@ -35,10 +38,12 @@ All user interactions use AskUserQuestion tool (max 4 questions per call, multi-
|-------|------|----------|--------| |-------|------|----------|--------|
| 1 | Session detection | Main flow | session_id, brainstorm_dir | | 1 | Session detection | Main flow | session_id, brainstorm_dir |
| 2 | File discovery | Main flow | role_analysis_paths | | 2 | File discovery | Main flow | role_analysis_paths |
| 3A | Cross-role analysis | Agent | enhancement_recommendations | | 3A | Cross-role analysis | Agent | enhancement_recommendations, feature_conflict_map |
| 4 | User interaction | Main flow + AskUserQuestion | update_plan | | 4 | User interaction | Main flow + AskUserQuestion | update_plan |
| 5 | Document updates | Parallel agents | Updated analysis*.md | | 5 | Document updates | Parallel agents | Updated analysis*.md |
| 6 | Finalization | Main flow | context-package.json, report | | 6 | Feature spec generation | Parallel agents | feature-specs/F-{id}-{slug}.md [feature_mode] |
| 6.5 | Feature index generation | Main flow | feature-index.json [feature_mode] |
| 7 | Finalization | Main flow | context-package.json, report |
### AskUserQuestion Pattern ### AskUserQuestion Pattern
@@ -81,10 +86,12 @@ AskUserQuestion({
[ [
{"content": "Detect session and validate analyses", "status": "pending", "activeForm": "Detecting session"}, {"content": "Detect session and validate analyses", "status": "pending", "activeForm": "Detecting session"},
{"content": "Discover role analysis file paths", "status": "pending", "activeForm": "Discovering paths"}, {"content": "Discover role analysis file paths", "status": "pending", "activeForm": "Discovering paths"},
{"content": "Execute analysis agent (cross-role analysis)", "status": "pending", "activeForm": "Executing analysis"}, {"content": "Execute analysis agent (cross-role analysis + feature conflict map)", "status": "pending", "activeForm": "Executing analysis"},
{"content": "Present enhancements via AskUserQuestion", "status": "pending", "activeForm": "Selecting enhancements"}, {"content": "Present enhancements via AskUserQuestion", "status": "pending", "activeForm": "Selecting enhancements"},
{"content": "Clarification questions via AskUserQuestion", "status": "pending", "activeForm": "Clarifying"}, {"content": "Clarification questions via AskUserQuestion", "status": "pending", "activeForm": "Clarifying"},
{"content": "Execute parallel update agents", "status": "pending", "activeForm": "Updating documents"}, {"content": "Execute parallel update agents", "status": "pending", "activeForm": "Updating documents"},
{"content": "Generate parallel feature specs (feature_mode only)", "status": "pending", "activeForm": "Generating feature specs"},
{"content": "Generate feature-index.json (feature_mode only)", "status": "pending", "activeForm": "Building feature index"},
{"content": "Update context package and metadata", "status": "pending", "activeForm": "Finalizing"} {"content": "Update context package and metadata", "status": "pending", "activeForm": "Finalizing"}
] ]
``` ```
@@ -100,6 +107,22 @@ AskUserQuestion({
- `guidance-specification.md` (optional, warn if missing) - `guidance-specification.md` (optional, warn if missing)
- `*/analysis*.md` (required, error if empty) - `*/analysis*.md` (required, error if empty)
3. **Load User Intent**: Extract from `workflow-session.json` 3. **Load User Intent**: Extract from `workflow-session.json`
4. **Detect Feature Mode**: Check if role analyses use feature-point organization
```javascript
// Feature mode is active when:
// 1. guidance-specification.md contains Feature Decomposition table
// 2. Role directories contain analysis-F-{id}-*.md files
const has_feature_decomposition = guidanceSpecContent &&
guidanceSpecContent.includes('Feature Decomposition');
const has_feature_subdocs = Glob(`${brainstorm_dir}/*/analysis-F-*-*.md`).length > 0;
const feature_mode = has_feature_decomposition && has_feature_subdocs;
// Extract feature_list from guidance-spec if feature_mode
if (feature_mode) {
feature_list = extractFeatureDecompositionTable(guidanceSpecContent);
// feature_list: [{id, slug, description, roles, priority}, ...]
}
```
### Phase 2: Role Discovery & Path Preparation ### Phase 2: Role Discovery & Path Preparation
@@ -119,23 +142,41 @@ AskUserQuestion({
**Agent executes cross-role analysis**: **Agent executes cross-role analysis**:
**Input Optimization (feature_mode)**: When feature_mode is active, only read `{role}/analysis.md` index files (NOT sub-documents like `analysis-F-{id}-*.md` or `analysis-cross-cutting.md`). This reduces input tokens from ~39K to ~4.5K while preserving the role perspective overview, feature point index, and cross-cutting summary needed for conflict detection.
**Input (fallback mode)**: When feature_mode is NOT active, read all `{role}/analysis*.md` files as before.
```javascript ```javascript
// Prepare input paths based on mode
const analysis_input_paths = feature_mode
? participating_roles.map(r => `${brainstorm_dir}/${r}/analysis.md`) // Index files only (~4.5K total)
: role_analysis_paths; // All analysis files (fallback)
Task(conceptual-planning-agent, ` Task(conceptual-planning-agent, `
## Agent Mission ## Agent Mission
Analyze role documents, identify conflicts/gaps, generate enhancement recommendations Analyze role documents, identify conflicts/gaps, generate enhancement recommendations.
${feature_mode ? 'Additionally, generate feature_conflict_map for per-feature consensus/conflicts across roles.' : ''}
## Input ## Input
- brainstorm_dir: ${brainstorm_dir} - brainstorm_dir: ${brainstorm_dir}
- role_analysis_paths: ${role_analysis_paths} - analysis_input_paths: ${analysis_input_paths}
- participating_roles: ${participating_roles} - participating_roles: ${participating_roles}
- feature_mode: ${feature_mode}
${feature_mode ? `- guidance_spec_path: ${brainstorm_dir}/guidance-specification.md (read Feature Decomposition section only)` : ''}
## Flow Control Steps ## Flow Control Steps
1. load_session_metadata → Read workflow-session.json 1. load_session_metadata → Read workflow-session.json
2. load_role_analyses → Read all analysis files 2. load_role_analyses → Read analysis files from analysis_input_paths
3. cross_role_analysis → Identify consensus, conflicts, gaps, ambiguities ${feature_mode ? '(INDEX files only - each ~500-800 words with role overview, feature index table, cross-cutting summary)' : '(All analysis files)'}
4. generate_recommendationsFormat as EP-001, EP-002, ... ${feature_mode ? `3. load_feature_decomposition → Read Feature Decomposition table from guidance-specification.md
4. cross_role_analysis → Identify consensus, conflicts, gaps, ambiguities
5. generate_feature_conflict_map → For each feature in Feature Decomposition, extract per-feature consensus/conflicts/cross-references from role index summaries
6. generate_recommendations → Format as EP-001, EP-002, ...` : `3. cross_role_analysis → Identify consensus, conflicts, gaps, ambiguities
4. generate_recommendations → Format as EP-001, EP-002, ...`}
## Output Format ## Output Format
### enhancement_recommendations (always)
[ [
{ {
"id": "EP-001", "id": "EP-001",
@@ -148,9 +189,79 @@ Analyze role documents, identify conflicts/gaps, generate enhancement recommenda
"priority": "High" "priority": "High"
} }
] ]
${feature_mode ? `### feature_conflict_map (feature_mode only)
Bridge artifact from Phase 3A to Phase 6. One entry per feature from Feature Decomposition.
{
"F-001": {
"consensus": [
"All roles agree on real-time sync via WebSocket",
"Event-driven architecture preferred"
],
"conflicts": [
{
"topic": "State management approach",
"views": {
"system-architect": "Server-authoritative with CRDT",
"ux-expert": "Optimistic local-first updates",
"data-architect": "Event-sourced append-only log"
},
"resolution": "Hybrid: optimistic local with server reconciliation via CRDT"
}
],
"cross_refs": [
"F-003 (offline-mode) depends on sync conflict resolution strategy",
"analysis-cross-cutting.md#shared-patterns references this feature"
]
},
"F-002": { ... }
}
**feature_conflict_map Rules**:
- One entry per feature ID from guidance-specification.md Feature Decomposition
- consensus[]: Statements where 2+ roles explicitly agree (extracted from index summaries)
- conflicts[]: Disagreements with topic, per-role positions, and suggested resolution
- cross_refs[]: References to other features or cross-cutting docs that relate to this feature
- If a feature has no conflicts, set conflicts to empty array (consensus-only is valid)
- Keep each entry concise: aim for 100-200 words per feature
**Resolution Quality Requirements** (每条 conflict 的 resolution 必须满足):
1. **Actionable**: resolution 必须是可直接执行的技术方案而非模糊描述。Bad: "需要权衡" → Good: "采用 JWT 无状态认证RefreshToken 存 HttpOnly Cookie"
2. **Justified**: 说明为什么选择该方案而非其他。格式: "[方案] because [原因]tradeoff: [代价]"
3. **Scoped**: 明确 resolution 的适用范围。如果仅适用于特定场景,标注 "Applies when: [条件]"
4. **Resolution Confidence**: 每条 conflict 标注置信度
- `[RESOLVED]`: Phase 3A 从角色分析中找到明确共识或用户已决策 → Phase 6 直接采用
- `[SUGGESTED]`: Phase 3A 基于角色分析推荐方案,但未被用户显式确认 → Phase 6 采用但标注来源
- `[UNRESOLVED]`: 角色之间存在根本分歧且无法从现有信息推导 → Phase 6 标注 [DECISION NEEDED],列出所有选项供 plan 阶段决策
**conflict entry 增强 schema**:
```json
{
"topic": "State management approach",
"views": {
"system-architect": "Server-authoritative with CRDT",
"ux-expert": "Optimistic local-first updates"
},
"resolution": "Hybrid: optimistic local with server reconciliation via CRDT because balances UX responsiveness with data consistency, tradeoff: increased client complexity",
"confidence": "[RESOLVED]",
"applies_when": "Online mode with collaborative editing"
}
```
` : ''}
`) `)
``` ```
**Phase 3A Output Storage**:
```javascript
// Store enhancement_recommendations for Phase 4
const enhancement_recommendations = agent_output.enhancement_recommendations;
// Store feature_conflict_map for Phase 6 (feature_mode only)
const feature_conflict_map = feature_mode ? agent_output.feature_conflict_map : null;
```
```
### Phase 4: User Interaction ### Phase 4: User Interaction
**All interactions via AskUserQuestion (Chinese questions)** **All interactions via AskUserQuestion (Chinese questions)**
@@ -300,7 +411,288 @@ Updated ${role}/analysis.md
- **Dependencies**: Zero cross-agent dependencies - **Dependencies**: Zero cross-agent dependencies
- **Validation**: All updates must align with original_user_intent - **Validation**: All updates must align with original_user_intent
### Phase 6: Finalization ### Phase 6: Parallel Feature Spec Generation [feature_mode only]
**Skip condition**: If `feature_mode` is false (no feature list in guidance-spec, or role analyses were not organized by feature points), skip Phase 6 and Phase 6.5 entirely. Proceed directly to Phase 7.
**Purpose**: Generate one consolidated feature specification per feature by aggregating all role perspectives. Each agent reads the detailed per-feature sub-documents from all roles, applies the conflict map from Phase 3A, and produces a unified spec.
#### Step 1: Prepare Feature Spec Directory
```javascript
// Create feature-specs directory
const feature_specs_dir = `${brainstorm_dir}/feature-specs`;
// Ensure directory exists (create if not)
```
#### Step 2: Build Per-Feature Input Bundles
```javascript
// For each feature in feature_list (from guidance-spec Feature Decomposition)
const feature_bundles = feature_list.map(feature => {
const fid = feature.id; // e.g., "F-001"
const slug = feature.slug; // e.g., "real-time-sync"
// Collect per-feature analysis files from all roles
const role_analysis_files = participating_roles
.map(role => `${brainstorm_dir}/${role}/analysis-${fid}-${slug}.md`)
.filter(path => fileExists(path)); // Only existing files
return {
feature_id: fid,
feature_slug: slug,
feature_name: feature.description,
feature_priority: feature.priority,
conflict_map_entry: feature_conflict_map[fid], // From Phase 3A
role_analysis_files: role_analysis_files,
contributing_roles: role_analysis_files.map(f => extractRoleName(f)),
output_path: `${feature_specs_dir}/${fid}-${slug}.md`
};
});
```
#### Step 3: Execute Parallel Feature Spec Agents
**Execute in parallel** (one agent per feature, mirrors Phase 5 pattern):
```javascript
// Single message with multiple Task calls for parallelism
// Each agent generates ONE feature spec document
// For each feature bundle:
Task(conceptual-planning-agent, `
## Agent Mission
Generate consolidated feature specification for ${feature.feature_id}: ${feature.feature_name}
by aggregating all role-specific analyses with conflict resolution.
## Input
- feature_id: ${feature.feature_id}
- feature_slug: ${feature.feature_slug}
- feature_name: ${feature.feature_name}
- feature_priority: ${feature.feature_priority}
- role_analysis_files: ${feature.role_analysis_files}
- conflict_map_entry: ${JSON.stringify(feature.conflict_map_entry)}
- output_path: ${feature.output_path}
- guidance_spec_feature_section: (Feature Decomposition row for this feature from guidance-specification.md)
## Flow Control Steps
1. load_role_analyses → Read all role-specific analysis files for this feature
(Each file ~1500-2000 words, total ~6.5K words for 3-4 roles)
2. apply_conflict_map → Use conflict_map_entry to identify resolved/unresolved conflicts
3. four_layer_aggregation → Apply aggregation rules (see below)
4. generate_feature_spec → Write consolidated spec using template (see below)
5. write_output → Save to output_path
## Four-Layer Aggregation Rules
### Layer 1: Direct Reference
- Quote role analyses directly when consensus exists (from conflict_map.consensus)
- Format: "[Role] recommends: [direct quote]"
- Use for undisputed technical recommendations
### Layer 2: Structured Extraction
- Extract and organize key information from each role into unified structure
- Merge complementary perspectives (e.g., UX user flows + architect data flows)
- De-duplicate overlapping content across roles
### Layer 3: Conflict Distillation
- For each conflict in conflict_map_entry.conflicts, handle by confidence level:
- **[RESOLVED]**: State the resolution directly as a design decision. Format: "**Decision**: [resolution]. **Rationale**: [from conflict.resolution]. **Trade-off**: [tradeoff]."
- **[SUGGESTED]**: Adopt the suggested resolution but mark source. Format: "**Recommended**: [resolution] (suggested by Phase 3A cross-role analysis). **Rationale**: [reason]. **Alternative**: [strongest competing view]."
- **[UNRESOLVED]**: Do NOT pick a side. Present all options neutrally for downstream decision. Format: "**[DECISION NEEDED]**: [topic]. **Options**: [role1: approach1] vs [role2: approach2]. **Evaluation**: [pros/cons of each]. **Impact if deferred**: [consequence of not deciding]."
- For each conflict regardless of confidence:
- Present all role positions concisely (who said what)
- Document trade-offs of the chosen or suggested approach
- If `applies_when` is set, note the scope limitation
- **Unresolved conflict escalation**: If a feature has 2+ [UNRESOLVED] conflicts, add a prominent warning at the top of Section 2: "⚠ This feature has N unresolved design decisions. Plan stage must resolve before task generation."
### Layer 4: Cross-Feature Annotation
- For each cross_ref in conflict_map_entry.cross_refs:
- Add explicit dependency notes with feature IDs
- Document integration points with other features
- Note shared constraints or patterns
## Feature Spec Template (7 Sections, target 1500-2500 words)
The output MUST follow this template:
---
# Feature Spec: ${feature.feature_id} - ${feature.feature_name}
**Priority**: ${feature.feature_priority}
**Contributing Roles**: [list of roles that analyzed this feature]
**Status**: Draft (from synthesis)
## 1. Requirements Summary
[Consolidated requirements from all role perspectives]
- Functional requirements (from product-manager, product-owner)
- User experience requirements (from ux-expert, ui-designer)
- Technical requirements (from system-architect, data-architect, api-designer)
- Domain requirements (from subject-matter-expert)
## 2. Design Decisions [CORE SECTION]
[Key architectural and design decisions with rationale]
For each decision:
- **Decision**: [What was decided]
- **Context**: [Why this decision was needed]
- **Options Considered**: [Alternatives from different roles]
- **Chosen Approach**: [Selected option with rationale]
- **Trade-offs**: [What we gain vs. what we sacrifice]
- **Source**: [Which role(s) drove this decision]
## 3. Interface Contract
[API endpoints, data models, component interfaces]
- External interfaces (API contracts from api-designer)
- Internal interfaces (component boundaries from system-architect)
- Data interfaces (schemas from data-architect)
- User interfaces (interaction patterns from ux-expert/ui-designer)
## 4. Constraints & Risks
[Technical constraints, business risks, mitigation strategies]
- Performance constraints (from system-architect)
- Data constraints (from data-architect)
- UX constraints (from ux-expert)
- Business/domain constraints (from subject-matter-expert)
- Risk mitigation strategies (from scrum-master)
## 5. Acceptance Criteria
[Testable criteria for feature completion]
- Functional acceptance (from product-owner user stories)
- Performance acceptance (from system-architect NFRs)
- UX acceptance (from ux-expert usability criteria)
- Data integrity acceptance (from data-architect)
## 6. Detailed Analysis References
[Pointers back to role-specific analysis documents]
- @../{role}/analysis-${feature.feature_id}-${feature.feature_slug}.md for each contributing role
- @../guidance-specification.md#feature-decomposition
## 7. Cross-Feature Dependencies
[Dependencies on and from other features]
- **Depends on**: [Feature IDs this feature requires]
- **Required by**: [Feature IDs that depend on this feature]
- **Shared patterns**: References to analysis-cross-cutting.md patterns
- **Integration points**: [Specific interfaces between features]
---
## Completion Criteria
- All 7 sections populated with aggregated content
- Section 2 (Design Decisions) is the most detailed section (40%+ of word count)
- All conflicts from conflict_map_entry addressed with resolutions
- Cross-feature dependencies explicitly documented
- Word count between 1500-2500
- No placeholder text (TODO/TBD) except [DECISION NEEDED] for genuinely unresolved items
`)
```
**Agent Characteristics (Phase 6)**:
- **Isolation**: Each agent processes exactly ONE feature (parallel safe)
- **Dependencies**: Requires Phase 3A feature_conflict_map and Phase 5 updated role analyses
- **Input budget**: ~6.5K words per agent (3-4 role sub-docs + conflict map entry)
- **Output budget**: 1500-2500 words per feature spec
### Phase 6.5: Feature Index Generation [feature_mode only]
**Skip condition**: Same as Phase 6 - skip if `feature_mode` is false.
**Purpose**: Collect all Phase 6 outputs and generate a structured `feature-index.json` for downstream consumption by action-planning-agent and code-developer.
#### Step 1: Collect Feature Spec Outputs
```javascript
// Read all generated feature spec files
const feature_spec_files = Glob(`${brainstorm_dir}/feature-specs/F-*-*.md`);
// Also collect cross-cutting spec paths
const cross_cutting_specs = participating_roles
.map(role => `${brainstorm_dir}/${role}/analysis-cross-cutting.md`)
.filter(path => fileExists(path));
```
#### Step 2: Generate feature-index.json
```javascript
const feature_index = {
"version": "1.0",
"generated_at": new Date().toISOString(),
"session_id": session_id,
"feature_mode": true,
"features": feature_list.map(feature => {
const fid = feature.id;
const slug = feature.slug;
const spec_path = `feature-specs/${fid}-${slug}.md`;
const spec_exists = fileExists(`${brainstorm_dir}/${spec_path}`);
// Extract contributing roles from the spec file header
const contributing_roles = participating_roles.filter(role =>
fileExists(`${brainstorm_dir}/${role}/analysis-${fid}-${slug}.md`)
);
// Extract cross-cutting references from conflict_map
const cross_cutting_refs = feature_conflict_map[fid]
? feature_conflict_map[fid].cross_refs
: [];
return {
"id": fid,
"slug": slug,
"name": feature.description,
"priority": feature.priority,
"spec_path": spec_exists ? spec_path : null,
"contributing_roles": contributing_roles,
"cross_cutting_refs": cross_cutting_refs
};
}),
"cross_cutting_specs": cross_cutting_specs.map(path =>
path.replace(brainstorm_dir + '/', '') // Relative path
)
};
Write(
`${brainstorm_dir}/feature-index.json`,
JSON.stringify(feature_index, null, 2)
);
```
#### feature-index.json Schema
```json
{
"version": "1.0",
"generated_at": "2026-02-11T10:00:00.000Z",
"session_id": "WFS-xxx",
"feature_mode": true,
"features": [
{
"id": "F-001",
"slug": "real-time-sync",
"name": "Real-time collaborative synchronization",
"priority": "High",
"spec_path": "feature-specs/F-001-real-time-sync.md",
"contributing_roles": ["system-architect", "ux-expert", "data-architect"],
"cross_cutting_refs": ["F-003 offline-mode depends on sync strategy"]
},
{
"id": "F-002",
"slug": "user-permissions",
"name": "Role-based user permissions and access control",
"priority": "High",
"spec_path": "feature-specs/F-002-user-permissions.md",
"contributing_roles": ["system-architect", "product-manager", "subject-matter-expert"],
"cross_cutting_refs": []
}
],
"cross_cutting_specs": [
"system-architect/analysis-cross-cutting.md",
"ux-expert/analysis-cross-cutting.md",
"data-architect/analysis-cross-cutting.md"
]
}
```
**Consumers**: `action-planning-agent` reads feature-index.json to generate task JSONs with feature_spec references. `code-developer` loads individual feature specs (3-5K words) as implementation context.
### Phase 7: Finalization
#### Step 1: Update Context Package #### Step 1: Update Context Package
@@ -313,6 +705,13 @@ const context_pkg = Read(".workflow/active/WFS-{session}/.process/context-packag
// Re-read all role analysis files // Re-read all role analysis files
// Update metadata timestamps // Update metadata timestamps
// If feature_mode: add feature-index.json and feature-specs paths
if (feature_mode) {
context_pkg.feature_index_path = `${brainstorm_dir}/feature-index.json`;
context_pkg.feature_specs_dir = `${brainstorm_dir}/feature-specs/`;
context_pkg.feature_mode = true;
}
Write(context_pkg_path, JSON.stringify(context_pkg)) Write(context_pkg_path, JSON.stringify(context_pkg))
``` ```
@@ -332,6 +731,13 @@ Write(context_pkg_path, JSON.stringify(context_pkg))
"categories_clarified": ["Architecture", "UX"], "categories_clarified": ["Architecture", "UX"],
"roles_updated": ["role1", "role2"] "roles_updated": ["role1", "role2"]
}, },
"feature_spec_results": {
"feature_mode": true,
"features_generated": ["F-001", "F-002", "F-003"],
"feature_index_path": ".brainstorming/feature-index.json",
"feature_specs_dir": ".brainstorming/feature-specs/",
"conflict_map_generated": true
},
"quality_metrics": { "quality_metrics": {
"user_intent_alignment": "validated", "user_intent_alignment": "validated",
"ambiguity_resolution": "complete", "ambiguity_resolution": "complete",
@@ -342,26 +748,53 @@ Write(context_pkg_path, JSON.stringify(context_pkg))
} }
``` ```
**Note**: `feature_spec_results` is only present when `feature_mode` is true. When `feature_mode` is false, this key is omitted entirely.
#### Step 3: Completion Report #### Step 3: Completion Report
```markdown ```markdown
## ✅ Clarification Complete ## Clarification Complete
**Enhancements Applied**: EP-001, EP-002, EP-003 **Enhancements Applied**: EP-001, EP-002, EP-003
**Questions Answered**: 3/5 **Questions Answered**: 3/5
**Roles Updated**: role1, role2, role3 **Roles Updated**: role1, role2, role3
### Feature Specs (feature_mode only)
**Feature Specs Generated**: F-001, F-002, F-003
**Feature Index**: .brainstorming/feature-index.json
**Spec Directory**: .brainstorming/feature-specs/
### Next Steps ### Next Steps
PROCEED: `/workflow:plan --session WFS-{session-id}` PROCEED: `/workflow:plan --session WFS-{session-id}`
``` ```
--- ---
## Output ## Output
**Location**: `.workflow/active/WFS-{session}/.brainstorming/[role]/analysis*.md` **Location (role analyses)**: `.workflow/active/WFS-{session}/.brainstorming/[role]/analysis*.md`
**Location (feature specs)**: `.workflow/active/WFS-{session}/.brainstorming/feature-specs/F-{id}-{slug}.md` [feature_mode]
**Location (feature index)**: `.workflow/active/WFS-{session}/.brainstorming/feature-index.json` [feature_mode]
**Updated Structure**: **Updated Directory Structure** (feature_mode):
```
.workflow/active/WFS-{session}/.brainstorming/
├── guidance-specification.md
├── feature-index.json # Phase 6.5 output
├── feature-specs/ # Phase 6 output directory
│ ├── F-001-{slug}.md # Consolidated feature spec (1500-2500 words)
│ ├── F-002-{slug}.md
│ └── F-00N-{slug}.md
├── {role-1}/
│ ├── analysis.md # Role overview index (read by Phase 3A)
│ ├── analysis-cross-cutting.md
│ ├── analysis-F-001-{slug}.md # Per-feature detail (read by Phase 6)
│ └── analysis-F-002-{slug}.md
└── {role-N}/
└── ...
```
**Updated Role Analysis Structure**:
```markdown ```markdown
## Clarifications ## Clarifications
### Session {date} ### Session {date}
@@ -378,25 +811,37 @@ Write(context_pkg_path, JSON.stringify(context_pkg))
- Architecture with rationale - Architecture with rationale
- Ambiguities resolved, placeholders removed - Ambiguities resolved, placeholders removed
- Consistent terminology - Consistent terminology
- Feature specs generated with cross-role conflict resolution [feature_mode]
- Feature index provides structured access for downstream consumers [feature_mode]
--- ---
## Quality Checklist ## Quality Checklist
**Content**: **Content**:
- All role analyses loaded/analyzed - All role analyses loaded/analyzed
- Cross-role analysis (consensus, conflicts, gaps) - Cross-role analysis (consensus, conflicts, gaps)
- 9-category ambiguity scan - 9-category ambiguity scan
- Questions prioritized - Questions prioritized
**Analysis**: **Analysis**:
- User intent validated - User intent validated
- Cross-role synthesis complete - Cross-role synthesis complete
- Ambiguities resolved - Ambiguities resolved
- Terminology consistent - Terminology consistent
**Documents**: **Documents**:
- Clarifications section formatted - Clarifications section formatted
- Sections reflect answers - Sections reflect answers
- No placeholders (TODO/TBD) - No placeholders (TODO/TBD)
- Valid Markdown - Valid Markdown
**Feature Specs (feature_mode only)**:
- Phase 3A reads only analysis.md index files (not sub-documents), input token <= 5K words
- feature_conflict_map generated with consensus/conflicts/cross_refs per feature
- Phase 6 parallel agents defined: one per feature, input token <= 7K words each
- Feature spec template has 7 sections, Section 2 (Design Decisions) is core
- Four-layer aggregation rules applied (direct reference/structured extraction/conflict distillation/cross-feature annotation)
- Each feature spec is 1500-2500 words
- feature-index.json generated with features[] + cross_cutting_specs[]
- feature-specs/ directory created with F-{id}-{slug}.md files

View File

@@ -279,6 +279,19 @@ Output:
Session ID: {session-id} Session ID: {session-id}
MCP Capabilities: {exa_code, exa_web, code_index} MCP Capabilities: {exa_code, exa_web, code_index}
## FEATURE SPECIFICATIONS (conditional)
If .workflow/active/{session-id}/.brainstorming/feature-specs/ exists:
Feature Index: .workflow/active/{session-id}/.brainstorming/feature-specs/feature-index.json
Feature Spec Dir: .workflow/active/{session-id}/.brainstorming/feature-specs/
Use feature-index.json to:
- Map features to implementation tasks (feature_id → task alignment)
- Reference individual feature spec files (spec_path) for detailed requirements
- Identify cross-cutting concerns (cross_cutting_specs) that span multiple tasks
- Align task priorities with feature priorities
If the directory does not exist, skip this section (backward compatible with non-brainstorm workflows).
## USER CONFIGURATION (from Phase 0) ## USER CONFIGURATION (from Phase 0)
Execution Method: ${userConfig.executionMethod} // agent|hybrid|cli Execution Method: ${userConfig.executionMethod} // agent|hybrid|cli
Preferred CLI Tool: ${userConfig.preferredCliTool} // codex|gemini|qwen|auto Preferred CLI Tool: ${userConfig.preferredCliTool} // codex|gemini|qwen|auto
@@ -461,6 +474,19 @@ Output:
Session ID: {session-id} Session ID: {session-id}
MCP Capabilities: {exa_code, exa_web, code_index} MCP Capabilities: {exa_code, exa_web, code_index}
## FEATURE SPECIFICATIONS (conditional)
If .workflow/active/{session-id}/.brainstorming/feature-specs/ exists:
Feature Index: .workflow/active/{session-id}/.brainstorming/feature-specs/feature-index.json
Feature Spec Dir: .workflow/active/{session-id}/.brainstorming/feature-specs/
Use feature-index.json to:
- Map features to module-scoped tasks (filter by ${module.paths.join(', ')})
- Reference individual feature spec files (spec_path) for detailed requirements
- Identify cross-cutting concerns affecting this module
- Align task priorities with feature priorities
If the directory does not exist, skip this section (backward compatible with non-brainstorm workflows).
## USER CONFIGURATION (from Phase 0) ## USER CONFIGURATION (from Phase 0)
Execution Method: ${userConfig.executionMethod} // agent|hybrid|cli Execution Method: ${userConfig.executionMethod} // agent|hybrid|cli
Preferred CLI Tool: ${userConfig.preferredCliTool} // codex|gemini|qwen|auto Preferred CLI Tool: ${userConfig.preferredCliTool} // codex|gemini|qwen|auto