feat: unified task.json schema migration and multi-module updates

- Create task-schema.json (JSON Schema draft-07) with 10 field blocks fusing
  Unified JSONL, 6-field Task JSON, and Solution Schema advantages
- Migrate unified-execute-with-file from JSONL to .task/*.json directory scanning
- Migrate 3 producers (lite-plan, plan-converter, collaborative-plan) to
  .task/*.json multi-file output
- Add review-cycle Phase 7.5 export-to-tasks (FIX-*.json) and issue-resolve
  --export-tasks option
- Add schema compatibility annotations to action-planning-agent, workflow-plan,
  and tdd-plan
- Add spec-generator skill phases and templates
- Add memory v2 pipeline (consolidation, extraction, job scheduler, embedder)
- Add secret-redactor utility and core-memory enhancements
- Add codex-lens accuracy benchmarks and staged env config overrides
This commit is contained in:
catlog22
2026-02-11 17:40:56 +08:00
parent 7aa1038951
commit 99ee4e7d36
36 changed files with 7823 additions and 315 deletions

View File

@@ -283,6 +283,34 @@ Generate individual `.task/IMPL-*.json` files with the following structure:
- `resume_from`: Parent task's cli_execution_id (for resume/fork)
- `merge_from`: Array of parent cli_execution_ids (for merge_fork)
#### Schema Compatibility
The 6-field task JSON is a **superset** of `task-schema.json` (the unified task schema at `.ccw/workflows/cli-templates/schemas/task-schema.json`). All generated `.task/IMPL-*.json` files are compatible with the unified schema via the following field mapping:
| 6-Field Task JSON (this schema) | task-schema.json (unified) | Notes |
|--------------------------------|---------------------------|-------|
| `id` | `id` | Direct mapping |
| `title` | `title` | Direct mapping |
| `status` | `status` | Direct mapping |
| `meta.type` | `type` | Flattened in unified schema |
| `meta.agent` | `meta.agent` | Same path, preserved |
| `meta.execution_config` | `meta.execution_config` | Same path, preserved |
| `context.requirements` | `description` + `implementation` | Unified schema splits into goal description and step-by-step guide |
| `context.acceptance` | `convergence.criteria` | **Key mapping**: acceptance criteria become convergence criteria |
| `context.focus_paths` | `focus_paths` | Moved to top-level in unified schema |
| `context.depends_on` | `depends_on` | Moved to top-level in unified schema |
| `context.shared_context` | _(no direct equivalent)_ | 6-field extension for tech stack and conventions |
| `context.artifacts` | `evidence` + `inputs` | Unified schema uses generic evidence/inputs arrays |
| `flow_control.target_files` | `files[].path` | Unified schema uses structured file objects |
| `flow_control.implementation_approach` | `implementation` | Unified schema uses flat string array |
| `flow_control.pre_analysis` | _(no direct equivalent)_ | 6-field extension for pre-execution analysis |
| `context_package_path` | `context_package_path` | Direct mapping |
| `cli_execution_id` | `cli_execution.id` | Nested in unified schema |
| `cli_execution` | `cli_execution` | Direct mapping |
**Backward Compatibility**: The 6-field schema retains all existing fields. The unified schema fields (`convergence`, `depends_on` at top-level, `files`, `implementation`) are accepted as **optional aliases** when present. Consumers SHOULD check both locations (e.g., `convergence.criteria` OR `context.acceptance`).
**CLI Execution Strategy Rules** (MANDATORY - apply to all tasks):
| Dependency Pattern | Strategy | CLI Command Pattern |
@@ -418,6 +446,14 @@ userConfig.executionMethod → meta.execution_config
"auth_strategy": "JWT with refresh tokens",
"conventions": ["Follow existing auth patterns in src/auth/legacy/"]
},
"convergence": {
"criteria": [
"3 features implemented: verify by npm test -- auth (exit code 0)",
"5 files created: verify by ls src/auth/*.ts | wc -l = 5"
],
"verification": "npm test -- auth && ls src/auth/*.ts | wc -l",
"definition_of_done": "Authentication module fully functional with all endpoints and tests passing"
},
"artifacts": [
{
"type": "feature_spec|cross_cutting_spec|synthesis_specification|topic_framework|individual_role_analysis",
@@ -437,6 +473,10 @@ userConfig.executionMethod → meta.execution_config
- `requirements`: **QUANTIFIED** implementation requirements (MUST include explicit counts and enumerated lists, e.g., "5 files: [list]")
- `focus_paths`: Target directories/files (concrete paths without wildcards)
- `acceptance`: **MEASURABLE** acceptance criteria (MUST include verification commands, e.g., "verify by ls ... | wc -l = N")
- `convergence`: _(Optional, unified schema alias)_ Structured completion criteria object following `task-schema.json` format. When present, `convergence.criteria` maps to `acceptance`. Use **either** `acceptance` (6-field native) **or** `convergence` (unified schema native), not both. See [Schema Compatibility](#schema-compatibility) for full mapping.
- `criteria`: Array of testable completion conditions (equivalent to `acceptance`)
- `verification`: Executable verification command or steps
- `definition_of_done`: Business-language completion definition (non-technical)
- `depends_on`: Prerequisite task IDs that must complete before this task starts
- `inherited`: Context, patterns, and dependencies passed from parent task
- `shared_context`: Tech stack, conventions, and architectural strategies for the task

View File

@@ -0,0 +1,81 @@
# Spec Generator
Structured specification document generator producing a complete document chain (Product Brief -> PRD -> Architecture -> Epics).
## Usage
```bash
# Via workflow command
/workflow:spec "Build a task management system"
/workflow:spec -y "User auth with OAuth2" # Auto mode
/workflow:spec -c "task management" # Resume session
```
## Architecture
```
spec-generator/
|- SKILL.md # Entry point: metadata + architecture + flow
|- phases/
| |- 01-discovery.md # Seed analysis + codebase exploration
| |- 02-product-brief.md # Multi-CLI product brief generation
| |- 03-requirements.md # PRD with MoSCoW priorities
| |- 04-architecture.md # Architecture decisions + review
| |- 05-epics-stories.md # Epic/Story decomposition
| |- 06-readiness-check.md # Quality validation + handoff
|- specs/
| |- document-standards.md # Format, frontmatter, naming rules
| |- quality-gates.md # Per-phase quality criteria
|- templates/
| |- product-brief.md # Product brief template
| |- requirements-prd.md # PRD template
| |- architecture-doc.md # Architecture document template
| |- epics-template.md # Epic/Story template
|- README.md # This file
```
## 6-Phase Pipeline
| Phase | Name | Output | CLI Tools |
|-------|------|--------|-----------|
| 1 | Discovery | spec-config.json | Gemini (analysis) |
| 2 | Product Brief | product-brief.md | Gemini + Codex + Claude (parallel) |
| 3 | Requirements | requirements.md | Gemini (analysis) |
| 4 | Architecture | architecture.md | Gemini + Codex (sequential) |
| 5 | Epics & Stories | epics.md | Gemini (analysis) |
| 6 | Readiness Check | readiness-report.md, spec-summary.md | Gemini (validation) |
## Runtime Output
```
.workflow/.spec/SPEC-{slug}-{YYYY-MM-DD}/
|- spec-config.json # Session state
|- discovery-context.json # Codebase context (optional)
|- product-brief.md # Phase 2
|- requirements.md # Phase 3
|- architecture.md # Phase 4
|- epics.md # Phase 5
|- readiness-report.md # Phase 6
|- spec-summary.md # Phase 6
```
## Flags
- `-y|--yes`: Auto mode - skip all interactive confirmations
- `-c|--continue`: Resume from last completed phase
## Handoff
After Phase 6, choose execution path:
- `workflow:lite-plan` - Execute per Epic
- `workflow:req-plan-with-file` - Roadmap decomposition
- `workflow:plan` - Full planning
- `issue:new` - Create issues per Epic
## Design Principles
- **Document chain**: Each phase builds on previous outputs
- **Multi-perspective**: Gemini/Codex/Claude provide different viewpoints
- **Template-driven**: Consistent format via templates + frontmatter
- **Resumable**: spec-config.json tracks completed phases
- **Pure documentation**: No code generation - clean handoff to execution workflows

View File

@@ -0,0 +1,242 @@
# Phase 1: Discovery
Parse input, analyze the seed idea, optionally explore codebase, establish session configuration.
## Objective
- Generate session ID and create output directory
- Parse user input (text description or file reference)
- Analyze seed via Gemini CLI to extract problem space dimensions
- Conditionally explore codebase for existing patterns and constraints
- Gather user preferences (depth, focus areas) via interactive confirmation
- Write `spec-config.json` as the session state file
## Input
- Dependency: `$ARGUMENTS` (user input from command)
- Flags: `-y` (auto mode), `-c` (continue mode)
## Execution Steps
### Step 1: Session Initialization
```javascript
// Parse arguments
const args = $ARGUMENTS;
const autoMode = args.includes('-y') || args.includes('--yes');
const continueMode = args.includes('-c') || args.includes('--continue');
// Extract the idea/topic (remove flags)
const idea = args.replace(/(-y|--yes|-c|--continue)\s*/g, '').trim();
// Generate session ID
const slug = idea.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 40);
const date = new Date().toISOString().slice(0, 10);
const sessionId = `SPEC-${slug}-${date}`;
const workDir = `.workflow/.spec/${sessionId}`;
// Check for continue mode
if (continueMode) {
// Find existing session
const existingSessions = Glob('.workflow/.spec/SPEC-*/spec-config.json');
// If slug matches an existing session, load it and resume
// Read spec-config.json, find first incomplete phase, jump to that phase
return; // Resume logic handled by orchestrator
}
// Create output directory
Bash(`mkdir -p "${workDir}"`);
```
### Step 2: Input Parsing
```javascript
// Determine input type
if (idea.startsWith('@') || idea.endsWith('.md') || idea.endsWith('.txt')) {
// File reference - read and extract content
const filePath = idea.replace(/^@/, '');
const fileContent = Read(filePath);
// Use file content as the seed
inputType = 'file';
seedInput = fileContent;
} else {
// Direct text description
inputType = 'text';
seedInput = idea;
}
```
### Step 3: Seed Analysis via Gemini CLI
```javascript
Bash({
command: `ccw cli -p "PURPOSE: Analyze this seed idea/requirement to extract structured problem space dimensions.
Success: Clear problem statement, target users, domain identification, 3-5 exploration dimensions.
SEED INPUT:
${seedInput}
TASK:
- Extract a clear problem statement (what problem does this solve?)
- Identify target users (who benefits?)
- Determine the domain (technical, business, consumer, etc.)
- List constraints (budget, time, technical, regulatory)
- Generate 3-5 exploration dimensions (key areas to investigate)
- Assess complexity: simple (1-2 components), moderate (3-5 components), complex (6+ components)
MODE: analysis
EXPECTED: JSON output with fields: problem_statement, target_users[], domain, constraints[], dimensions[], complexity
CONSTRAINTS: Be specific and actionable, not vague
" --tool gemini --mode analysis`,
run_in_background: true
});
// Wait for CLI result before continuing
```
Parse the CLI output into structured `seedAnalysis`:
```javascript
const seedAnalysis = {
problem_statement: "...",
target_users: ["..."],
domain: "...",
constraints: ["..."],
dimensions: ["..."]
};
const complexity = "moderate"; // from CLI output
```
### Step 4: Codebase Exploration (Conditional)
```javascript
// Detect if running inside a project with code
const hasCodebase = Glob('**/*.{ts,js,py,java,go,rs}').length > 0
|| Glob('package.json').length > 0
|| Glob('Cargo.toml').length > 0;
if (hasCodebase) {
Task({
subagent_type: "cli-explore-agent",
run_in_background: false,
description: `Explore codebase for spec: ${slug}`,
prompt: `
## Spec Generator Context
Topic: ${seedInput}
Dimensions: ${seedAnalysis.dimensions.join(', ')}
Session: ${workDir}
## MANDATORY FIRST STEPS
1. Search for code related to topic keywords
2. Read project config files (package.json, pyproject.toml, etc.) if they exist
## Exploration Focus
- Identify existing implementations related to the topic
- Find patterns that could inform architecture decisions
- Map current architecture constraints
- Locate integration points and dependencies
## Output
Write findings to: ${workDir}/discovery-context.json
Schema:
{
"relevant_files": [{"path": "...", "relevance": "high|medium|low", "rationale": "..."}],
"existing_patterns": ["pattern descriptions"],
"architecture_constraints": ["constraint descriptions"],
"integration_points": ["integration point descriptions"],
"tech_stack": {"languages": [], "frameworks": [], "databases": []},
"_metadata": { "exploration_type": "spec-discovery", "timestamp": "ISO8601" }
}
`
});
}
```
### Step 5: User Confirmation (Interactive)
```javascript
if (!autoMode) {
// Confirm problem statement and select depth
AskUserQuestion({
questions: [
{
question: `Problem statement: "${seedAnalysis.problem_statement}" - Is this accurate?`,
header: "Problem",
multiSelect: false,
options: [
{ label: "Accurate", description: "Proceed with this problem statement" },
{ label: "Needs adjustment", description: "I'll refine the problem statement" }
]
},
{
question: "What specification depth do you need?",
header: "Depth",
multiSelect: false,
options: [
{ label: "Light", description: "Quick overview - key decisions only" },
{ label: "Standard (Recommended)", description: "Balanced detail for most projects" },
{ label: "Comprehensive", description: "Maximum detail for complex/critical projects" }
]
},
{
question: "Which areas should we focus on?",
header: "Focus",
multiSelect: true,
options: seedAnalysis.dimensions.map(d => ({ label: d, description: `Explore ${d} in depth` }))
}
]
});
} else {
// Auto mode defaults
depth = "standard";
focusAreas = seedAnalysis.dimensions;
}
```
### Step 6: Write spec-config.json
```javascript
const specConfig = {
session_id: sessionId,
seed_input: seedInput,
input_type: inputType,
timestamp: new Date().toISOString(),
mode: autoMode ? "auto" : "interactive",
complexity: complexity,
depth: depth,
focus_areas: focusAreas,
seed_analysis: seedAnalysis,
has_codebase: hasCodebase,
phasesCompleted: [
{
phase: 1,
name: "discovery",
output_file: "spec-config.json",
completed_at: new Date().toISOString()
}
]
};
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
```
## Output
- **File**: `spec-config.json`
- **File**: `discovery-context.json` (optional, if codebase detected)
- **Format**: JSON
## Quality Checklist
- [ ] Session ID matches `SPEC-{slug}-{date}` format
- [ ] Problem statement exists and is >= 20 characters
- [ ] Target users identified (>= 1)
- [ ] 3-5 exploration dimensions generated
- [ ] spec-config.json written with all required fields
- [ ] Output directory created
## Next Phase
Proceed to [Phase 2: Product Brief](02-product-brief.md) with the generated spec-config.json.

View File

@@ -0,0 +1,226 @@
# Phase 2: Product Brief
Generate a product brief through multi-perspective CLI analysis, establishing "what" and "why".
## Objective
- Read Phase 1 outputs (spec-config.json, discovery-context.json)
- Launch 3 parallel CLI analyses from product, technical, and user perspectives
- Synthesize convergent themes and conflicting views
- Optionally refine with user input
- Generate product-brief.md using template
## Input
- Dependency: `{workDir}/spec-config.json`
- Optional: `{workDir}/discovery-context.json`
- Config: `{workDir}/spec-config.json`
- Template: `templates/product-brief.md`
## Execution Steps
### Step 1: Load Phase 1 Context
```javascript
const specConfig = JSON.parse(Read(`${workDir}/spec-config.json`));
const { seed_analysis, seed_input, has_codebase, depth, focus_areas } = specConfig;
let discoveryContext = null;
if (has_codebase) {
try {
discoveryContext = JSON.parse(Read(`${workDir}/discovery-context.json`));
} catch (e) {
// No discovery context available, proceed without
}
}
// Build shared context string for CLI prompts
const sharedContext = `
SEED: ${seed_input}
PROBLEM: ${seed_analysis.problem_statement}
TARGET USERS: ${seed_analysis.target_users.join(', ')}
DOMAIN: ${seed_analysis.domain}
CONSTRAINTS: ${seed_analysis.constraints.join(', ')}
FOCUS AREAS: ${focus_areas.join(', ')}
${discoveryContext ? `
CODEBASE CONTEXT:
- Existing patterns: ${discoveryContext.existing_patterns?.slice(0,5).join(', ') || 'none'}
- Architecture constraints: ${discoveryContext.architecture_constraints?.slice(0,3).join(', ') || 'none'}
- Tech stack: ${JSON.stringify(discoveryContext.tech_stack || {})}
` : ''}`;
```
### Step 2: Multi-CLI Parallel Analysis (3 perspectives)
Launch 3 CLI calls in parallel:
**Product Perspective (Gemini)**:
```javascript
Bash({
command: `ccw cli -p "PURPOSE: Product analysis for specification - identify market fit, user value, and success criteria.
Success: Clear vision, measurable goals, competitive positioning.
${sharedContext}
TASK:
- Define product vision (1-3 sentences, aspirational)
- Analyze market/competitive landscape
- Define 3-5 measurable success metrics
- Identify scope boundaries (in-scope vs out-of-scope)
- Assess user value proposition
- List assumptions that need validation
MODE: analysis
EXPECTED: Structured product analysis with: vision, goals with metrics, scope, competitive positioning, assumptions
CONSTRAINTS: Focus on 'what' and 'why', not 'how'
" --tool gemini --mode analysis`,
run_in_background: true
});
```
**Technical Perspective (Codex)**:
```javascript
Bash({
command: `ccw cli -p "PURPOSE: Technical feasibility analysis for specification - assess implementation viability and constraints.
Success: Clear technical constraints, integration complexity, technology recommendations.
${sharedContext}
TASK:
- Assess technical feasibility of the core concept
- Identify technical constraints and blockers
- Evaluate integration complexity with existing systems
- Recommend technology approach (high-level)
- Identify technical risks and dependencies
- Estimate complexity: simple/moderate/complex
MODE: analysis
EXPECTED: Technical analysis with: feasibility assessment, constraints, integration complexity, tech recommendations, risks
CONSTRAINTS: Focus on feasibility and constraints, not detailed architecture
" --tool codex --mode analysis`,
run_in_background: true
});
```
**User Perspective (Claude)**:
```javascript
Bash({
command: `ccw cli -p "PURPOSE: User experience analysis for specification - understand user journeys, pain points, and UX considerations.
Success: Clear user personas, journey maps, UX requirements.
${sharedContext}
TASK:
- Elaborate user personas with goals and frustrations
- Map primary user journey (happy path)
- Identify key pain points in current experience
- Define UX success criteria
- List accessibility and usability considerations
- Suggest interaction patterns
MODE: analysis
EXPECTED: User analysis with: personas, journey map, pain points, UX criteria, interaction recommendations
CONSTRAINTS: Focus on user needs and experience, not implementation
" --tool claude --mode analysis`,
run_in_background: true
});
// STOP: Wait for all 3 CLI results before continuing
```
### Step 3: Synthesize Perspectives
```javascript
// After receiving all 3 CLI results:
// Extract convergent themes (all agree)
// Identify conflicting views (need resolution)
// Note unique contributions from each perspective
const synthesis = {
convergent_themes: [], // themes all 3 perspectives agree on
conflicts: [], // areas where perspectives differ
product_insights: [], // unique from product perspective
technical_insights: [], // unique from technical perspective
user_insights: [] // unique from user perspective
};
```
### Step 4: Interactive Refinement (Optional)
```javascript
if (!autoMode) {
// Present synthesis summary to user
// AskUserQuestion with:
// - Confirm vision statement
// - Resolve any conflicts between perspectives
// - Adjust scope if needed
AskUserQuestion({
questions: [
{
question: "Review the synthesized product brief. Any adjustments needed?",
header: "Review",
multiSelect: false,
options: [
{ label: "Looks good", description: "Proceed to PRD generation" },
{ label: "Adjust scope", description: "Narrow or expand the scope" },
{ label: "Revise vision", description: "Refine the vision statement" }
]
}
]
});
}
```
### Step 5: Generate product-brief.md
```javascript
// Read template
const template = Read('templates/product-brief.md');
// Fill template with synthesized content
// Apply document-standards.md formatting rules
// Write with YAML frontmatter
const frontmatter = `---
session_id: ${specConfig.session_id}
phase: 2
document_type: product-brief
status: ${autoMode ? 'complete' : 'draft'}
generated_at: ${new Date().toISOString()}
stepsCompleted: ["load-context", "multi-cli-analysis", "synthesis", "generation"]
version: 1
dependencies:
- spec-config.json
---`;
// Combine frontmatter + filled template content
Write(`${workDir}/product-brief.md`, `${frontmatter}\n\n${filledContent}`);
// Update spec-config.json
specConfig.phasesCompleted.push({
phase: 2,
name: "product-brief",
output_file: "product-brief.md",
completed_at: new Date().toISOString()
});
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
```
## Output
- **File**: `product-brief.md`
- **Format**: Markdown with YAML frontmatter
## Quality Checklist
- [ ] Vision statement: clear, 1-3 sentences
- [ ] Problem statement: specific and measurable
- [ ] Target users: >= 1 persona with needs
- [ ] Goals: >= 2 with measurable metrics
- [ ] Scope: in-scope and out-of-scope defined
- [ ] Multi-perspective synthesis included
- [ ] YAML frontmatter valid
## Next Phase
Proceed to [Phase 3: Requirements](03-requirements.md) with the generated product-brief.md.

View File

@@ -0,0 +1,192 @@
# Document Standards
Defines format conventions, YAML frontmatter schema, naming rules, and content structure for all spec-generator outputs.
## When to Use
| Phase | Usage | Section |
|-------|-------|---------|
| All Phases | Frontmatter format | YAML Frontmatter Schema |
| All Phases | File naming | Naming Conventions |
| Phase 2-5 | Document structure | Content Structure |
| Phase 6 | Validation reference | All sections |
---
## YAML Frontmatter Schema
Every generated document MUST begin with YAML frontmatter:
```yaml
---
session_id: SPEC-{slug}-{YYYY-MM-DD}
phase: {1-6}
document_type: {product-brief|requirements|architecture|epics|readiness-report|spec-summary}
status: draft|review|complete
generated_at: {ISO8601 timestamp}
stepsCompleted: []
version: 1
dependencies:
- {list of input documents used}
---
```
### Field Definitions
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `session_id` | string | Yes | Session identifier matching spec-config.json |
| `phase` | number | Yes | Phase number that generated this document (1-6) |
| `document_type` | string | Yes | One of: product-brief, requirements, architecture, epics, readiness-report, spec-summary |
| `status` | enum | Yes | draft (initial), review (user reviewed), complete (finalized) |
| `generated_at` | string | Yes | ISO8601 timestamp of generation |
| `stepsCompleted` | array | Yes | List of step IDs completed during generation |
| `version` | number | Yes | Document version, incremented on re-generation |
| `dependencies` | array | No | List of input files this document depends on |
### Status Transitions
```
draft -> review -> complete
| ^
+-------------------+ (direct promotion in auto mode)
```
- **draft**: Initial generation, not yet user-reviewed
- **review**: User has reviewed and provided feedback
- **complete**: Finalized, ready for downstream consumption
In auto mode (`-y`), documents are promoted directly from `draft` to `complete`.
---
## Naming Conventions
### Session ID Format
```
SPEC-{slug}-{YYYY-MM-DD}
```
- **slug**: Lowercase, alphanumeric + Chinese characters, hyphens as separators, max 40 chars
- **date**: UTC+8 date in YYYY-MM-DD format
Examples:
- `SPEC-task-management-system-2026-02-11`
- `SPEC-user-auth-oauth-2026-02-11`
### Output Files
| File | Phase | Description |
|------|-------|-------------|
| `spec-config.json` | 1 | Session configuration and state |
| `discovery-context.json` | 1 | Codebase exploration results (optional) |
| `product-brief.md` | 2 | Product brief document |
| `requirements.md` | 3 | PRD document |
| `architecture.md` | 4 | Architecture decisions document |
| `epics.md` | 5 | Epic/Story breakdown document |
| `readiness-report.md` | 6 | Quality validation report |
| `spec-summary.md` | 6 | One-page executive summary |
### Output Directory
```
.workflow/.spec/{session-id}/
```
---
## Content Structure
### Heading Hierarchy
- `#` (H1): Document title only (one per document)
- `##` (H2): Major sections
- `###` (H3): Subsections
- `####` (H4): Detail items (use sparingly)
Maximum depth: 4 levels. Prefer flat structures.
### Section Ordering
Every document follows this general pattern:
1. **YAML Frontmatter** (mandatory)
2. **Title** (H1)
3. **Executive Summary** (2-3 sentences)
4. **Core Content Sections** (H2, document-specific)
5. **Open Questions / Risks** (if applicable)
6. **References / Traceability** (links to upstream/downstream docs)
### Formatting Rules
| Element | Format | Example |
|---------|--------|---------|
| Requirements | `REQ-{NNN}` prefix | REQ-001: User login |
| Acceptance criteria | Checkbox list | `- [ ] User can log in with email` |
| Architecture decisions | `ADR-{NNN}` prefix | ADR-001: Use PostgreSQL |
| Epics | `EPIC-{NNN}` prefix | EPIC-001: Authentication |
| Stories | `STORY-{EPIC}-{NNN}` prefix | STORY-001-001: Login form |
| Priority tags | MoSCoW labels | `[Must]`, `[Should]`, `[Could]`, `[Won't]` |
| Mermaid diagrams | Fenced code blocks | ````mermaid ... ``` `` |
| Code examples | Language-tagged blocks | ````typescript ... ``` `` |
### Cross-Reference Format
Use relative references between documents:
```markdown
See [Product Brief](product-brief.md#section-name) for details.
Derived from [REQ-001](requirements.md#req-001).
```
### Language
- Document body: Follow user's input language (Chinese or English)
- Technical identifiers: Always English (REQ-001, ADR-001, EPIC-001)
- YAML frontmatter keys: Always English
---
## spec-config.json Schema
```json
{
"session_id": "string (required)",
"seed_input": "string (required) - original user input",
"input_type": "text|file (required)",
"timestamp": "ISO8601 (required)",
"mode": "interactive|auto (required)",
"complexity": "simple|moderate|complex (required)",
"depth": "light|standard|comprehensive (required)",
"focus_areas": ["string array"],
"seed_analysis": {
"problem_statement": "string",
"target_users": ["string array"],
"domain": "string",
"constraints": ["string array"],
"dimensions": ["string array - 3-5 exploration dimensions"]
},
"has_codebase": "boolean",
"phasesCompleted": [
{
"phase": "number (1-6)",
"name": "string (phase name)",
"output_file": "string (primary output file)",
"completed_at": "ISO8601"
}
]
}
```
---
## Validation Checklist
- [ ] Every document starts with valid YAML frontmatter
- [ ] `session_id` matches across all documents in a session
- [ ] `status` field reflects current document state
- [ ] All cross-references resolve to valid targets
- [ ] Heading hierarchy is correct (no skipped levels)
- [ ] Technical identifiers use correct prefixes
- [ ] Output files are in the correct directory

