feat: Implement DeepWiki documentation generation tools

- Added `__init__.py` in `codexlens/tools` for documentation generation.
- Created `deepwiki_generator.py` to handle symbol extraction and markdown generation.
- Introduced `MockMarkdownGenerator` for testing purposes.
- Implemented `DeepWikiGenerator` class for managing documentation generation and file processing.
- Added unit tests for `DeepWikiStore` to ensure proper functionality and error handling.
- Created tests for DeepWiki TypeScript types matching.
This commit is contained in:
catlog22
2026-03-05 18:30:56 +08:00
parent 0bfae3fd1a
commit fb4f6e718e
62 changed files with 7500 additions and 68 deletions

View File

@@ -17,33 +17,42 @@ Structured specification document generator producing a complete document chain
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
| |- 01-discovery.md # Seed analysis + codebase exploration + spec type selection
| |- 01-5-requirement-clarification.md # Interactive requirement expansion
| |- 02-product-brief.md # Multi-CLI product brief + glossary generation
| |- 03-requirements.md # PRD with MoSCoW priorities + RFC 2119 constraints
| |- 04-architecture.md # Architecture + state machine + config model + observability
| |- 05-epics-stories.md # Epic/Story decomposition
| |- 06-readiness-check.md # Quality validation + handoff
| |- 06-readiness-check.md # Quality validation + handoff + iterate option
| |- 06-5-auto-fix.md # Auto-fix loop for readiness issues (max 2 iterations)
|- specs/
| |- document-standards.md # Format, frontmatter, naming rules
| |- quality-gates.md # Per-phase quality criteria
| |- quality-gates.md # Per-phase quality criteria + iteration tracking
| |- glossary-template.json # Terminology glossary schema
|- templates/
| |- product-brief.md # Product brief template
| |- product-brief.md # Product brief template (+ Concepts & Non-Goals)
| |- requirements-prd.md # PRD template
| |- architecture-doc.md # Architecture document template
| |- epics-template.md # Epic/Story template
| |- architecture-doc.md # Architecture template (+ state machine, config, observability)
| |- epics-template.md # Epic/Story template (+ versioning)
| |- profiles/ # Spec type specialization profiles
| |- service-profile.md # Service spec: lifecycle, observability, trust
| |- api-profile.md # API spec: endpoints, auth, rate limiting
| |- library-profile.md # Library spec: public API, examples, compatibility
|- 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) |
| Phase | Name | Output | CLI Tools | Key Features |
|-------|------|--------|-----------|-------------|
| 1 | Discovery | spec-config.json | Gemini (analysis) | Spec type selection |
| 1.5 | Req Expansion | refined-requirements.json | Gemini (analysis) | Multi-round interactive |
| 2 | Product Brief | product-brief.md, glossary.json | Gemini + Codex + Claude (parallel) | Terminology glossary |
| 3 | Requirements | requirements/ | Gemini (analysis) | RFC 2119, data model |
| 4 | Architecture | architecture/ | Gemini + Codex (sequential) | State machine, config, observability |
| 5 | Epics & Stories | epics/ | Gemini (analysis) | Glossary consistency |
| 6 | Readiness Check | readiness-report.md, spec-summary.md | Gemini (validation) | Terminology + scope validation |
| 6.5 | Auto-Fix | Updated phase docs | Gemini (analysis) | Max 2 iterations |
## Runtime Output
@@ -51,12 +60,21 @@ spec-generator/
.workflow/.spec/SPEC-{slug}-{YYYY-MM-DD}/
|- spec-config.json # Session state
|- discovery-context.json # Codebase context (optional)
|- refined-requirements.json # Phase 1.5 (requirement expansion)
|- glossary.json # Phase 2 (terminology)
|- product-brief.md # Phase 2
|- requirements.md # Phase 3
|- architecture.md # Phase 4
|- epics.md # Phase 5
|- requirements/ # Phase 3 (directory)
| |- _index.md
| |- REQ-*.md
| └── NFR-*.md
|- architecture/ # Phase 4 (directory)
| |- _index.md
| └── ADR-*.md
|- epics/ # Phase 5 (directory)
| |- _index.md
| └── EPIC-*.md
|- readiness-report.md # Phase 6
|- spec-summary.md # Phase 6
└── spec-summary.md # Phase 6
```
## Flags
@@ -64,6 +82,9 @@ spec-generator/
- `-y|--yes`: Auto mode - skip all interactive confirmations
- `-c|--continue`: Resume from last completed phase
Spec type is selected interactively in Phase 1 (defaults to `service` in auto mode)
Available types: `service`, `api`, `library`, `platform`
## Handoff
After Phase 6, choose execution path:
@@ -79,3 +100,6 @@ After Phase 6, choose execution path:
- **Template-driven**: Consistent format via templates + frontmatter
- **Resumable**: spec-config.json tracks completed phases
- **Pure documentation**: No code generation - clean handoff to execution workflows
- **Type-specialized**: Profiles adapt templates to service/api/library/platform requirements
- **Iterative quality**: Phase 6.5 auto-fix repairs issues, max 2 iterations before handoff
- **Terminology-first**: glossary.json ensures consistent terminology across all documents

View File

@@ -14,20 +14,26 @@ Structured specification document generator producing a complete specification p
Phase 0: Specification Study (Read specs/ + templates/ - mandatory prerequisite)
|
Phase 1: Discovery -> spec-config.json + discovery-context.json
|
| (includes spec_type selection)
Phase 1.5: Req Expansion -> refined-requirements.json (interactive discussion + CLI gap analysis)
| (-y auto mode: auto-expansion, skip interaction)
Phase 2: Product Brief -> product-brief.md (multi-CLI parallel analysis)
Phase 2: Product Brief -> product-brief.md + glossary.json (multi-CLI parallel analysis)
|
Phase 3: Requirements (PRD) -> requirements/ (_index.md + REQ-*.md + NFR-*.md)
|
| (RFC 2119 keywords, data model definitions)
Phase 4: Architecture -> architecture/ (_index.md + ADR-*.md, multi-CLI review)
|
| (state machine, config model, error handling, observability)
Phase 5: Epics & Stories -> epics/ (_index.md + EPIC-*.md)
|
Phase 6: Readiness Check -> readiness-report.md + spec-summary.md
|
Handoff to execution workflows
| (terminology + scope consistency validation)
├── Pass (>=80%): Handoff to execution workflows
├── Review (60-79%): Handoff with caveats
└── Fail (<60%): Phase 6.5 Auto-Fix (max 2 iterations)
|
Phase 6.5: Auto-Fix -> Updated Phase 2-5 documents
|
└── Re-run Phase 6 validation
```
## Key Design Principles
@@ -38,6 +44,9 @@ Phase 6: Readiness Check -> readiness-report.md + spec-summary.md
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
7. **Spec Type Specialization**: Templates adapt to spec type (service/api/library/platform) via profiles for domain-specific depth
8. **Iterative Quality**: Phase 6.5 auto-fix loop repairs issues found in readiness check (max 2 iterations)
9. **Terminology Consistency**: glossary.json generated in Phase 2, injected into all subsequent phases
---
@@ -78,6 +87,7 @@ Phase 1: Discovery & Seed Analysis
|- Parse input (text or file reference)
|- Gemini CLI seed analysis (problem, users, domain, dimensions)
|- Codebase exploration (conditional, if project detected)
|- Spec type selection: service|api|library|platform (interactive, -y defaults to service)
|- User confirmation (interactive, -y skips)
|- Output: spec-config.json, discovery-context.json (optional)
@@ -95,13 +105,17 @@ 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
|- Generate glossary.json (terminology from product brief + CLI analysis)
|- Interactive refinement (-y skips)
|- Output: product-brief.md (from template)
|- Output: product-brief.md (from template), glossary.json
Phase 3: Requirements / PRD
|- Ref: phases/03-requirements.md
|- Gemini CLI: expand goals into functional + non-functional requirements
|- Generate acceptance criteria per requirement
|- RFC 2119 behavioral constraints (MUST/SHOULD/MAY)
|- Core entity data model definitions
|- Glossary injection for terminology consistency
|- User priority sorting: MoSCoW (interactive, -y auto-assigns)
|- Output: requirements/ directory (_index.md + REQ-*.md + NFR-*.md, from template)
@@ -109,6 +123,12 @@ Phase 4: Architecture
|- Ref: phases/04-architecture.md
|- Gemini CLI: core components, tech stack, ADRs
|- Codebase integration mapping (conditional)
|- State machine generation (ASCII diagrams for lifecycle entities)
|- Configuration model definition (fields, types, defaults, constraints)
|- Error handling strategy (per-component classification + recovery)
|- Observability specification (metrics, logs, health checks)
|- Spec type profile injection (templates/profiles/{type}-profile.md)
|- Glossary injection for terminology consistency
|- Codex CLI: architecture challenge + review
|- Interactive ADR decisions (-y auto-accepts)
|- Output: architecture/ directory (_index.md + ADR-*.md, from template)
@@ -125,9 +145,20 @@ Phase 6: Readiness Check
|- Ref: phases/06-readiness-check.md
|- Cross-document validation (completeness, consistency, traceability)
|- Quality scoring per dimension
|- Terminology consistency validation (glossary compliance)
|- Scope containment validation (PRD <= Brief scope)
|- Output: readiness-report.md, spec-summary.md
|- Handoff options: lite-plan, req-plan, plan, issue:new, export only, iterate
Phase 6.5: Auto-Fix (conditional, triggered when Phase 6 score < 60%)
|- Ref: phases/06-5-auto-fix.md
|- Parse readiness-report.md for Error/Warning items
|- Group issues by originating Phase (2-5)
|- Re-generate affected sections via CLI with error context
|- Re-run Phase 6 validation
|- Max 2 iterations, then force handoff
|- Output: Updated Phase 2-5 documents
Complete: Full specification package ready for execution
Phase 6 → Handoff Bridge (conditional, based on user selection):
@@ -161,6 +192,7 @@ Bash(`mkdir -p "${workDir}"`);
├── spec-config.json # Session configuration + phase state
├── discovery-context.json # Codebase exploration results (optional)
├── refined-requirements.json # Phase 1.5: Confirmed requirements after discussion
├── glossary.json # Phase 2: Terminology glossary for cross-doc consistency
├── product-brief.md # Phase 2: Product brief
├── requirements/ # Phase 3: Detailed PRD (directory)
│ ├── _index.md # Summary, MoSCoW table, traceability, links
@@ -189,6 +221,9 @@ Bash(`mkdir -p "${workDir}"`);
"complexity": "moderate",
"depth": "standard",
"focus_areas": [],
"spec_type": "service",
"iteration_count": 0,
"iteration_history": [],
"seed_analysis": {
"problem_statement": "...",
"target_users": [],
@@ -217,6 +252,9 @@ Bash(`mkdir -p "${workDir}"`);
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
8. **Inject Glossary**: From Phase 3 onward, inject glossary.json terms into every CLI prompt
9. **Load Profile**: Read templates/profiles/{spec_type}-profile.md and inject requirements into Phase 2-5 prompts
10. **Iterate on Failure**: When Phase 6 score < 60%, auto-trigger Phase 6.5 (max 2 iterations)
## Reference Documents by Phase
@@ -224,6 +262,7 @@ Bash(`mkdir -p "${workDir}"`);
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/01-discovery.md](phases/01-discovery.md) | Seed analysis and session setup | Phase start |
| [templates/profiles/](templates/profiles/) | Spec type profiles | Spec type selection |
| [specs/document-standards.md](specs/document-standards.md) | Frontmatter format for spec-config.json | Config generation |
### Phase 1.5: Requirement Expansion & Clarification
@@ -237,6 +276,7 @@ Bash(`mkdir -p "${workDir}"`);
|----------|---------|-------------|
| [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 |
| [specs/glossary-template.json](specs/glossary-template.json) | Glossary schema | Glossary generation |
### Phase 3: Requirements
| Document | Purpose | When to Use |
@@ -262,6 +302,12 @@ Bash(`mkdir -p "${workDir}"`);
| [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 |
### Phase 6.5: Auto-Fix
| Document | Purpose | When to Use |
|----------|---------|-------------|
| [phases/06-5-auto-fix.md](phases/06-5-auto-fix.md) | Auto-fix workflow for readiness issues | When Phase 6 score < 60% |
| [specs/quality-gates.md](specs/quality-gates.md) | Iteration exit criteria | Validation |
### Debugging & Troubleshooting
| Issue | Solution Document |
|-------|-------------------|
@@ -284,6 +330,8 @@ Bash(`mkdir -p "${workDir}"`);
| 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 |
| Phase 6.5 | Auto-fix CLI fails | No | Log failure, proceed to handoff with Review status |
| Phase 6.5 | Max iterations reached | No | Force handoff, report remaining issues |
### CLI Fallback Chain

View File

@@ -185,6 +185,17 @@ if (!autoMode) {
header: "Focus",
multiSelect: true,
options: seedAnalysis.dimensions.map(d => ({ label: d, description: `Explore ${d} in depth` }))
},
{
question: "What type of specification is this?",
header: "Spec Type",
multiSelect: false,
options: [
{ label: "Service (Recommended)", description: "Long-running service with lifecycle, state machine, observability" },
{ label: "API", description: "REST/GraphQL API with endpoints, auth, rate limiting" },
{ label: "Library/SDK", description: "Reusable package with public API surface, examples" },
{ label: "Platform", description: "Multi-component system, uses Service profile" }
]
}
]
});
@@ -192,6 +203,7 @@ if (!autoMode) {
// Auto mode defaults
depth = "standard";
focusAreas = seedAnalysis.dimensions;
specType = "service"; // default for auto mode
}
```
@@ -209,6 +221,9 @@ const specConfig = {
focus_areas: focusAreas,
seed_analysis: seedAnalysis,
has_codebase: hasCodebase,
spec_type: specType, // "service" | "api" | "library" | "platform"
iteration_count: 0,
iteration_history: [],
phasesCompleted: [
{
phase: 1,

View File

@@ -227,6 +227,33 @@ specConfig.phasesCompleted.push({
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
```
### Step 5.5: Generate glossary.json
```javascript
// Extract terminology from product brief and CLI analysis
// Generate structured glossary for cross-document consistency
const glossary = {
session_id: specConfig.session_id,
terms: [
// Extract from product brief content:
// - Key domain nouns from problem statement
// - User persona names
// - Technical terms from multi-perspective synthesis
// Each term should have:
// { term: "...", definition: "...", aliases: [], first_defined_in: "product-brief.md", category: "core|technical|business" }
]
};
Write(`${workDir}/glossary.json`, JSON.stringify(glossary, null, 2));
```
**Glossary Injection**: In all subsequent phase prompts, inject the following into the CONTEXT section:
```
TERMINOLOGY GLOSSARY (use these terms consistently):
${JSON.stringify(glossary.terms, null, 2)}
```
## Output
- **File**: `product-brief.md`

