From 8475a724ae5a5bc4f7df4a6af1d1745453104399 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Wed, 11 Feb 2026 16:30:07 +0800 Subject: [PATCH] feat: add spec-generator handoff bridge to workflow:plan consumption pipeline Phase 6 now creates brainstorm_artifacts-compatible bridge files (.brainstorming/guidance-specification.md, feature-index.json, feature-specs) when handing off to workflow:plan or req-plan, enabling context-search-agent auto-discovery without modifying downstream consumers. --- .claude/commands/workflow/spec.md | 107 +++++ .claude/skills/spec-generator/SKILL.md | 258 +++++++++++ .../phases/06-readiness-check.md | 433 ++++++++++++++++++ 3 files changed, 798 insertions(+) create mode 100644 .claude/commands/workflow/spec.md create mode 100644 .claude/skills/spec-generator/SKILL.md create mode 100644 .claude/skills/spec-generator/phases/06-readiness-check.md diff --git a/.claude/commands/workflow/spec.md b/.claude/commands/workflow/spec.md new file mode 100644 index 00000000..f8dfbdfc --- /dev/null +++ b/.claude/commands/workflow/spec.md @@ -0,0 +1,107 @@ +--- +name: spec +description: Specification generator - 6 phase document chain producing product brief, PRD, architecture, and epics. Triggers on "generate spec", "create specification", "spec generator". +argument-hint: "[-y|--yes] [-c|--continue] \"idea or requirement description\"" +allowed-tools: TodoWrite(*), Task(*), AskUserQuestion(*), Read(*), Grep(*), Glob(*), Bash(*), Edit(*), Write(*) +--- + +## Auto Mode + +When `--yes` or `-y`: Auto-confirm decisions, use recommended defaults, skip interactive validation. + +# Workflow Spec Command (/workflow:spec) + +## Quick Start + +```bash +# Basic usage +/workflow:spec "Build a task management system with real-time collaboration" + +# Auto mode (skip all confirmations) +/workflow:spec -y "User authentication system with OAuth2 and 2FA" + +# Continue existing session +/workflow:spec -c "task management" + +# Combined +/workflow:spec -y -c "task management" +``` + +**Skill**: `spec-generator` +**Output Directory**: `.workflow/.spec/SPEC-{slug}-{YYYY-MM-DD}/` +**Core Flow**: Discovery -> Product Brief -> PRD -> Architecture -> Epics -> Readiness Check + +## What This Command Does + +Generates a complete specification package through 6 sequential phases: + +1. **Discovery**: Analyze seed idea, explore codebase (optional), establish session +2. **Product Brief**: Multi-CLI analysis (Product/Technical/User perspectives) +3. **Requirements (PRD)**: Functional + non-functional requirements with MoSCoW priorities +4. **Architecture**: Component design, tech stack, ADRs with review +5. **Epics & Stories**: Implementation breakdown with dependency mapping +6. **Readiness Check**: Cross-document validation, quality scoring, handoff + +## Output Artifacts + +| Phase | Artifact | Description | +|-------|----------|-------------| +| 1 | `spec-config.json` | Session configuration and state | +| 1 | `discovery-context.json` | Codebase exploration (optional) | +| 2 | `product-brief.md` | Product brief with multi-perspective synthesis | +| 3 | `requirements.md` | Detailed PRD with acceptance criteria | +| 4 | `architecture.md` | Architecture decisions and component design | +| 5 | `epics.md` | Epic/Story breakdown with dependencies | +| 6 | `readiness-report.md` | Quality validation report | +| 6 | `spec-summary.md` | One-page executive summary | + +## Flags + +| Flag | Description | +|------|-------------| +| `-y`, `--yes` | Auto mode: skip all confirmations, use defaults | +| `-c`, `--continue` | Resume from last completed phase | + +## After Completion + +The readiness check (Phase 6) offers handoff to execution workflows: + +- `/workflow:lite-plan` - Execute one Epic at a time (direct text input) +- `/workflow:req-plan-with-file` - Generate execution roadmap +- `/workflow:plan` - Full planning for entire scope +- `/issue:new` - Create issues per Epic + +### Plan Integration (Automatic Bridge) + +When selecting "Full planning" or "Create roadmap", Phase 6 automatically: + +1. Creates a WFS session via `/workflow:session:start` +2. Generates `.brainstorming/` bridge files in the session directory: + - `guidance-specification.md` — synthesized from spec outputs (product-brief + requirements + architecture key decisions) + - `feature-specs/feature-index.json` — maps each Epic to a Feature entry + - `feature-specs/F-{num}-{slug}.md` — individual feature spec per Epic +3. Invokes the downstream workflow (`/workflow:plan` or `/workflow:req-plan-with-file`) + +The `context-search-agent` auto-discovers these `.brainstorming/` files and populates `context-package.json.brainstorm_artifacts`, which `action-planning-agent` consumes via the standard priority chain: `guidance_specification` → `feature_index` → `feature_specs`. No manual bridging required. + +## When to Use + +- Starting a new product/feature from scratch +- Need structured specification before implementation +- Want multi-perspective analysis of an idea +- Need traceable requirement -> architecture -> story chain +- Replacing ad-hoc brainstorming with structured output + +## Compared to Other Workflows + +| Workflow | Use When | +|----------|----------| +| `/workflow:spec` | Need full specification package before any coding | +| `/workflow:brainstorm-with-file` | Exploring ideas, not ready for structure | +| `/workflow:lite-plan` | Have clear requirements, ready to implement | +| `/workflow:plan` | Have requirements, need detailed task planning | +| `/workflow:req-plan-with-file` | Have requirements, need layered roadmap | + +--- + +**Now execute spec-generator for**: $ARGUMENTS diff --git a/.claude/skills/spec-generator/SKILL.md b/.claude/skills/spec-generator/SKILL.md new file mode 100644 index 00000000..c0c89c03 --- /dev/null +++ b/.claude/skills/spec-generator/SKILL.md @@ -0,0 +1,258 @@ +--- +name: spec-generator +description: Specification generator - 6 phase document chain producing product brief, PRD, architecture, and epics. Triggers on "generate spec", "create specification", "spec generator", "workflow:spec". +allowed-tools: Task, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Read, Write, Edit, Bash, Glob, Grep, Skill +--- + +# Spec Generator + +Structured specification document generator producing a complete specification package (Product Brief, PRD, Architecture, Epics) through 6 sequential phases with multi-CLI analysis and interactive refinement. **Document generation only** - execution handoff to existing workflows (lite-plan, plan, req-plan). + +## Architecture Overview + +``` +Phase 0: Specification Study (Read specs/ + templates/ - mandatory prerequisite) + | +Phase 1: Discovery -> spec-config.json + discovery-context.json + | +Phase 2: Product Brief -> product-brief.md (multi-CLI parallel analysis) + | +Phase 3: Requirements (PRD) -> requirements.md + | +Phase 4: Architecture -> architecture.md (multi-CLI review) + | +Phase 5: Epics & Stories -> epics.md + | +Phase 6: Readiness Check -> readiness-report.md + spec-summary.md + | + Handoff to execution workflows +``` + +## Key Design Principles + +1. **Document Chain**: Each phase builds on previous outputs, creating a traceable specification chain from idea to executable stories +2. **Multi-Perspective Analysis**: CLI tools (Gemini/Codex/Claude) provide product, technical, and user perspectives in parallel +3. **Interactive by Default**: Each phase offers user confirmation points; `-y` flag enables full auto mode +4. **Resumable Sessions**: `spec-config.json` tracks completed phases; `-c` flag resumes from last checkpoint +5. **Template-Driven**: All documents generated from standardized templates with YAML frontmatter +6. **Pure Documentation**: No code generation or execution - clean handoff to existing execution workflows + +--- + +## Mandatory Prerequisites + +> **Do NOT skip**: Before performing any operations, you **must** completely read the following documents. Proceeding without reading the specifications will result in outputs that do not meet quality standards. + +### Specification Documents (Required Reading) + +| Document | Purpose | Priority | +|----------|---------|----------| +| [specs/document-standards.md](specs/document-standards.md) | Document format, frontmatter, naming conventions | **P0 - Must read before execution** | +| [specs/quality-gates.md](specs/quality-gates.md) | Per-phase quality gate criteria and scoring | **P0 - Must read before execution** | + +### Template Files (Must read before generation) + +| Document | Purpose | +|----------|---------| +| [templates/product-brief.md](templates/product-brief.md) | Product brief document template | +| [templates/requirements-prd.md](templates/requirements-prd.md) | PRD document template | +| [templates/architecture-doc.md](templates/architecture-doc.md) | Architecture document template | +| [templates/epics-template.md](templates/epics-template.md) | Epic/Story document template | + +--- + +## Execution Flow + +``` +Input Parsing: + |- Parse $ARGUMENTS: extract idea/topic, flags (-y, -c, -m) + |- Detect mode: new | continue + |- If continue: read spec-config.json, resume from first incomplete phase + |- If new: proceed to Phase 1 + +Phase 1: Discovery & Seed Analysis + |- Ref: phases/01-discovery.md + |- Generate session ID: SPEC-{slug}-{YYYY-MM-DD} + |- Parse input (text or file reference) + |- Gemini CLI seed analysis (problem, users, domain, dimensions) + |- Codebase exploration (conditional, if project detected) + |- User confirmation (interactive, -y skips) + |- Output: spec-config.json, discovery-context.json (optional) + +Phase 2: Product Brief + |- Ref: phases/02-product-brief.md + |- 3 parallel CLI analyses: Product (Gemini) + Technical (Codex) + User (Claude) + |- Synthesize perspectives: convergent themes + conflicts + |- Interactive refinement (-y skips) + |- Output: product-brief.md (from template) + +Phase 3: Requirements / PRD + |- Ref: phases/03-requirements.md + |- Gemini CLI: expand goals into functional + non-functional requirements + |- Generate acceptance criteria per requirement + |- User priority sorting: MoSCoW (interactive, -y auto-assigns) + |- Output: requirements.md (from template) + +Phase 4: Architecture + |- Ref: phases/04-architecture.md + |- Gemini CLI: core components, tech stack, ADRs + |- Codebase integration mapping (conditional) + |- Codex CLI: architecture challenge + review + |- Interactive ADR decisions (-y auto-accepts) + |- Output: architecture.md (from template) + +Phase 5: Epics & Stories + |- Ref: phases/05-epics-stories.md + |- Gemini CLI: requirement grouping into Epics, MVP subset tagging + |- Story generation: As a...I want...So that... + |- Dependency mapping (Mermaid) + |- Interactive validation (-y skips) + |- Output: epics.md (from template) + +Phase 6: Readiness Check + |- Ref: phases/06-readiness-check.md + |- Cross-document validation (completeness, consistency, traceability) + |- Quality scoring per dimension + |- Output: readiness-report.md, spec-summary.md + |- Handoff options: lite-plan, req-plan, plan, issue:new, export only, iterate + +Complete: Full specification package ready for execution + +Phase 6 → Handoff Bridge (conditional, based on user selection): + ├─ lite-plan: Extract first MVP Epic description → direct text input + ├─ plan / req-plan: Create WFS session + .brainstorming/ bridge files + │ ├─ guidance-specification.md (synthesized from spec outputs) + │ ├─ feature-specs/feature-index.json (Epic → Feature mapping) + │ └─ feature-specs/F-{num}-{slug}.md (one per Epic) + ├─ issue:new: Create issues per Epic + └─ context-search-agent auto-discovers .brainstorming/ + → context-package.json.brainstorm_artifacts populated + → action-planning-agent consumes: guidance_spec (P1) → feature_index (P2) +``` + +## Directory Setup + +```javascript +// Session ID generation +const slug = topic.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-').slice(0, 40); +const date = new Date().toISOString().slice(0, 10); +const sessionId = `SPEC-${slug}-${date}`; +const workDir = `.workflow/.spec/${sessionId}`; + +Bash(`mkdir -p "${workDir}"`); +``` + +## Output Structure + +``` +.workflow/.spec/SPEC-{slug}-{YYYY-MM-DD}/ +|- spec-config.json # Session configuration + phase state +|- discovery-context.json # Codebase exploration results (optional) +|- product-brief.md # Phase 2: Product brief +|- requirements.md # Phase 3: Detailed PRD +|- architecture.md # Phase 4: Architecture decisions +|- epics.md # Phase 5: Epic/Story breakdown +|- readiness-report.md # Phase 6: Quality report +|- spec-summary.md # Phase 6: One-page executive summary +``` + +## State Management + +**spec-config.json** serves as core state file: +```json +{ + "session_id": "SPEC-xxx-2026-02-11", + "seed_input": "User input text", + "input_type": "text", + "timestamp": "ISO8601", + "mode": "interactive", + "complexity": "moderate", + "depth": "standard", + "focus_areas": [], + "seed_analysis": { + "problem_statement": "...", + "target_users": [], + "domain": "...", + "constraints": [], + "dimensions": [] + }, + "has_codebase": false, + "phasesCompleted": [ + { "phase": 1, "name": "discovery", "output_file": "spec-config.json", "completed_at": "ISO8601" } + ] +} +``` + +**Resume mechanism**: `-c|--continue` flag reads `spec-config.json.phasesCompleted`, resumes from first incomplete phase. + +## Core Rules + +1. **Start Immediately**: First action is TaskCreate initialization, then Phase 0 (spec study), then Phase 1 +2. **Progressive Phase Loading**: Read phase docs ONLY when that phase is about to execute +3. **Auto-Continue**: All phases run autonomously; check TaskList to execute next pending phase +4. **Parse Every Output**: Extract required data from each phase for next phase context +5. **DO NOT STOP**: Continuous 6-phase pipeline until all phases complete or user exits +6. **Respect -y Flag**: When auto mode, skip all AskUserQuestion calls, use recommended defaults +7. **Respect -c Flag**: When continue mode, load spec-config.json and resume from checkpoint + +## Reference Documents by Phase + +### Phase 1: Discovery +| Document | Purpose | When to Use | +|----------|---------|-------------| +| [phases/01-discovery.md](phases/01-discovery.md) | Seed analysis and session setup | Phase start | +| [specs/document-standards.md](specs/document-standards.md) | Frontmatter format for spec-config.json | Config generation | + +### Phase 2: Product Brief +| Document | Purpose | When to Use | +|----------|---------|-------------| +| [phases/02-product-brief.md](phases/02-product-brief.md) | Multi-CLI analysis orchestration | Phase start | +| [templates/product-brief.md](templates/product-brief.md) | Document template | Document generation | + +### Phase 3: Requirements +| Document | Purpose | When to Use | +|----------|---------|-------------| +| [phases/03-requirements.md](phases/03-requirements.md) | PRD generation workflow | Phase start | +| [templates/requirements-prd.md](templates/requirements-prd.md) | Document template | Document generation | + +### Phase 4: Architecture +| Document | Purpose | When to Use | +|----------|---------|-------------| +| [phases/04-architecture.md](phases/04-architecture.md) | Architecture decision workflow | Phase start | +| [templates/architecture-doc.md](templates/architecture-doc.md) | Document template | Document generation | + +### Phase 5: Epics & Stories +| Document | Purpose | When to Use | +|----------|---------|-------------| +| [phases/05-epics-stories.md](phases/05-epics-stories.md) | Epic/Story decomposition | Phase start | +| [templates/epics-template.md](templates/epics-template.md) | Document template | Document generation | + +### Phase 6: Readiness Check +| Document | Purpose | When to Use | +|----------|---------|-------------| +| [phases/06-readiness-check.md](phases/06-readiness-check.md) | Cross-document validation | Phase start | +| [specs/quality-gates.md](specs/quality-gates.md) | Quality scoring criteria | Validation | + +### Debugging & Troubleshooting +| Issue | Solution Document | +|-------|-------------------| +| Phase execution failed | Refer to the relevant Phase documentation | +| Output does not meet expectations | [specs/quality-gates.md](specs/quality-gates.md) | +| Document format issues | [specs/document-standards.md](specs/document-standards.md) | + +## Error Handling + +| Phase | Error | Blocking? | Action | +|-------|-------|-----------|--------| +| Phase 1 | Empty input | Yes | Error and exit | +| Phase 1 | CLI seed analysis fails | No | Use basic parsing fallback | +| Phase 2 | Single CLI perspective fails | No | Continue with available perspectives | +| Phase 2 | All CLI calls fail | No | Generate basic brief from seed analysis | +| Phase 3 | Gemini CLI fails | No | Use codex fallback | +| Phase 4 | Architecture review fails | No | Skip review, proceed with initial analysis | +| Phase 5 | Story generation fails | No | Generate epics without detailed stories | +| Phase 6 | Validation CLI fails | No | Generate partial report with available data | + +### CLI Fallback Chain + +Gemini -> Codex -> Claude -> degraded mode (local analysis only) diff --git a/.claude/skills/spec-generator/phases/06-readiness-check.md b/.claude/skills/spec-generator/phases/06-readiness-check.md new file mode 100644 index 00000000..5810ef87 --- /dev/null +++ b/.claude/skills/spec-generator/phases/06-readiness-check.md @@ -0,0 +1,433 @@ +# Phase 6: Readiness Check + +Validate the complete specification package, generate quality report and executive summary, provide execution handoff options. + +## Objective + +- Cross-document validation: completeness, consistency, traceability, depth +- Generate quality scores per dimension +- Produce readiness-report.md with issue list and traceability matrix +- Produce spec-summary.md as one-page executive summary +- Update all document frontmatter to `status: complete` +- Present handoff options to execution workflows + +## Input + +- All Phase 2-5 outputs: `product-brief.md`, `requirements.md`, `architecture.md`, `epics.md` +- Config: `{workDir}/spec-config.json` +- Reference: `specs/quality-gates.md` + +## Execution Steps + +### Step 1: Load All Documents + +```javascript +const specConfig = JSON.parse(Read(`${workDir}/spec-config.json`)); +const productBrief = Read(`${workDir}/product-brief.md`); +const requirements = Read(`${workDir}/requirements.md`); +const architecture = Read(`${workDir}/architecture.md`); +const epics = Read(`${workDir}/epics.md`); +const qualityGates = Read('specs/quality-gates.md'); +``` + +### Step 2: Cross-Document Validation via Gemini CLI + +```javascript +Bash({ + command: `ccw cli -p "PURPOSE: Validate specification package for completeness, consistency, traceability, and depth. +Success: Comprehensive quality report with scores, issues, and traceability matrix. + +DOCUMENTS TO VALIDATE: + +=== PRODUCT BRIEF === +${productBrief.slice(0, 3000)} + +=== REQUIREMENTS === +${requirements.slice(0, 4000)} + +=== ARCHITECTURE === +${architecture.slice(0, 3000)} + +=== EPICS === +${epics.slice(0, 3000)} + +QUALITY CRITERIA (from quality-gates.md): +${qualityGates.slice(0, 2000)} + +TASK: +Perform 4-dimension validation: + +1. COMPLETENESS (25%): + - All required sections present in each document? + - All template fields filled with substantive content? + - Score 0-100 with specific gaps listed + +2. CONSISTENCY (25%): + - Terminology uniform across documents? + - User personas consistent? + - Scope consistent (PRD does not exceed brief)? + - Tech stack references match between architecture and epics? + - Score 0-100 with inconsistencies listed + +3. TRACEABILITY (25%): + - Every goal has >= 1 requirement? + - Every Must requirement has architecture coverage? + - Every Must requirement appears in >= 1 story? + - ADR choices reflected in epics? + - Build traceability matrix: Goal -> Requirement -> Architecture -> Epic/Story + - Score 0-100 with orphan items listed + +4. DEPTH (25%): + - Acceptance criteria specific and testable? + - Architecture decisions justified with alternatives? + - Stories estimable by dev team? + - Score 0-100 with vague areas listed + +ALSO: +- List all issues found, classified as Error/Warning/Info +- Generate overall weighted score +- Determine gate: Pass (>=80) / Review (60-79) / Fail (<60) + +MODE: analysis +EXPECTED: JSON-compatible output with: dimension scores, overall score, gate, issues list (severity + description + location), traceability matrix +CONSTRAINTS: Be thorough but fair. Focus on actionable issues. +" --tool gemini --mode analysis`, + run_in_background: true +}); + +// Wait for CLI result +``` + +### Step 3: Generate readiness-report.md + +```javascript +const frontmatterReport = `--- +session_id: ${specConfig.session_id} +phase: 6 +document_type: readiness-report +status: complete +generated_at: ${new Date().toISOString()} +stepsCompleted: ["load-all", "cross-validation", "scoring", "report-generation"] +version: 1 +dependencies: + - product-brief.md + - requirements.md + - architecture.md + - epics.md +---`; + +// Report content from CLI validation output: +// - Quality Score Summary (4 dimensions + overall) +// - Gate Decision (Pass/Review/Fail) +// - Issue List (grouped by severity: Error, Warning, Info) +// - Traceability Matrix (Goal -> Req -> Arch -> Epic/Story) +// - Recommendations for improvement + +Write(`${workDir}/readiness-report.md`, `${frontmatterReport}\n\n${reportContent}`); +``` + +### Step 4: Generate spec-summary.md + +```javascript +const frontmatterSummary = `--- +session_id: ${specConfig.session_id} +phase: 6 +document_type: spec-summary +status: complete +generated_at: ${new Date().toISOString()} +stepsCompleted: ["synthesis"] +version: 1 +dependencies: + - product-brief.md + - requirements.md + - architecture.md + - epics.md + - readiness-report.md +---`; + +// One-page executive summary: +// - Product Name & Vision (from product-brief.md) +// - Problem & Target Users (from product-brief.md) +// - Key Requirements count (Must/Should/Could from requirements.md) +// - Architecture Style & Tech Stack (from architecture.md) +// - Epic Overview (count, MVP scope from epics.md) +// - Quality Score (from readiness-report.md) +// - Recommended Next Step +// - File manifest with links + +Write(`${workDir}/spec-summary.md`, `${frontmatterSummary}\n\n${summaryContent}`); +``` + +### Step 5: Update All Document Status + +```javascript +// Update frontmatter status to 'complete' in all documents +const docs = ['product-brief.md', 'requirements.md', 'architecture.md', 'epics.md']; +for (const doc of docs) { + const content = Read(`${workDir}/${doc}`); + const updated = content.replace(/status: draft/, 'status: complete'); + Write(`${workDir}/${doc}`, updated); +} + +// Update spec-config.json +specConfig.phasesCompleted.push({ + phase: 6, + name: "readiness-check", + output_file: "readiness-report.md", + completed_at: new Date().toISOString() +}); +Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2)); +``` + +### Step 6: Handoff Options + +```javascript +AskUserQuestion({ + questions: [ + { + question: "Specification package is complete. What would you like to do next?", + header: "Next Step", + multiSelect: false, + options: [ + { + label: "Execute via lite-plan", + description: "Start implementing with /workflow:lite-plan, one Epic at a time" + }, + { + label: "Create roadmap", + description: "Generate execution roadmap with /workflow:req-plan-with-file" + }, + { + label: "Full planning", + description: "Detailed planning with /workflow:plan for the full scope" + }, + { + label: "Create Issues", + description: "Generate issues for each Epic via /issue:new" + } + ] + } + ] +}); + +// Based on user selection, execute the corresponding handoff: + +if (selection === "Execute via lite-plan") { + // lite-plan accepts a text description directly + const epicsContent = Read(`${workDir}/epics.md`); + // Extract first MVP Epic's title + description as task input + const firstEpic = extractFirstMvpEpicDescription(epicsContent); + Skill(skill="workflow:lite-plan", args=`"${firstEpic}"`) +} + +if (selection === "Full planning" || selection === "Create roadmap") { + // === Bridge: Build brainstorm_artifacts compatible structure === + // This enables workflow:plan's context-search-agent to discover spec artifacts + // via the standard .brainstorming/ directory convention. + + // Step A: Read all spec documents + const specSummary = Read(`${workDir}/spec-summary.md`); + const productBrief = Read(`${workDir}/product-brief.md`); + const requirements = Read(`${workDir}/requirements.md`); + const architecture = Read(`${workDir}/architecture.md`); + const epics = Read(`${workDir}/epics.md`); + + // Step B: Build structured description from spec-summary + const structuredDesc = `GOAL: ${extractGoal(specSummary)} +SCOPE: ${extractScope(specSummary)} +CONTEXT: Generated from spec session ${specConfig.session_id}. Source: ${workDir}/`; + + // Step C: Create WFS session (provides session directory + .brainstorming/) + Skill(skill="workflow:session:start", args=`--auto "${structuredDesc}"`) + // → Produces sessionId (WFS-xxx) and session directory at .workflow/active/{sessionId}/ + + // Step D: Create .brainstorming/ bridge files + const brainstormDir = `.workflow/active/${sessionId}/.brainstorming`; + Bash(`mkdir -p "${brainstormDir}/feature-specs"`); + + // D.1: guidance-specification.md (highest priority - action-planning-agent reads first) + // Synthesized from spec-summary + product-brief key decisions + architecture decisions + Write(`${brainstormDir}/guidance-specification.md`, ` +# ${specConfig.seed_analysis.problem_statement} - Confirmed Guidance Specification + +**Source**: spec-generator session ${specConfig.session_id} +**Generated**: ${new Date().toISOString()} +**Spec Directory**: ${workDir} + +## 1. Project Positioning & Goals +${extractSection(productBrief, "Vision")} +${extractSection(productBrief, "Goals")} + +## 2. Requirements Summary +${extractSection(requirements, "Requirement Summary")} + +## 3. Architecture Decisions +${extractSection(architecture, "Architecture Decision Records")} +${extractSection(architecture, "Technology Stack")} + +## 4. Implementation Scope +${extractSection(epics, "Epic Overview")} +${extractSection(epics, "MVP Scope")} + +## Feature Decomposition +${extractFeatureTable(epics)} + +## Appendix: Source Documents +| Document | Path | Description | +|----------|------|-------------| +| Product Brief | ${workDir}/product-brief.md | Vision, goals, scope | +| Requirements | ${workDir}/requirements.md | Functional + non-functional requirements | +| Architecture | ${workDir}/architecture.md | ADRs, tech stack, components | +| Epics | ${workDir}/epics.md | Epic/Story breakdown | +| Readiness Report | ${workDir}/readiness-report.md | Quality validation | +`); + + // D.2: feature-index.json (each Epic mapped to a Feature) + // Path: feature-specs/feature-index.json (matches context-search-agent discovery at line 344) + const epicsList = parseEpics(epics); // Extract: id, slug, name, description, mvp, stories[] + const featureIndex = { + version: "1.0", + source: "spec-generator", + spec_session: specConfig.session_id, + features: epicsList.map(epic => ({ + id: `F-${epic.id.replace('EPIC-', '')}`, + slug: epic.slug, + name: epic.name, + description: epic.description, + priority: epic.mvp ? "High" : "Medium", + spec_path: `${brainstormDir}/feature-specs/F-${epic.id.replace('EPIC-','')}-${epic.slug}.md`, + source_epic: epic.id, + stories: epic.stories + })), + cross_cutting_specs: [] + }; + Write(`${brainstormDir}/feature-specs/feature-index.json`, JSON.stringify(featureIndex, null, 2)); + + // D.3: Individual feature-spec files (one per Epic) + // Filename pattern: F-{num}-{slug}.md (matches context-search-agent glob F-*-*.md) + epicsList.forEach(epic => { + const epicDetail = extractEpicDetail(epics, epic.id); + const relatedReqs = extractRelatedRequirements(requirements, epic.id); + Write(`${brainstormDir}/feature-specs/F-${epic.id.replace('EPIC-','')}-${epic.slug}.md`, ` +# Feature Spec: ${epic.id} - ${epic.name} + +**Source**: ${workDir}/epics.md +**Priority**: ${epic.mvp ? "MVP" : "Post-MVP"} +**Related Requirements**: ${relatedReqs.join(', ')} + +## Scope +${epicDetail.scope} + +## Stories +${epicDetail.stories.map(s => `- ${s.id}: ${s.title} (${s.estimate})`).join('\n')} + +## Acceptance Criteria +${epicDetail.acceptanceCriteria} + +## Architecture Notes +${extractArchitectureNotes(architecture, epic.id)} +`); + }); + + // Step E: Invoke downstream workflow + // context-search-agent will auto-discover .brainstorming/ files + // → context-package.json.brainstorm_artifacts populated + // → action-planning-agent loads guidance_specification (priority 1) + feature_index (priority 2) + if (selection === "Full planning") { + Skill(skill="workflow:plan", args=`"${structuredDesc}"`) + } else { + Skill(skill="workflow:req-plan-with-file", args=`"${extractGoal(specSummary)}"`) + } +} + +if (selection === "Create Issues") { + // For each Epic, create an issue + const epics = Read(`${workDir}/epics.md`); + const epicsList = parseEpics(epics); + epicsList.forEach(epic => { + Skill(skill="issue:new", args=`"${epic.name}: ${epic.description}"`) + }); +} + +// If user selects "Other": Export only or return to specific phase +``` + +#### Helper Functions Reference (pseudocode) + +The following helper functions are used in the handoff bridge. They operate on the markdown content loaded from spec documents: + +```javascript +// Extract the first MVP Epic's title + scope as a one-line task description +function extractFirstMvpEpicDescription(epicsContent) { + // Find first Epic marked as MVP, return: "Epic Name - Brief scope description" +} + +// Extract GOAL/SCOPE from spec-summary frontmatter or ## sections +function extractGoal(specSummary) { /* Return the Vision/Goal line */ } +function extractScope(specSummary) { /* Return the Scope/MVP boundary */ } + +// Extract a named ## section from a markdown document +function extractSection(markdown, sectionName) { + // Return content between ## {sectionName} and next ## heading +} + +// Build a markdown table of Epics from epics.md +function extractFeatureTable(epicsContent) { + // Return: | Epic ID | Name | Priority | Story Count | +} + +// Parse epics.md into structured Epic objects +function parseEpics(epicsContent) { + // Returns: [{ id, slug, name, description, mvp, stories[] }] +} + +// Extract detailed Epic section (scope, stories, acceptance criteria) +function extractEpicDetail(epicsContent, epicId) { + // Returns: { scope, stories[], acceptanceCriteria } +} + +// Find requirements related to a specific Epic +function extractRelatedRequirements(requirementsContent, epicId) { + // Returns: ["REQ-001", "REQ-003"] based on traceability references +} + +// Extract architecture notes relevant to a specific Epic +function extractArchitectureNotes(architectureContent, epicId) { + // Returns: relevant ADRs, component references, tech stack notes +} +``` + +## Output + +- **File**: `readiness-report.md` - Quality validation report +- **File**: `spec-summary.md` - One-page executive summary +- **Format**: Markdown with YAML frontmatter + +## Quality Checklist + +- [ ] All 4 documents validated (product-brief, requirements, architecture, epics) +- [ ] All frontmatter parseable and valid +- [ ] Cross-references checked +- [ ] Overall quality score calculated +- [ ] No unresolved Error-severity issues +- [ ] Traceability matrix generated +- [ ] spec-summary.md created +- [ ] All document statuses updated to 'complete' +- [ ] Handoff options presented + +## Completion + +This is the final phase. The specification package is ready for execution handoff. + +### Output Files Manifest + +| File | Phase | Description | +|------|-------|-------------| +| `spec-config.json` | 1 | Session configuration and state | +| `discovery-context.json` | 1 | Codebase exploration (optional) | +| `product-brief.md` | 2 | Product brief with multi-perspective synthesis | +| `requirements.md` | 3 | Detailed PRD with MoSCoW priorities | +| `architecture.md` | 4 | Architecture decisions and component design | +| `epics.md` | 5 | Epic/Story breakdown with dependencies | +| `readiness-report.md` | 6 | Quality validation report | +| `spec-summary.md` | 6 | One-page executive summary |