View File

@@ -0,0 +1,207 @@
# Quality Gates
Per-phase quality gate criteria and scoring dimensions for spec-generator outputs.
## When to Use
| Phase | Usage | Section |
|-------|-------|---------|
| Phase 2-5 | Post-generation self-check | Per-Phase Gates |
| Phase 6 | Cross-document validation | Cross-Document Validation |
| Phase 6 | Final scoring | Scoring Dimensions |
---
## Quality Thresholds
| Gate | Score | Action |
|------|-------|--------|
| **Pass** | >= 80% | Continue to next phase |
| **Review** | 60-79% | Log warnings, continue with caveats |
| **Fail** | < 60% | Must address issues before continuing |
In auto mode (`-y`), Review-level issues are logged but do not block progress.
---
## Scoring Dimensions
### 1. Completeness (25%)
All required sections present with substantive content.
| Score | Criteria |
|-------|----------|
| 100% | All template sections filled with detailed content |
| 75% | All sections present, some lack detail |
| 50% | Major sections present but minor sections missing |
| 25% | Multiple major sections missing or empty |
| 0% | Document is a skeleton only |
### 2. Consistency (25%)
Terminology, formatting, and references are uniform across documents.
| Score | Criteria |
|-------|----------|
| 100% | All terms consistent, all references valid, formatting uniform |
| 75% | Minor terminology variations, all references valid |
| 50% | Some inconsistent terms, 1-2 broken references |
| 25% | Frequent inconsistencies, multiple broken references |
| 0% | Documents contradict each other |
### 3. Traceability (25%)
Requirements, architecture decisions, and stories trace back to goals.
| Score | Criteria |
|-------|----------|
| 100% | Every story traces to a requirement, every requirement traces to a goal |
| 75% | Most items traceable, few orphans |
| 50% | Partial traceability, some disconnected items |
| 25% | Weak traceability, many orphan items |
| 0% | No traceability between documents |
### 4. Depth (25%)
Content provides sufficient detail for execution teams.
| Score | Criteria |
|-------|----------|
| 100% | Acceptance criteria specific and testable, architecture decisions justified, stories estimable |
| 75% | Most items detailed enough, few vague areas |
| 50% | Mix of detailed and vague content |
| 25% | Mostly high-level, lacking actionable detail |
| 0% | Too abstract for execution |
---
## Per-Phase Quality Gates
### Phase 1: Discovery
| Check | Criteria | Severity |
|-------|----------|----------|
| Session ID valid | Matches `SPEC-{slug}-{date}` format | Error |
| Problem statement exists | Non-empty, >= 20 characters | Error |
| Target users identified | >= 1 user group | Error |
| Dimensions generated | 3-5 exploration dimensions | Warning |
| Constraints listed | >= 0 (can be empty with justification) | Info |
### Phase 2: Product Brief
| Check | Criteria | Severity |
|-------|----------|----------|
| Vision statement | Clear, 1-3 sentences | Error |
| Problem statement | Specific and measurable | Error |
| Target users | >= 1 persona with needs described | Error |
| Goals defined | >= 2 measurable goals | Error |
| Success metrics | >= 2 quantifiable metrics | Warning |
| Scope boundaries | In-scope and out-of-scope listed | Warning |
| Multi-perspective | >= 2 CLI perspectives synthesized | Info |
### Phase 3: Requirements (PRD)
| Check | Criteria | Severity |
|-------|----------|----------|
| Functional requirements | >= 3 with REQ-NNN IDs | Error |
| Acceptance criteria | Every requirement has >= 1 criterion | Error |
| MoSCoW priority | Every requirement tagged | Error |
| Non-functional requirements | >= 1 (performance, security, etc.) | Warning |
| User stories | >= 1 per Must-have requirement | Warning |
| Traceability | Requirements trace to product brief goals | Warning |
### Phase 4: Architecture
| Check | Criteria | Severity |
|-------|----------|----------|
| Component diagram | Present (Mermaid or ASCII) | Error |
| Tech stack specified | Languages, frameworks, key libraries | Error |
| ADR present | >= 1 Architecture Decision Record | Error |
| ADR has alternatives | Each ADR lists >= 2 options considered | Warning |
| Integration points | External systems/APIs identified | Warning |
| Data model | Key entities and relationships described | Warning |
| Codebase mapping | Mapped to existing code (if has_codebase) | Info |
### Phase 5: Epics & Stories
| Check | Criteria | Severity |
|-------|----------|----------|
| Epics defined | 3-7 epics with EPIC-NNN IDs | Error |
| MVP subset | >= 1 epic tagged as MVP | Error |
| Stories per epic | 2-5 stories per epic | Error |
| Story format | "As a...I want...So that..." pattern | Warning |
| Dependency map | Cross-epic dependencies documented | Warning |
| Estimation hints | Relative sizing (S/M/L/XL) per story | Info |
| Traceability | Stories trace to requirements | Warning |
### Phase 6: Readiness Check
| Check | Criteria | Severity |
|-------|----------|----------|
| All documents exist | product-brief, requirements, architecture, epics | Error |
| Frontmatter valid | All YAML frontmatter parseable and correct | Error |
| Cross-references valid | All document links resolve | Error |
| Overall score >= 60% | Weighted average across 4 dimensions | Error |
| No unresolved Errors | All Error-severity issues addressed | Error |
| Summary generated | spec-summary.md created | Warning |
---
## Cross-Document Validation
Checks performed during Phase 6 across all documents:
### Completeness Matrix
```
Product Brief goals -> Requirements (each goal has >= 1 requirement)
Requirements -> Architecture (each Must requirement has design coverage)
Requirements -> Epics (each Must requirement appears in >= 1 story)
Architecture ADRs -> Epics (tech choices reflected in implementation stories)
```
### Consistency Checks
| Check | Documents | Rule |
|-------|-----------|------|
| Terminology | All | Same term used consistently (no synonyms for same concept) |
| User personas | Brief + PRD + Epics | Same user names/roles throughout |
| Scope | Brief + PRD | PRD scope does not exceed brief scope |
| Tech stack | Architecture + Epics | Stories reference correct technologies |
### Traceability Matrix Format
```markdown
| Goal | Requirements | Architecture | Epics |
|------|-------------|--------------|-------|
| G-001: ... | REQ-001, REQ-002 | ADR-001 | EPIC-001 |
| G-002: ... | REQ-003 | ADR-002 | EPIC-002, EPIC-003 |
```
---
## Issue Classification
### Error (Must Fix)
- Missing required document or section
- Broken cross-references
- Contradictory information between documents
- Empty acceptance criteria on Must-have requirements
- No MVP subset defined in epics
### Warning (Should Fix)
- Vague acceptance criteria
- Missing non-functional requirements
- No success metrics defined
- Incomplete traceability
- Missing architecture review notes
### Info (Nice to Have)
- Could add more detailed personas
- Consider additional ADR alternatives
- Story estimation hints missing
- Mermaid diagrams could be more detailed