View File

@@ -60,6 +60,11 @@ TASK:
- Should: Important but has workaround
- Could: Nice-to-have, enhances experience
- Won't: Explicitly deferred
- Use RFC 2119 keywords (MUST, SHOULD, MAY, MUST NOT, SHOULD NOT) to define behavioral constraints for each requirement. Example: 'The system MUST return a 401 response within 100ms for invalid tokens.'
- For each core domain entity referenced in requirements, define its data model: fields, types, constraints, and relationships to other entities
- Maintain terminology consistency with the glossary below:
TERMINOLOGY GLOSSARY:
\${glossary ? JSON.stringify(glossary.terms, null, 2) : 'N/A - generate terms inline'}
MODE: analysis
EXPECTED: Structured requirements with: ID, title, description, user story, acceptance criteria, priority, traceability to goals

View File

@@ -33,6 +33,19 @@ if (specConfig.has_codebase) {
discoveryContext = JSON.parse(Read(`${workDir}/discovery-context.json`));
} catch (e) { /* no context */ }
}
// Load glossary for terminology consistency
let glossary = null;
try {
glossary = JSON.parse(Read(`${workDir}/glossary.json`));
} catch (e) { /* proceed without */ }
// Load spec type profile for specialized sections
const specType = specConfig.spec_type || 'service';
let profile = null;
try {
profile = Read(`templates/profiles/${specType}-profile.md`);
} catch (e) { /* use base template only */ }
```
### Step 2: Architecture Analysis via Gemini CLI
@@ -66,6 +79,28 @@ TASK:
- Identify security architecture: auth, authorization, data protection
- List API endpoints (high-level)
${discoveryContext ? '- Map new components to existing codebase modules' : ''}
- For each core entity with a lifecycle, create an ASCII state machine diagram showing:
- All states and transitions
- Trigger events for each transition
- Side effects of transitions
- Error states and recovery paths
- Define a Configuration Model: list all configurable fields with name, type, default value, constraint, and description
- Define Error Handling strategy:
- Classify errors (transient/permanent/degraded)
- Per-component error behavior using RFC 2119 keywords
- Recovery mechanisms
- Define Observability requirements:
- Key metrics (name, type: counter/gauge/histogram, labels)
- Structured log format and key log events
- Health check endpoints
\${profile ? \`
SPEC TYPE PROFILE REQUIREMENTS (\${specType}):
\${profile}
\` : ''}
\${glossary ? \`
TERMINOLOGY GLOSSARY (use consistently):
\${JSON.stringify(glossary.terms, null, 2)}
\` : ''}
MODE: analysis
EXPECTED: Complete architecture with: style justification, component diagram, tech stack table, ADRs, data model, security controls, API overview

View File

@@ -26,6 +26,11 @@ 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`);
let glossary = null;
try {
glossary = JSON.parse(Read(`${workDir}/glossary.json`));
} catch (e) { /* proceed without */ }
```
### Step 2: Epic Decomposition via Gemini CLI
@@ -69,10 +74,11 @@ TASK:
MODE: analysis
EXPECTED: Structured output with: Epic list (ID, title, priority, MVP flag), Stories per Epic (ID, user story, AC, size, trace), dependency Mermaid diagram, execution order, MVP definition
CONSTRAINTS:
CONSTRAINTS:
- Every Must-have requirement must appear in at least one Story
- Stories must be small enough to implement independently (no XL stories in MVP)
- Dependencies should be minimized across Epics
\${glossary ? \`- Maintain terminology consistency with glossary: \${glossary.terms.map(t => t.term).join(', ')}\` : ''}
" --tool gemini --mode analysis`,
run_in_background: true
});

View File

@@ -0,0 +1,144 @@
# Phase 6.5: Auto-Fix
Automatically repair specification issues identified in Phase 6 Readiness Check.
## Objective
- Parse readiness-report.md to extract Error and Warning items
- Group issues by originating Phase (2-5)
- Re-generate affected sections with error context injected into CLI prompts
- Re-run Phase 6 validation after fixes
## Input
- Dependency: `{workDir}/readiness-report.md` (Phase 6 output)
- Config: `{workDir}/spec-config.json` (with iteration_count)
- All Phase 2-5 outputs
## Execution Steps
### Step 1: Parse Readiness Report
```javascript
const readinessReport = Read(`${workDir}/readiness-report.md`);
const specConfig = JSON.parse(Read(`${workDir}/spec-config.json`));
// Load glossary for terminology consistency during fixes
let glossary = null;
try {
glossary = JSON.parse(Read(`${workDir}/glossary.json`));
} catch (e) { /* proceed without */ }
// Extract issues from readiness report
// Parse Error and Warning severity items
// Group by originating phase:
// Phase 2 issues: vision, problem statement, scope, personas
// Phase 3 issues: requirements, acceptance criteria, priority, traceability
// Phase 4 issues: architecture, ADRs, tech stack, data model, state machine
// Phase 5 issues: epics, stories, dependencies, MVP scope
const issuesByPhase = {
2: [], // product brief issues
3: [], // requirements issues
4: [], // architecture issues
5: [] // epics issues
};
// Parse structured issues from report
// Each issue: { severity: "Error"|"Warning", description: "...", location: "file:section" }
// Map phase numbers to output files
const phaseOutputFile = {
2: 'product-brief.md',
3: 'requirements/_index.md',
4: 'architecture/_index.md',
5: 'epics/_index.md'
};
```
### Step 2: Fix Affected Phases (Sequential)
For each phase with issues (in order 2 -> 3 -> 4 -> 5):
```javascript
for (const [phase, issues] of Object.entries(issuesByPhase)) {
if (issues.length === 0) continue;
const errorContext = issues.map(i => `[${i.severity}] ${i.description} (at ${i.location})`).join('\n');
// Read current phase output
const currentOutput = Read(`${workDir}/${phaseOutputFile[phase]}`);
Bash({
command: `ccw cli -p "PURPOSE: Fix specification issues identified in readiness check for Phase ${phase}.
Success: All listed issues resolved while maintaining consistency with other documents.
CURRENT DOCUMENT:
${currentOutput.slice(0, 5000)}
ISSUES TO FIX:
${errorContext}
${glossary ? `GLOSSARY (maintain consistency):
${JSON.stringify(glossary.terms, null, 2)}` : ''}
TASK:
- Address each listed issue specifically
- Maintain all existing content that is not flagged
- Ensure terminology consistency with glossary
- Preserve YAML frontmatter and cross-references
- Use RFC 2119 keywords for behavioral requirements
- Increment document version number
MODE: analysis
EXPECTED: Corrected document content addressing all listed issues
CONSTRAINTS: Minimal changes - only fix flagged issues, do not restructure unflagged sections
" --tool gemini --mode analysis`,
run_in_background: true
});
// Wait for result, apply fixes to document
// Update document version in frontmatter
}
```
### Step 3: Update State
```javascript
specConfig.phasesCompleted.push({
phase: 6.5,
name: "auto-fix",
iteration: specConfig.iteration_count,
phases_fixed: Object.keys(issuesByPhase).filter(p => issuesByPhase[p].length > 0),
completed_at: new Date().toISOString()
});
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
```
### Step 4: Re-run Phase 6 Validation
```javascript
// Re-execute Phase 6: Readiness Check
// This creates a new readiness-report.md
// If still Fail and iteration_count < 2: loop back to Step 1
// If Pass or iteration_count >= 2: proceed to handoff
```
## Output
- **Updated**: Phase 2-5 documents (only affected ones)
- **Updated**: `spec-config.json` (iteration tracking)
- **Triggers**: Phase 6 re-validation
## Quality Checklist
- [ ] All Error-severity issues addressed
- [ ] Warning-severity issues attempted (best effort)
- [ ] Document versions incremented for modified files
- [ ] Terminology consistency maintained
- [ ] Cross-references still valid after fixes
- [ ] Iteration count not exceeded (max 2)
## Next Phase
Re-run [Phase 6: Readiness Check](06-readiness-check.md) to validate fixes.

View File

@@ -70,8 +70,12 @@ Perform 4-dimension validation:
2. CONSISTENCY (25%):
- Terminology uniform across documents?
- Terminology glossary compliance: all core terms used consistently per glossary.json definitions?
- No synonym drift (e.g., "user" vs "client" vs "consumer" for same concept)?
- User personas consistent?
- Scope consistent (PRD does not exceed brief)?
- Scope containment: PRD requirements do not exceed product brief's defined scope?
- Non-Goals respected: no requirement or story contradicts explicit Non-Goals?
- Tech stack references match between architecture and epics?
- Score 0-100 with inconsistencies listed
@@ -223,6 +227,10 @@ AskUserQuestion({
{
label: "Create Issues",
description: "Generate issues for each Epic via /issue:new"
},
{
label: "Iterate & improve",
description: "Re-run failed phases based on readiness report issues (max 2 iterations)"
}
]
}
@@ -386,6 +394,29 @@ if (selection === "Create Issues") {
}
// If user selects "Other": Export only or return to specific phase
if (selection === "Iterate & improve") {
// Check iteration count
if (specConfig.iteration_count >= 2) {
// Max iterations reached, force handoff
// Present handoff options again without iterate
return;
}
// Update iteration tracking
specConfig.iteration_count = (specConfig.iteration_count || 0) + 1;
specConfig.iteration_history.push({
iteration: specConfig.iteration_count,
timestamp: new Date().toISOString(),
readiness_score: overallScore,
errors_found: errorCount,
phases_to_fix: affectedPhases
});
Write(`${workDir}/spec-config.json`, JSON.stringify(specConfig, null, 2));
// Proceed to Phase 6.5: Auto-Fix
// Read phases/06-5-auto-fix.md and execute
}
```
#### Helper Functions Reference (pseudocode)