View File

@@ -0,0 +1,133 @@
# Product Brief Template
Template for generating product brief documents in Phase 2.
## Usage Context
| Phase | Usage |
|-------|-------|
| Phase 2 (Product Brief) | Generate product-brief.md from multi-CLI analysis |
| Output Location | `{workDir}/product-brief.md` |
---
## Template
```markdown
---
session_id: {session_id}
phase: 2
document_type: product-brief
status: draft
generated_at: {timestamp}
stepsCompleted: []
version: 1
dependencies:
- spec-config.json
---
# Product Brief: {product_name}
{executive_summary - 2-3 sentences capturing the essence of the product/feature}
## Vision
{vision_statement - clear, aspirational 1-3 sentence statement of what success looks like}
## Problem Statement
### Current Situation
{description of the current state and pain points}
### Impact
{quantified impact of the problem - who is affected, how much, how often}
## Target Users
{for each user persona:}
### {Persona Name}
- **Role**: {user's role/context}
- **Needs**: {primary needs related to this product}
- **Pain Points**: {current frustrations}
- **Success Criteria**: {what success looks like for this user}
## Goals & Success Metrics
| Goal ID | Goal | Success Metric | Target |
|---------|------|----------------|--------|
| G-001 | {goal description} | {measurable metric} | {specific target} |
| G-002 | {goal description} | {measurable metric} | {specific target} |
## Scope
### In Scope
- {feature/capability 1}
- {feature/capability 2}
- {feature/capability 3}
### Out of Scope
- {explicitly excluded item 1}
- {explicitly excluded item 2}
### Assumptions
- {key assumption 1}
- {key assumption 2}
## Competitive Landscape
| Aspect | Current State | Proposed Solution | Advantage |
|--------|--------------|-------------------|-----------|
| {aspect} | {how it's done now} | {our approach} | {differentiator} |
## Constraints & Dependencies
### Technical Constraints
- {constraint 1}
- {constraint 2}
### Business Constraints
- {constraint 1}
### Dependencies
- {external dependency 1}
- {external dependency 2}
## Multi-Perspective Synthesis
### Product Perspective
{summary of product/market analysis findings}
### Technical Perspective
{summary of technical feasibility and constraints}
### User Perspective
{summary of user journey and UX considerations}
### Convergent Themes
{themes where all perspectives agree}
### Conflicting Views
{areas where perspectives differ, with notes on resolution approach}
## Open Questions
- [ ] {unresolved question 1}
- [ ] {unresolved question 2}
## References
- Derived from: [spec-config.json](spec-config.json)
- Next: [Requirements PRD](requirements.md)
```
## Variable Descriptions
| Variable | Source | Description |
|----------|--------|-------------|
| `{session_id}` | spec-config.json | Session identifier |
| `{timestamp}` | Runtime | ISO8601 generation timestamp |
| `{product_name}` | Seed analysis | Product/feature name |
| `{executive_summary}` | CLI synthesis | 2-3 sentence summary |
| `{vision_statement}` | CLI product perspective | Aspirational vision |
| All `{...}` fields | CLI analysis outputs | Filled from multi-perspective analysis |