View File

@@ -82,6 +82,7 @@ Examples:
| `spec-config.json` | 1 | Session configuration and state |
| `discovery-context.json` | 1 | Codebase exploration results (optional) |
| `refined-requirements.json` | 1.5 | Confirmed requirements after discussion |
| `glossary.json` | 2 | Terminology glossary for cross-document consistency |
| `product-brief.md` | 2 | Product brief document |
| `requirements.md` | 3 | PRD document |
| `architecture.md` | 4 | Architecture decisions document |
@@ -169,6 +170,17 @@ Derived from [REQ-001](requirements.md#req-001).
"dimensions": ["string array - 3-5 exploration dimensions"]
},
"has_codebase": "boolean",
"spec_type": "service|api|library|platform (required) - type of specification",
"iteration_count": "number (required, default 0) - number of auto-fix iterations completed",
"iteration_history": [
{
"iteration": "number",
"timestamp": "ISO8601",
"readiness_score": "number (0-100)",
"errors_found": "number",
"phases_fixed": ["number array - phase numbers that were re-generated"]
}
],
"refined_requirements_file": "string (optional) - path to refined-requirements.json",
"phasesCompleted": [
{
@@ -237,6 +249,34 @@ Derived from [REQ-001](requirements.md#req-001).
---
## glossary.json Schema
```json
{
"session_id": "string (required) - matches spec-config.json",
"generated_at": "ISO8601 (required)",
"version": "number (required, default 1) - incremented on updates",
"terms": [
{
"term": "string (required) - the canonical term",
"definition": "string (required) - concise definition",
"aliases": ["string array - acceptable alternative names"],
"first_defined_in": "string (required) - source document path",
"category": "core|technical|business (required)"
}
]
}
```
### Glossary Usage Rules
- Terms MUST be defined before first use in any document
- All documents MUST use the canonical term from glossary; aliases are for reference only
- Glossary is generated in Phase 2 and injected into all subsequent phase prompts
- Phase 6 validates glossary compliance across all documents
---
## Validation Checklist
- [ ] Every document starts with valid YAML frontmatter
@@ -246,3 +286,7 @@ Derived from [REQ-001](requirements.md#req-001).
- [ ] Heading hierarchy is correct (no skipped levels)
- [ ] Technical identifiers use correct prefixes
- [ ] Output files are in the correct directory
- [ ] `glossary.json` created with >= 5 terms
- [ ] `spec_type` field set in spec-config.json
- [ ] All documents use glossary terms consistently
- [ ] Non-Goals section present in product brief (if applicable)

View File

@@ -0,0 +1,29 @@
{
"$schema": "glossary-v1",
"description": "Template for terminology glossary used across spec-generator documents",
"session_id": "",
"generated_at": "",
"version": 1,
"terms": [
{
"term": "",
"definition": "",
"aliases": [],
"first_defined_in": "product-brief.md",
"category": "core"
}
],
"_usage_notes": {
"category_values": {
"core": "Domain-specific terms central to the product (e.g., 'Workspace', 'Session')",
"technical": "Technical terms specific to the architecture (e.g., 'gRPC', 'event bus')",
"business": "Business/process terms (e.g., 'Sprint', 'SLA', 'stakeholder')"
},
"rules": [
"Terms MUST be defined before first use in any document",
"All documents MUST use the canonical 'term' field consistently",
"Aliases are for reference only - prefer canonical term in all documents",
"Phase 6 validates glossary compliance across all documents"
]
}
}

View File

@@ -111,6 +111,9 @@ Content provides sufficient detail for execution teams.
| Success metrics | >= 2 quantifiable metrics | Warning |
| Scope boundaries | In-scope and out-of-scope listed | Warning |
| Multi-perspective | >= 2 CLI perspectives synthesized | Info |
| Terminology glossary generated | glossary.json created with >= 5 terms | Warning |
| Non-Goals section present | At least 1 non-goal with rationale | Warning |
| Concepts section present | Terminology table in product brief | Warning |
### Phase 3: Requirements (PRD)
@@ -122,6 +125,8 @@ Content provides sufficient detail for execution teams.
| Non-functional requirements | >= 1 (performance, security, etc.) | Warning |
| User stories | >= 1 per Must-have requirement | Warning |
| Traceability | Requirements trace to product brief goals | Warning |
| RFC 2119 keywords used | Behavioral requirements use MUST/SHOULD/MAY | Warning |
| Data model defined | Core entities have field-level definitions | Warning |
### Phase 4: Architecture
@@ -134,6 +139,12 @@ Content provides sufficient detail for execution teams.
| 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 |
| State machine defined | >= 1 lifecycle state diagram (if service/platform type) | Warning |
| Configuration model defined | All config fields with type/default/constraint (if service type) | Warning |
| Error handling strategy | Per-component error classification and recovery | Warning |
| Observability metrics | >= 3 metrics defined (if service/platform type) | Warning |
| Trust model defined | Trust levels documented (if service type) | Info |
| Implementation guidance | Key decisions for implementers listed | Info |
### Phase 5: Epics & Stories
@@ -171,6 +182,8 @@ 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)
Glossary terms -> All Documents (core terms used consistently)
Non-Goals (Brief) -> Requirements + Epics (no contradictions)
```
### Consistency Checks
@@ -181,6 +194,9 @@ Architecture ADRs -> Epics (tech choices reflected in implementation stories
| 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 |
| Glossary compliance | All | Core terms match glossary.json definitions, no synonym drift |
| Scope containment | Brief + PRD | PRD requirements do not introduce scope beyond brief boundaries |
| Non-Goals respected | Brief + PRD + Epics | No requirement/story contradicts explicit Non-Goals |
### Traceability Matrix Format
@@ -217,3 +233,23 @@ Architecture ADRs -> Epics (tech choices reflected in implementation stories
- Consider additional ADR alternatives
- Story estimation hints missing
- Mermaid diagrams could be more detailed
---
## Iteration Quality Tracking
When Phase 6.5 (Auto-Fix) is triggered:
| Iteration | Expected Improvement | Max Iterations |
|-----------|---------------------|----------------|
| 1st | Fix all Error-severity issues | - |
| 2nd | Fix remaining Warnings, improve scores | Max reached |
### Iteration Exit Criteria
| Condition | Action |
|-----------|--------|
| Overall score >= 80% after fix | Pass, proceed to handoff |
| Overall score 60-79% after 2 iterations | Review, proceed with caveats |
| Overall score < 60% after 2 iterations | Fail, manual intervention required |
| No Error-severity issues remaining | Eligible for handoff regardless of score |

View File

@@ -181,6 +181,125 @@ erDiagram
| Scalability | {target} | {how measured} | [ADR-{NNN}](ADR-{NNN}-{slug}.md) |
| Reliability | {target} | {how measured} | [ADR-{NNN}](ADR-{NNN}-{slug}.md) |
## State Machine
{For each core entity with a lifecycle (e.g., Order, Session, Task):}
### {Entity} Lifecycle
```
{ASCII state diagram showing all states, transitions, triggers, and error paths}
┌──────────┐
│ Created │
└─────┬────┘
│ start()
┌──────────┐ error ┌──────────┐
│ Running │ ──────────▶ │ Failed │
└─────┬────┘ └──────────┘
│ complete()
┌──────────┐
│ Completed │
└──────────┘
```
| From State | Event | To State | Side Effects | Error Handling |
|-----------|-------|----------|-------------|----------------|
| {from} | {event} | {to} | {side_effects} | {error_behavior} |
## Configuration Model
### Required Configuration
| Field | Type | Default | Constraint | Description |
|-------|------|---------|------------|-------------|
| {field_name} | {string/number/boolean/enum} | {default_value} | {validation rule} | {description} |
### Optional Configuration
| Field | Type | Default | Constraint | Description |
|-------|------|---------|------------|-------------|
| {field_name} | {type} | {default} | {constraint} | {description} |
### Environment Variables
| Variable | Maps To | Required |
|----------|---------|----------|
| {ENV_VAR} | {config_field} | {yes/no} |
## Error Handling
### Error Classification
| Category | Severity | Retry | Example |
|----------|----------|-------|---------|
| Transient | Low | Yes, with backoff | Network timeout, rate limit |
| Permanent | High | No | Invalid configuration, auth failure |
| Degraded | Medium | Partial | Dependency unavailable, fallback active |
### Per-Component Error Strategy
| Component | Error Scenario | Behavior | Recovery |
|-----------|---------------|----------|----------|
| {component} | {scenario} | {MUST/SHOULD behavior} | {recovery strategy} |
## Observability
### Metrics
| Metric Name | Type | Labels | Description |
|-------------|------|--------|-------------|
| {metric_name} | {counter/gauge/histogram} | {label1, label2} | {what it measures} |
### Logging
| Event | Level | Fields | Description |
|-------|-------|--------|-------------|
| {event_name} | {INFO/WARN/ERROR} | {structured fields} | {when logged} |
### Health Checks
| Check | Endpoint | Interval | Failure Action |
|-------|----------|----------|----------------|
| {check_name} | {/health/xxx} | {duration} | {action on failure} |
## Trust & Safety
### Trust Levels
| Level | Description | Approval Required | Allowed Operations |
|-------|-------------|-------------------|-------------------|
| High Trust | {description} | None | {operations} |
| Standard | {description} | {approval type} | {operations} |
| Low Trust | {description} | {approval type} | {operations} |
### Security Controls
{Detailed security controls beyond the basic auth covered in Security Architecture}
## Implementation Guidance
### Key Decisions for Implementers
| Decision | Options | Recommendation | Rationale |
|----------|---------|---------------|-----------|
| {decision_area} | {option_1, option_2} | {recommended} | {why} |
### Implementation Order
1. {component/module 1}: {why first}
2. {component/module 2}: {depends on #1}
### Testing Strategy
| Layer | Scope | Tools | Coverage Target |
|-------|-------|-------|-----------------|
| Unit | {scope} | {tools} | {target} |
| Integration | {scope} | {tools} | {target} |
| E2E | {scope} | {tools} | {target} |
## Risks & Mitigations
| Risk | Impact | Probability | Mitigation |

View File

@@ -101,6 +101,19 @@ graph LR
|------|---------------|------------|
| {risk description} | [EPIC-{NNN}](EPIC-{NNN}-{slug}.md) | {mitigation} |
## Versioning & Changelog
### Version Strategy
- **Versioning Scheme**: {semver/calver/custom}
- **Breaking Change Definition**: {what constitutes a breaking change}
- **Deprecation Policy**: {how deprecated features are handled}
### Changelog
| Version | Date | Type | Description |
|---------|------|------|-------------|
| {version} | {date} | {Added/Changed/Fixed/Removed} | {description} |
## Open Questions
- [ ] {question about scope or implementation 1}

View File

@@ -30,6 +30,15 @@ dependencies:
{executive_summary - 2-3 sentences capturing the essence of the product/feature}
## Concepts & Terminology
| Term | Definition | Aliases |
|------|-----------|---------|
| {term_1} | {definition} | {comma-separated aliases if any} |
| {term_2} | {definition} | |
{Note: All documents in this specification MUST use these terms consistently.}
## Vision
{vision_statement - clear, aspirational 1-3 sentence statement of what success looks like}
@@ -70,6 +79,15 @@ dependencies:
- {explicitly excluded item 1}
- {explicitly excluded item 2}
### Non-Goals
{Explicit list of things this project will NOT do, with rationale for each:}
| Non-Goal | Rationale |
|----------|-----------|
| {non_goal_1} | {why this is explicitly excluded} |
| {non_goal_2} | {why this is explicitly excluded} |
### Assumptions
- {key assumption 1}
- {key assumption 2}
@@ -130,4 +148,6 @@ dependencies:
| `{product_name}` | Seed analysis | Product/feature name |
| `{executive_summary}` | CLI synthesis | 2-3 sentence summary |
| `{vision_statement}` | CLI product perspective | Aspirational vision |
| `{term_1}`, `{term_2}` | CLI synthesis | Domain terms with definitions and optional aliases |
| `{non_goal_1}`, `{non_goal_2}` | CLI synthesis | Explicit exclusions with rationale |
| All `{...}` fields | CLI analysis outputs | Filled from multi-perspective analysis |

View File

@@ -0,0 +1,27 @@
# API Spec Profile
Defines additional required sections for API-type specifications.
## Required Sections (in addition to base template)
### In Architecture Document
- **Endpoint Definition**: MUST list all endpoints with method, path, auth, request/response schema
- **Authentication Model**: MUST define auth mechanism (OAuth2/JWT/API Key), token lifecycle
- **Rate Limiting**: MUST define rate limits per tier/endpoint, throttling behavior
- **Error Codes**: MUST define error response format, standard error codes with descriptions
- **API Versioning**: MUST define versioning strategy (URL/header/query), deprecation policy
- **Pagination**: SHOULD define pagination strategy for list endpoints
- **Idempotency**: SHOULD define idempotency requirements for write operations
### In Requirements Document
- **Endpoint Acceptance Criteria**: Each requirement SHOULD map to specific endpoints
- **SLA Definitions**: MUST define response time, availability targets per endpoint tier
### Quality Gate Additions
| Check | Criteria | Severity |
|-------|----------|----------|
| Endpoints documented | All endpoints with method + path | Error |
| Auth model defined | Authentication mechanism specified | Error |
| Error codes defined | Standard error format + codes | Warning |
| Rate limits defined | Per-endpoint or per-tier limits | Warning |
| API versioning strategy | Versioning approach specified | Warning |

View File

@@ -0,0 +1,25 @@
# Library Spec Profile
Defines additional required sections for library/SDK-type specifications.
## Required Sections (in addition to base template)
### In Architecture Document
- **Public API Surface**: MUST define all public interfaces with signatures, parameters, return types
- **Usage Examples**: MUST provide >= 3 code examples showing common usage patterns
- **Compatibility Matrix**: MUST define supported language versions, runtime environments
- **Dependency Policy**: MUST define transitive dependency policy, version constraints
- **Extension Points**: SHOULD define plugin/extension mechanisms if applicable
- **Bundle Size**: SHOULD define target bundle size and tree-shaking strategy
### In Requirements Document
- **API Ergonomics**: Requirements SHOULD address developer experience and API consistency
- **Error Reporting**: MUST define error types, messages, and recovery hints for consumers
### Quality Gate Additions
| Check | Criteria | Severity |
|-------|----------|----------|
| Public API documented | All public interfaces with types | Error |
| Usage examples | >= 3 working examples | Warning |
| Compatibility matrix | Supported environments listed | Warning |
| Dependency policy | Transitive deps strategy defined | Info |

View File

@@ -0,0 +1,28 @@
# Service Spec Profile
Defines additional required sections for service-type specifications.
## Required Sections (in addition to base template)
### In Architecture Document
- **Concepts & Terminology**: MUST define all domain terms with consistent aliases
- **State Machine**: MUST include ASCII state diagram for each entity with a lifecycle
- **Configuration Model**: MUST define all configurable fields with types, defaults, constraints
- **Error Handling**: MUST define per-component error classification and recovery strategies
- **Observability**: MUST define >= 3 metrics, structured log format, health check endpoints
- **Trust & Safety**: SHOULD define trust levels and approval matrix
- **Graceful Shutdown**: MUST describe shutdown sequence and cleanup procedures
- **Implementation Guidance**: SHOULD provide implementation order and key decisions
### In Requirements Document
- **Behavioral Constraints**: MUST use RFC 2119 keywords (MUST/SHOULD/MAY) for all requirements
- **Data Model**: MUST define core entities with field-level detail (type, constraint, relation)
### Quality Gate Additions
| Check | Criteria | Severity |
|-------|----------|----------|
| State machine present | >= 1 lifecycle state diagram | Error |
| Configuration model | All config fields documented | Warning |
| Observability metrics | >= 3 metrics defined | Warning |
| Error handling defined | Per-component strategy | Warning |
| RFC keywords used | Behavioral requirements use MUST/SHOULD/MAY | Warning |

View File

@@ -264,9 +264,15 @@ AskUserQuestion({
│ └── test-report.md ← tester output
├── explorations/ ← explorer cache
│ └── cache-index.json
└── wisdom/ ← Knowledge base
├── ui-patterns.md
── state-management.md
└── wisdom/ ← Session knowledge base
├── contributions/ ← Worker contributions (write-only for workers)
── principles/ ← Core principles
│ └── general-ux.md
├── patterns/ ← Solution patterns
│ ├── ui-feedback.md
│ └── state-management.md
└── anti-patterns/ ← Issues to avoid
└── common-ux-pitfalls.md
```
## Error Handling

View File

@@ -22,6 +22,13 @@ Design feedback mechanisms (loading/error/success states) and state management p
| React | useState, useRef | onClick, onChange |
| Vue | ref, reactive | @click, @change |
### Wisdom Input
1. Read `<session>/wisdom/patterns/ui-feedback.md` for established feedback design patterns
2. Read `<session>/wisdom/patterns/state-management.md` for state handling patterns
3. Read `<session>/wisdom/principles/general-ux.md` for UX design principles
4. Apply patterns when designing solutions for identified issues
### Complex Design (use CLI)
For complex multi-component solutions:
@@ -166,6 +173,13 @@ const handleUpload = async (event: React.FormEvent) => {
```
2. Write guide to `<session>/artifacts/design-guide.md`
### Wisdom Contribution
If novel design patterns created:
1. Write new patterns to `<session>/wisdom/contributions/designer-pattern-<timestamp>.md`
2. Format: Problem context, solution design, implementation hints, trade-offs
3. Share state via team_msg:
```
team_msg(operation="log", session_id=<session-id>, from="designer",

View File

@@ -14,6 +14,13 @@ Diagnose root causes of UI issues: state management problems, event binding fail
1. Load scan report from `<session>/artifacts/scan-report.md`
2. Load scanner state via `team_msg(operation="get_state", session_id=<session-id>, role="scanner")`
### Wisdom Input
1. Read `<session>/wisdom/patterns/ui-feedback.md` and `<session>/wisdom/patterns/state-management.md` if available
2. Use patterns to identify root causes of UI interaction issues
3. Reference `<session>/wisdom/anti-patterns/common-ux-pitfalls.md` for common causes
3. Assess issue complexity:
| Complexity | Criteria | Strategy |
@@ -82,6 +89,13 @@ For each issue from scan report:
```
2. Write report to `<session>/artifacts/diagnosis.md`
### Wisdom Contribution
If new root cause patterns discovered:
1. Write diagnosis patterns to `<session>/wisdom/contributions/diagnoser-patterns-<timestamp>.md`
2. Format: Symptom, root cause, detection method, fix approach
3. Share state via team_msg:
```
team_msg(operation="log", session_id=<session-id>, from="diagnoser",

View File

@@ -15,6 +15,12 @@ Explore codebase for UI component patterns, state management conventions, and fr
1. Parse exploration request from task description
2. Determine file patterns based on framework:
### Wisdom Input
1. Read `<session>/wisdom/patterns/ui-feedback.md` and `<session>/wisdom/patterns/state-management.md` if available
2. Use known patterns as reference when exploring codebase for component structures
3. Check `<session>/wisdom/anti-patterns/common-ux-pitfalls.md` to identify problematic patterns during exploration
| Framework | Patterns |
|-----------|----------|
| React | `**/*.tsx`, `**/*.jsx`, `**/use*.ts`, `**/store*.ts` |
@@ -80,6 +86,18 @@ For each dimension, collect:
2. Cache results to `<session>/explorations/cache-index.json`
3. Write summary to `<session>/explorations/exploration-summary.md`
### Wisdom Contribution
If new component patterns or framework conventions discovered:
1. Write pattern summaries to `<session>/wisdom/contributions/explorer-patterns-<timestamp>.md`
2. Format:
- Pattern Name: Descriptive name
- Framework: React/Vue/etc.
- Use Case: When to apply this pattern
- Code Example: Representative snippet
- Adoption: How widely used in codebase
4. Share state via team_msg:
```
team_msg(operation="log", session_id=<session-id>, from="explorer",

View File

@@ -15,7 +15,12 @@ Generate executable fix code with proper state management, event handling, and U
1. Extract session path from task description
2. Read design guide: `<session>/artifacts/design-guide.md`
3. Extract implementation tasks from design guide
4. Load framework conventions from wisdom files (if available)
4. **Wisdom Input**:
- Read `<session>/wisdom/patterns/state-management.md` for state handling patterns
- Read `<session>/wisdom/patterns/ui-feedback.md` for UI feedback implementation patterns
- Read `<session>/wisdom/principles/general-ux.md` for implementation principles
- Load framework-specific conventions if available
- Apply these patterns and principles when generating code to ensure consistency and quality
5. **For inner loop**: Load context_accumulator from prior IMPL tasks
### Context Accumulator (Inner Loop)
@@ -123,3 +128,37 @@ team_msg(operation="log", session_id=<session-id>, from="implementer",
validation_passed: true
})
```
### Wisdom Contribution
If reusable code patterns or snippets created:
1. Write code snippets to `<session>/wisdom/contributions/implementer-snippets-<timestamp>.md`
2. Format: Use case, code snippet with comments, framework compatibility notes
Example contribution format:
```markdown
# Implementer Snippets - <timestamp>
## Loading State Pattern (React)
### Use Case
Async operations requiring loading indicator
### Code Snippet
```tsx
const [isLoading, setIsLoading] = useState(false);
const handleAsyncAction = async () => {
setIsLoading(true);
try {
await performAction();
} finally {
setIsLoading(false);
}
};
```
### Framework Compatibility
- React 16.8+ (hooks)
- Next.js compatible
```

View File

@@ -32,6 +32,12 @@ Scan UI components to identify interaction issues: unresponsive buttons, missing
- React: `**/*.tsx`, `**/*.jsx`, `**/use*.ts`
- Vue: `**/*.vue`, `**/composables/*.ts`
### Wisdom Input
1. Read `<session>/wisdom/anti-patterns/common-ux-pitfalls.md` if available
2. Use anti-patterns to identify known UX issues during scanning
3. Check `<session>/wisdom/patterns/ui-feedback.md` for expected feedback patterns
### Complex Analysis (use CLI)
For large projects with many components:
@@ -103,3 +109,9 @@ For each component file:
scanned_files: <count>
})
```
### Wisdom Contribution
If novel UX issues discovered that aren't in anti-patterns:
1. Write findings to `<session>/wisdom/contributions/scanner-issues-<timestamp>.md`
2. Format: Issue description, detection criteria, affected components

View File

@@ -29,6 +29,12 @@ Generate and run tests to verify fixes (loading states, error handling, state up
3. Load test strategy from design guide
### Wisdom Input
1. Read `<session>/wisdom/anti-patterns/common-ux-pitfalls.md` for common issues to test
2. Read `<session>/wisdom/patterns/ui-feedback.md` for expected feedback behaviors to verify
3. Use wisdom to design comprehensive test cases covering known edge cases
## Phase 3: Test Generation & Execution
### Test Generation
@@ -96,6 +102,12 @@ Iterative test-fix cycle (max 5 iterations):
## Phase 4: Test Report
### Wisdom Contribution
If new edge cases or test patterns discovered:
1. Write test findings to `<session>/wisdom/contributions/tester-edge-cases-<timestamp>.md`
2. Format: Edge case description, test scenario, expected behavior, actual behavior
Generate test report:
```markdown

View File

@@ -114,6 +114,23 @@ For callback/check/resume: load `commands/monitor.md` and execute handler, then
```
3. TeamCreate(team_name="ux-improve")
4. Initialize meta.json with pipeline config:
### Wisdom Initialization
After creating session directory, initialize wisdom from skill's permanent knowledge base:
1. Copy `.claude/skills/team-ux-improve/wisdom/` contents to `<session>/wisdom/`
2. Create `<session>/wisdom/contributions/` directory if not exists
3. This provides workers with initial patterns, principles, and anti-patterns
Example:
```bash
# Copy permanent wisdom to session
cp -r .claude/skills/team-ux-improve/wisdom/* <session>/wisdom/
mkdir -p <session>/wisdom/contributions/
```
5. Initialize meta.json with pipeline config:
```
team_msg(operation="log", session_id=<session-id>, from="coordinator",
type="state_update",
@@ -182,6 +199,32 @@ Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Pha
- artifacts/design-guide.md
- artifacts/fixes/
- artifacts/test-report.md
### Wisdom Consolidation
Before pipeline completion, handle knowledge contributions:
1. Check if `<session>/wisdom/contributions/` has any files
2. If contributions exist:
- Summarize contributions for user review
- Use AskUserQuestion to ask if user wants to merge valuable contributions back to permanent wisdom
- If approved, copy selected contributions to `.claude/skills/team-ux-improve/wisdom/` (classify into patterns/, anti-patterns/, etc.)
Example interaction:
```
AskUserQuestion({
questions: [{
question: "Workers contributed new knowledge during this session. Merge to permanent wisdom?",
header: "Knowledge",
options: [
{ label: "Merge All", description: "Add all contributions to permanent wisdom" },
{ label: "Review First", description: "Show contributions before deciding" },
{ label: "Skip", description: "Keep contributions in session only" }
]
}]
})
```
3. **Completion Action** (interactive mode):
```

View File

@@ -0,0 +1,17 @@
# Common UX Pitfalls
## Interaction Issues
- Buttons without loading states during async operations
- Missing error handling with user feedback
- State changes without visual updates
- Double-click vulnerabilities
## State Issues
- Stale data after mutations
- Race conditions in async operations
- Missing rollback for failed optimistic updates
## Feedback Issues
- Silent failures without user notification
- Generic error messages without actionable guidance
- Missing confirmation for destructive actions

View File

@@ -0,0 +1,14 @@
# State Management Patterns
## Local Component State
- Use for UI-only state (open/closed, hover, focus)
- Keep close to where it's used
## Shared State
- Lift state to lowest common ancestor
- Use context or state management library for deep trees
## Async State
- Track loading, error, and success states
- Handle race conditions with request cancellation
- Implement retry logic with exponential backoff

View File

@@ -0,0 +1,16 @@
# UI Feedback Patterns
## Loading States
- Use skeleton loaders for content areas
- Disable buttons during async operations
- Show progress indicators for long operations
## Error Handling
- Display errors inline when possible
- Provide actionable error messages
- Allow retry for transient failures
## Success Feedback
- Toast notifications for non-critical successes
- Inline confirmation for critical actions
- Auto-dismiss non-critical notifications

View File

@@ -0,0 +1,16 @@
# General UX Principles
## Feedback & Responsiveness
- Every user action should have immediate visual feedback
- Loading states must be shown for operations >200ms
- Success/error states should be clearly communicated
## State Management
- UI state should reflect the underlying data state
- Optimistic updates should have rollback mechanisms
- State changes should be atomic and predictable
## Accessibility
- Interactive elements must be keyboard accessible
- Color should not be the only indicator of state
- Focus states must be visible