feat(claude): add CC-SDD planning workflow and /plan command (Step 4)

Adopt CC-SDD (Kiro) as the project's spec-driven planning tool, with
plans persisted in .kiro/specs/ and a checkpoint after every task
(strictest cadence — no code without an approved plan).

CC-SDD install (via npx cc-sdd@latest --claude --lang en):
- .kiro/settings/rules/: EARS format, gap-analysis, design and
  requirements review gates, design discovery, tasks generation,
  steering principles, parallel-task analysis.
- .kiro/settings/templates/: specs (init, requirements, design, tasks,
  research) and steering (product/tech/structure plus optional
  api-standards/auth/db/deployment/error-handling/security/testing).
- .claude/commands/kiro/: 11 Kiro slash commands — spec-init,
  spec-requirements, spec-design, spec-tasks, spec-impl, spec-status,
  steering, steering-custom, validate-gap, validate-design,
  validate-impl.

Local additions:
- .claude/commands/plan.md: /plan [task] wrapper that picks up the task
  from $ARGUMENTS or a single .ticket/<n>.md snapshot, walks the Kiro
  flow (steering -> spec-init -> spec-requirements -> validate-gap ->
  spec-design -> validate-design -> spec-tasks) and stops for human
  approval after each artefact. Refuses "just code it" requests.
- .claude/hooks/session_start.sh: extend to print active tickets
  (.ticket/*.md) and open specs (.kiro/specs/*/) with phase from
  spec.json, alongside the existing branch/state line.

Documentation: .claude/onboarding/step4_workflow/01_tool_decision.md
This commit is contained in:
Dominik Seemann 2026-05-06 18:01:41 +02:00
parent 52f78d9fe3
commit 8144290fc6
42 changed files with 3570 additions and 24 deletions

View File

@ -0,0 +1,177 @@
---
description: Create comprehensive technical design for a specification
allowed-tools: Bash, Glob, Grep, LS, Read, Write, Edit, MultiEdit, Update, WebSearch, WebFetch
argument-hint: <feature-name> [-y]
---
# Technical Design Generator
<background_information>
- **Mission**: Generate comprehensive technical design document that translates requirements (WHAT) into architectural design (HOW)
- **Success Criteria**:
- All requirements mapped to technical components with clear interfaces
- Appropriate architecture discovery and research completed
- Design aligns with steering context and existing patterns
- Visual diagrams included for complex architectures
</background_information>
<instructions>
## Core Task
Generate technical design document for feature **$1** based on approved requirements.
## Execution Steps
### Step 1: Load Context
**Read all necessary context**:
- `.kiro/specs/$1/spec.json`, `requirements.md`, `design.md` (if exists)
- **Entire `.kiro/steering/` directory** for complete project memory
- `.kiro/settings/templates/specs/design.md` for document structure
- `.kiro/settings/rules/design-principles.md` for design principles
- `.kiro/settings/templates/specs/research.md` for discovery log structure
**Validate requirements approval**:
- If `-y` flag provided ($2 == "-y"): Auto-approve requirements in spec.json
- Otherwise: Verify approval status (stop if unapproved, see Safety & Fallback)
### Step 2: Discovery & Analysis
**Critical: This phase ensures design is based on complete, accurate information.**
1. **Classify Feature Type**:
- **New Feature** (greenfield) → Full discovery required
- **Extension** (existing system) → Integration-focused discovery
- **Simple Addition** (CRUD/UI) → Minimal or no discovery
- **Complex Integration** → Comprehensive analysis required
2. **Execute Appropriate Discovery Process**:
**For Complex/New Features**:
- Read and execute `.kiro/settings/rules/design-discovery-full.md`
- Conduct thorough research using WebSearch/WebFetch:
- Latest architectural patterns and best practices
- External dependency verification (APIs, libraries, versions, compatibility)
- Official documentation, migration guides, known issues
- Performance benchmarks and security considerations
**For Extensions**:
- Read and execute `.kiro/settings/rules/design-discovery-light.md`
- Focus on integration points, existing patterns, compatibility
- Use Grep to analyze existing codebase patterns
**For Simple Additions**:
- Skip formal discovery, quick pattern check only
3. **Retain Discovery Findings for Step 3**:
- External API contracts and constraints
- Technology decisions with rationale
- Existing patterns to follow or extend
- Integration points and dependencies
- Identified risks and mitigation strategies
- Potential architecture patterns and boundary options (note details in `research.md`)
- Parallelization considerations for future tasks (capture dependencies in `research.md`)
4. **Persist Findings to Research Log**:
- Create or update `.kiro/specs/$1/research.md` using the shared template
- Summarize discovery scope and key findings (Summary section)
- Record investigations in Research Log topics with sources and implications
- Document architecture pattern evaluation, design decisions, and risks using the template sections
- Use the language specified in spec.json when writing or updating `research.md`
### Step 3: Generate Design Document
1. **Load Design Template and Rules**:
- Read `.kiro/settings/templates/specs/design.md` for structure
- Read `.kiro/settings/rules/design-principles.md` for principles
2. **Generate Design Document**:
- **Follow specs/design.md template structure and generation instructions strictly**
- **Integrate all discovery findings**: Use researched information (APIs, patterns, technologies) throughout component definitions, architecture decisions, and integration points
- If existing design.md found in Step 1, use it as reference context (merge mode)
- Apply design rules: Type Safety, Visual Communication, Formal Tone
- Use language specified in spec.json
- Ensure sections reflect updated headings ("Architecture Pattern & Boundary Map", "Technology Stack & Alignment", "Components & Interface Contracts") and reference supporting details from `research.md`
3. **Update Metadata** in spec.json:
- Set `phase: "design-generated"`
- Set `approvals.design.generated: true, approved: false`
- Set `approvals.requirements.approved: true`
- Update `updated_at` timestamp
## Critical Constraints
- **Type Safety**:
- Enforce strong typing aligned with the project's technology stack.
- For statically typed languages, define explicit types/interfaces and avoid unsafe casts.
- For TypeScript, never use `any`; prefer precise types and generics.
- For dynamically typed languages, provide type hints/annotations where available (e.g., Python type hints) and validate inputs at boundaries.
- Document public interfaces and contracts clearly to ensure cross-component type safety.
- **Latest Information**: Use WebSearch/WebFetch for external dependencies and best practices
- **Steering Alignment**: Respect existing architecture patterns from steering context
- **Template Adherence**: Follow specs/design.md template structure and generation instructions strictly
- **Design Focus**: Architecture and interfaces ONLY, no implementation code
- **Requirements Traceability IDs**: Use numeric requirement IDs only (e.g. "1.1", "1.2", "3.1", "3.3") exactly as defined in requirements.md. Do not invent new IDs or use alphabetic labels.
</instructions>
## Tool Guidance
- **Read first**: Load all context before taking action (specs, steering, templates, rules)
- **Research when uncertain**: Use WebSearch/WebFetch for external dependencies, APIs, and latest best practices
- **Analyze existing code**: Use Grep to find patterns and integration points in codebase
- **Write last**: Generate design.md only after all research and analysis complete
## Output Description
**Command execution output** (separate from design.md content):
Provide brief summary in the language specified in spec.json:
1. **Status**: Confirm design document generated at `.kiro/specs/$1/design.md`
2. **Discovery Type**: Which discovery process was executed (full/light/minimal)
3. **Key Findings**: 2-3 critical insights from `research.md` that shaped the design
4. **Next Action**: Approval workflow guidance (see Safety & Fallback)
5. **Research Log**: Confirm `research.md` updated with latest decisions
**Format**: Concise Markdown (under 200 words) - this is the command output, NOT the design document itself
**Note**: The actual design document follows `.kiro/settings/templates/specs/design.md` structure.
## Safety & Fallback
### Error Scenarios
**Requirements Not Approved**:
- **Stop Execution**: Cannot proceed without approved requirements
- **User Message**: "Requirements not yet approved. Approval required before design generation."
- **Suggested Action**: "Run `/kiro:spec-design $1 -y` to auto-approve requirements and proceed"
**Missing Requirements**:
- **Stop Execution**: Requirements document must exist
- **User Message**: "No requirements.md found at `.kiro/specs/$1/requirements.md`"
- **Suggested Action**: "Run `/kiro:spec-requirements $1` to generate requirements first"
**Template Missing**:
- **User Message**: "Template file missing at `.kiro/settings/templates/specs/design.md`"
- **Suggested Action**: "Check repository setup or restore template file"
- **Fallback**: Use inline basic structure with warning
**Steering Context Missing**:
- **Warning**: "Steering directory empty or missing - design may not align with project standards"
- **Proceed**: Continue with generation but note limitation in output
**Discovery Complexity Unclear**:
- **Default**: Use full discovery process (`.kiro/settings/rules/design-discovery-full.md`)
- **Rationale**: Better to over-research than miss critical context
- **Invalid Requirement IDs**:
- **Stop Execution**: If requirements.md is missing numeric IDs or uses non-numeric headings (for example, "Requirement A"), stop and instruct the user to fix requirements.md before continuing.
### Next Phase: Task Generation
**If Design Approved**:
- Review generated design at `.kiro/specs/$1/design.md`
- **Optional**: Run `/kiro:validate-design $1` for interactive quality review
- Then `/kiro:spec-tasks $1 -y` to generate implementation tasks
**If Modifications Needed**:
- Provide feedback and re-run `/kiro:spec-design $1`
- Existing design used as reference (merge mode)
**Note**: Design approval is mandatory before proceeding to task generation.

View File

@ -0,0 +1,108 @@
---
description: Execute spec tasks using TDD methodology
allowed-tools: Bash, Read, Write, Edit, MultiEdit, Grep, Glob, LS, WebFetch, WebSearch
argument-hint: <feature-name> [task-numbers]
---
# Implementation Task Executor
<background_information>
- **Mission**: Execute implementation tasks using Test-Driven Development methodology based on approved specifications
- **Success Criteria**:
- All tests written before implementation code
- Code passes all tests with no regressions
- Tasks marked as completed in tasks.md
- Implementation aligns with design and requirements
</background_information>
<instructions>
## Core Task
Execute implementation tasks for feature **$1** using Test-Driven Development.
## Execution Steps
### Step 1: Load Context
**Read all necessary context**:
- `.kiro/specs/$1/spec.json`, `requirements.md`, `design.md`, `tasks.md`
- **Entire `.kiro/steering/` directory** for complete project memory
**Validate approvals**:
- Verify tasks are approved in spec.json (stop if not, see Safety & Fallback)
### Step 2: Select Tasks
**Determine which tasks to execute**:
- If `$2` provided: Execute specified task numbers (e.g., "1.1" or "1,2,3")
- Otherwise: Execute all pending tasks (unchecked `- [ ]` in tasks.md)
### Step 3: Execute with TDD
For each selected task, follow Kent Beck's TDD cycle:
1. **RED - Write Failing Test**:
- Write test for the next small piece of functionality
- Test should fail (code doesn't exist yet)
- Use descriptive test names
2. **GREEN - Write Minimal Code**:
- Implement simplest solution to make test pass
- Focus only on making THIS test pass
- Avoid over-engineering
3. **REFACTOR - Clean Up**:
- Improve code structure and readability
- Remove duplication
- Apply design patterns where appropriate
- Ensure all tests still pass after refactoring
4. **VERIFY - Validate Quality**:
- All tests pass (new and existing)
- No regressions in existing functionality
- Code coverage maintained or improved
5. **MARK COMPLETE**:
- Update checkbox from `- [ ]` to `- [x]` in tasks.md
## Critical Constraints
- **TDD Mandatory**: Tests MUST be written before implementation code
- **Task Scope**: Implement only what the specific task requires
- **Test Coverage**: All new code must have tests
- **No Regressions**: Existing tests must continue to pass
- **Design Alignment**: Implementation must follow design.md specifications
</instructions>
## Tool Guidance
- **Read first**: Load all context before implementation
- **Test first**: Write tests before code
- Use **WebSearch/WebFetch** for library documentation when needed
## Output Description
Provide brief summary in the language specified in spec.json:
1. **Tasks Executed**: Task numbers and test results
2. **Status**: Completed tasks marked in tasks.md, remaining tasks count
**Format**: Concise (under 150 words)
## Safety & Fallback
### Error Scenarios
**Tasks Not Approved or Missing Spec Files**:
- **Stop Execution**: All spec files must exist and tasks must be approved
- **Suggested Action**: "Complete previous phases: `/kiro:spec-requirements`, `/kiro:spec-design`, `/kiro:spec-tasks`"
**Test Failures**:
- **Stop Implementation**: Fix failing tests before continuing
- **Action**: Debug and fix, then re-run
### Task Execution
**Execute specific task(s)**:
- `/kiro:spec-impl $1 1.1` - Single task
- `/kiro:spec-impl $1 1,2,3` - Multiple tasks
**Execute all pending**:
- `/kiro:spec-impl $1` - All unchecked tasks

View File

@ -0,0 +1,65 @@
---
description: Initialize a new specification with detailed project description
allowed-tools: Bash, Read, Write, Glob
argument-hint: <project-description>
---
# Spec Initialization
<background_information>
- **Mission**: Initialize the first phase of spec-driven development by creating directory structure and metadata for a new specification
- **Success Criteria**:
- Generate appropriate feature name from project description
- Create unique spec structure without conflicts
- Provide clear path to next phase (requirements generation)
</background_information>
<instructions>
## Core Task
Generate a unique feature name from the project description ($ARGUMENTS) and initialize the specification structure.
## Execution Steps
1. **Check Uniqueness**: Verify `.kiro/specs/` for naming conflicts (append number suffix if needed)
2. **Create Directory**: `.kiro/specs/[feature-name]/`
3. **Initialize Files Using Templates**:
- Read `.kiro/settings/templates/specs/init.json`
- Read `.kiro/settings/templates/specs/requirements-init.md`
- Replace placeholders:
- `{{FEATURE_NAME}}` → generated feature name
- `{{TIMESTAMP}}` → current ISO 8601 timestamp
- `{{PROJECT_DESCRIPTION}}` → $ARGUMENTS
- Write `spec.json` and `requirements.md` to spec directory
## Important Constraints
- DO NOT generate requirements/design/tasks at this stage
- Follow stage-by-stage development principles
- Maintain strict phase separation
- Only initialization is performed in this phase
</instructions>
## Tool Guidance
- Use **Glob** to check existing spec directories for name uniqueness
- Use **Read** to fetch templates: `init.json` and `requirements-init.md`
- Use **Write** to create spec.json and requirements.md after placeholder replacement
- Perform validation before any file write operation
## Output Description
Provide output in the language specified in `spec.json` with the following structure:
1. **Generated Feature Name**: `feature-name` format with 1-2 sentence rationale
2. **Project Summary**: Brief summary (1 sentence)
3. **Created Files**: Bullet list with full paths
4. **Next Step**: Command block showing `/kiro:spec-requirements <feature-name>`
5. **Notes**: Explain why only initialization was performed (2-3 sentences on phase separation)
**Format Requirements**:
- Use Markdown headings (##, ###)
- Wrap commands in code blocks
- Keep total output concise (under 250 words)
- Use clear, professional language per `spec.json.language`
## Safety & Fallback
- **Ambiguous Feature Name**: If feature name generation is unclear, propose 2-3 options and ask user to select
- **Template Missing**: If template files don't exist in `.kiro/settings/templates/specs/`, report error with specific missing file path and suggest checking repository setup
- **Directory Conflict**: If feature name already exists, append numeric suffix (e.g., `feature-name-2`) and notify user of automatic conflict resolution
- **Write Failure**: Report error with specific path and suggest checking permissions or disk space

View File

@ -0,0 +1,96 @@
---
description: Generate comprehensive requirements for a specification
allowed-tools: Bash, Glob, Grep, LS, Read, Write, Edit, MultiEdit, Update, WebSearch, WebFetch
argument-hint: <feature-name>
---
# Requirements Generation
<background_information>
- **Mission**: Generate comprehensive, testable requirements in EARS format based on the project description from spec initialization
- **Success Criteria**:
- Create complete requirements document aligned with steering context
- Follow the project's EARS patterns and constraints for all acceptance criteria
- Focus on core functionality without implementation details
- Update metadata to track generation status
</background_information>
<instructions>
## Core Task
Generate complete requirements for feature **$1** based on the project description in requirements.md.
## Execution Steps
1. **Load Context**:
- Read `.kiro/specs/$1/spec.json` for language and metadata
- Read `.kiro/specs/$1/requirements.md` for project description
- **Load ALL steering context**: Read entire `.kiro/steering/` directory including:
- Default files: `structure.md`, `tech.md`, `product.md`
- All custom steering files (regardless of mode settings)
- This provides complete project memory and context
2. **Read Guidelines**:
- Read `.kiro/settings/rules/ears-format.md` for EARS syntax rules
- Read `.kiro/settings/templates/specs/requirements.md` for document structure
3. **Generate Requirements**:
- Create initial requirements based on project description
- Group related functionality into logical requirement areas
- Apply EARS format to all acceptance criteria
- Use language specified in spec.json
4. **Update Metadata**:
- Set `phase: "requirements-generated"`
- Set `approvals.requirements.generated: true`
- Update `updated_at` timestamp
## Important Constraints
- Focus on WHAT, not HOW (no implementation details)
- Requirements must be testable and verifiable
- Choose appropriate subject for EARS statements (system/service name for software)
- Generate initial version first, then iterate with user feedback (no sequential questions upfront)
- Requirement headings in requirements.md MUST include a leading numeric ID only (for example: "Requirement 1", "1.", "2 Feature ..."); do not use alphabetic IDs like "Requirement A".
</instructions>
## Tool Guidance
- **Read first**: Load all context (spec, steering, rules, templates) before generation
- **Write last**: Update requirements.md only after complete generation
- Use **WebSearch/WebFetch** only if external domain knowledge needed
## Output Description
Provide output in the language specified in spec.json with:
1. **Generated Requirements Summary**: Brief overview of major requirement areas (3-5 bullets)
2. **Document Status**: Confirm requirements.md updated and spec.json metadata updated
3. **Next Steps**: Guide user on how to proceed (approve and continue, or modify)
**Format Requirements**:
- Use Markdown headings for clarity
- Include file paths in code blocks
- Keep summary concise (under 300 words)
## Safety & Fallback
### Error Scenarios
- **Missing Project Description**: If requirements.md lacks project description, ask user for feature details
- **Ambiguous Requirements**: Propose initial version and iterate with user rather than asking many upfront questions
- **Template Missing**: If template files don't exist, use inline fallback structure with warning
- **Language Undefined**: Default to English (`en`) if spec.json doesn't specify language
- **Incomplete Requirements**: After generation, explicitly ask user if requirements cover all expected functionality
- **Steering Directory Empty**: Warn user that project context is missing and may affect requirement quality
- **Non-numeric Requirement Headings**: If existing headings do not include a leading numeric ID (for example, they use "Requirement A"), normalize them to numeric IDs and keep that mapping consistent (never mix numeric and alphabetic labels).
### Next Phase: Design Generation
**If Requirements Approved**:
- Review generated requirements at `.kiro/specs/$1/requirements.md`
- **Optional Gap Analysis** (for existing codebases):
- Run `/kiro:validate-gap $1` to analyze implementation gap with current code
- Identifies existing components, integration points, and implementation strategy
- Recommended for brownfield projects; skip for greenfield
- Then `/kiro:spec-design $1 -y` to proceed to design phase
**If Modifications Needed**:
- Provide feedback and re-run `/kiro:spec-requirements $1`
**Note**: Approval is mandatory before proceeding to design phase.

View File

@ -0,0 +1,85 @@
---
description: Show specification status and progress
allowed-tools: Bash, Read, Glob, Write, Edit, MultiEdit, Update
argument-hint: <feature-name>
---
# Specification Status
<background_information>
- **Mission**: Display comprehensive status and progress for a specification
- **Success Criteria**:
- Show current phase and completion status
- Identify next actions and blockers
- Provide clear visibility into progress
</background_information>
<instructions>
## Core Task
Generate status report for feature **$1** showing progress across all phases.
## Execution Steps
### Step 1: Load Spec Context
- Read `.kiro/specs/$1/spec.json` for metadata and phase status
- Read existing files: `requirements.md`, `design.md`, `tasks.md` (if they exist)
- Check `.kiro/specs/$1/` directory for available files
### Step 2: Analyze Status
**Parse each phase**:
- **Requirements**: Count requirements and acceptance criteria
- **Design**: Check for architecture, components, diagrams
- **Tasks**: Count completed vs total tasks (parse `- [x]` vs `- [ ]`)
- **Approvals**: Check approval status in spec.json
### Step 3: Generate Report
Create report in the language specified in spec.json covering:
1. **Current Phase & Progress**: Where the spec is in the workflow
2. **Completion Status**: Percentage complete for each phase
3. **Task Breakdown**: If tasks exist, show completed/remaining counts
4. **Next Actions**: What needs to be done next
5. **Blockers**: Any issues preventing progress
## Critical Constraints
- Use language from spec.json
- Calculate accurate completion percentages
- Identify specific next action commands
</instructions>
## Tool Guidance
- **Read**: Load spec.json first, then other spec files as needed
- **Parse carefully**: Extract completion data from tasks.md checkboxes
- Use **Glob** to check which spec files exist
## Output Description
Provide status report in the language specified in spec.json:
**Report Structure**:
1. **Feature Overview**: Name, phase, last updated
2. **Phase Status**: Requirements, Design, Tasks with completion %
3. **Task Progress**: If tasks exist, show X/Y completed
4. **Next Action**: Specific command to run next
5. **Issues**: Any blockers or missing elements
**Format**: Clear, scannable format with emojis (✅/⏳/❌) for status
## Safety & Fallback
### Error Scenarios
**Spec Not Found**:
- **Message**: "No spec found for `$1`. Check available specs in `.kiro/specs/`"
- **Action**: List available spec directories
**Incomplete Spec**:
- **Warning**: Identify which files are missing
- **Suggested Action**: Point to next phase command
### List All Specs
To see all available specs:
- Run with no argument or use wildcard
- Shows all specs in `.kiro/specs/` with their status

View File

@ -0,0 +1,136 @@
---
description: Generate implementation tasks for a specification
allowed-tools: Read, Write, Edit, MultiEdit, Glob, Grep
argument-hint: <feature-name> [-y] [--sequential]
---
# Implementation Tasks Generator
<background_information>
- **Mission**: Generate detailed, actionable implementation tasks that translate technical design into executable work items
- **Success Criteria**:
- All requirements mapped to specific tasks
- Tasks properly sized (1-3 hours each)
- Clear task progression with proper hierarchy
- Natural language descriptions focused on capabilities
</background_information>
<instructions>
## Core Task
Generate implementation tasks for feature **$1** based on approved requirements and design.
## Execution Steps
### Step 1: Load Context
**Read all necessary context**:
- `.kiro/specs/$1/spec.json`, `requirements.md`, `design.md`
- `.kiro/specs/$1/tasks.md` (if exists, for merge mode)
- **Entire `.kiro/steering/` directory** for complete project memory
**Validate approvals**:
- If `-y` flag provided ($2 == "-y"): Auto-approve requirements and design in spec.json
- Otherwise: Verify both approved (stop if not, see Safety & Fallback)
- Determine sequential mode based on presence of `--sequential`
### Step 2: Generate Implementation Tasks
**Load generation rules and template**:
- Read `.kiro/settings/rules/tasks-generation.md` for principles
- If `sequential` is **false**: Read `.kiro/settings/rules/tasks-parallel-analysis.md` for parallel judgement criteria
- Read `.kiro/settings/templates/specs/tasks.md` for format (supports `(P)` markers)
**Generate task list following all rules**:
- Use language specified in spec.json
- Map all requirements to tasks
- When documenting requirement coverage, list numeric requirement IDs only (comma-separated) without descriptive suffixes, parentheses, translations, or free-form labels
- Ensure all design components included
- Verify task progression is logical and incremental
- Collapse single-subtask structures by promoting them to major tasks and avoid duplicating details on container-only major tasks (use template patterns accordingly)
- Apply `(P)` markers to tasks that satisfy parallel criteria (omit markers in sequential mode)
- Mark optional test coverage subtasks with `- [ ]*` only when they strictly cover acceptance criteria already satisfied by core implementation and can be deferred post-MVP
- If existing tasks.md found, merge with new content
### Step 3: Finalize
**Write and update**:
- Create/update `.kiro/specs/$1/tasks.md`
- Update spec.json metadata:
- Set `phase: "tasks-generated"`
- Set `approvals.tasks.generated: true, approved: false`
- Set `approvals.requirements.approved: true`
- Set `approvals.design.approved: true`
- Update `updated_at` timestamp
## Critical Constraints
- **Follow rules strictly**: All principles in tasks-generation.md are mandatory
- **Natural Language**: Describe what to do, not code structure details
- **Complete Coverage**: ALL requirements must map to tasks
- **Maximum 2 Levels**: Major tasks and sub-tasks only (no deeper nesting)
- **Sequential Numbering**: Major tasks increment (1, 2, 3...), never repeat
- **Task Integration**: Every task must connect to the system (no orphaned work)
</instructions>
## Tool Guidance
- **Read first**: Load all context, rules, and templates before generation
- **Write last**: Generate tasks.md only after complete analysis and verification
## Output Description
Provide brief summary in the language specified in spec.json:
1. **Status**: Confirm tasks generated at `.kiro/specs/$1/tasks.md`
2. **Task Summary**:
- Total: X major tasks, Y sub-tasks
- All Z requirements covered
- Average task size: 1-3 hours per sub-task
3. **Quality Validation**:
- ✅ All requirements mapped to tasks
- ✅ Task dependencies verified
- ✅ Testing tasks included
4. **Next Action**: Review tasks and proceed when ready
**Format**: Concise (under 200 words)
## Safety & Fallback
### Error Scenarios
**Requirements or Design Not Approved**:
- **Stop Execution**: Cannot proceed without approved requirements and design
- **User Message**: "Requirements and design must be approved before task generation"
- **Suggested Action**: "Run `/kiro:spec-tasks $1 -y` to auto-approve both and proceed"
**Missing Requirements or Design**:
- **Stop Execution**: Both documents must exist
- **User Message**: "Missing requirements.md or design.md at `.kiro/specs/$1/`"
- **Suggested Action**: "Complete requirements and design phases first"
**Incomplete Requirements Coverage**:
- **Warning**: "Not all requirements mapped to tasks. Review coverage."
- **User Action Required**: Confirm intentional gaps or regenerate tasks
**Template/Rules Missing**:
- **User Message**: "Template or rules files missing in `.kiro/settings/`"
- **Fallback**: Use inline basic structure with warning
- **Suggested Action**: "Check repository setup or restore template files"
- **Missing Numeric Requirement IDs**:
- **Stop Execution**: All requirements in requirements.md MUST have numeric IDs. If any requirement lacks a numeric ID, stop and request that requirements.md be fixed before generating tasks.
### Next Phase: Implementation
**Before Starting Implementation**:
- **IMPORTANT**: Clear conversation history and free up context before running `/kiro:spec-impl`
- This applies when starting first task OR switching between tasks
- Fresh context ensures clean state and proper task focus
**If Tasks Approved**:
- Execute specific task: `/kiro:spec-impl $1 1.1` (recommended: clear context between each task)
- Execute multiple tasks: `/kiro:spec-impl $1 1.1,1.2` (use cautiously, clear context between tasks)
- Without arguments: `/kiro:spec-impl $1` (executes all pending tasks - NOT recommended due to context bloat)
**If Modifications Needed**:
- Provide feedback and re-run `/kiro:spec-tasks $1`
- Existing tasks used as reference (merge mode)
**Note**: The implementation phase will guide you through executing tasks with appropriate context and validation.

View File

@ -0,0 +1,127 @@
---
description: Create custom steering documents for specialized project contexts
allowed-tools: Bash, Read, Write, Edit, MultiEdit, Glob, Grep, LS
---
# Kiro Custom Steering Creation
<background_information>
**Role**: Create specialized steering documents beyond core files (product, tech, structure).
**Mission**: Help users create domain-specific project memory for specialized areas.
**Success Criteria**:
- Custom steering captures specialized patterns
- Follows same granularity principles as core steering
- Provides clear value for specific domain
</background_information>
<instructions>
## Workflow
1. **Ask user** for custom steering needs:
- Domain/topic (e.g., "API standards", "testing approach")
- Specific requirements or patterns to document
2. **Check if template exists**:
- Load from `.kiro/settings/templates/steering-custom/{name}.md` if available
- Use as starting point, customize based on project
3. **Analyze codebase** (JIT) for relevant patterns:
- **Glob** for related files
- **Read** for existing implementations
- **Grep** for specific patterns
4. **Generate custom steering**:
- Follow template structure if available
- Apply principles from `.kiro/settings/rules/steering-principles.md`
- Focus on patterns, not exhaustive lists
- Keep to 100-200 lines (2-3 minute read)
5. **Create file** in `.kiro/steering/{name}.md`
## Available Templates
Templates available in `.kiro/settings/templates/steering-custom/`:
1. **api-standards.md** - REST/GraphQL conventions, error handling
2. **testing.md** - Test organization, mocking, coverage
3. **security.md** - Auth patterns, input validation, secrets
4. **database.md** - Schema design, migrations, query patterns
5. **error-handling.md** - Error types, logging, retry strategies
6. **authentication.md** - Auth flows, permissions, session management
7. **deployment.md** - CI/CD, environments, rollback procedures
Load template when needed, customize for project.
## Steering Principles
From `.kiro/settings/rules/steering-principles.md`:
- **Patterns over lists**: Document patterns, not every file/component
- **Single domain**: One topic per file
- **Concrete examples**: Show patterns with code
- **Maintainable size**: 100-200 lines typical
- **Security first**: Never include secrets or sensitive data
</instructions>
## Tool guidance
- **Read**: Load template, analyze existing code
- **Glob**: Find related files for pattern analysis
- **Grep**: Search for specific patterns
- **LS**: Understand relevant structure
**JIT Strategy**: Load template only when creating that type of steering.
## Output description
Chat summary with file location (file created directly).
```
✅ Custom Steering Created
## Created:
- .kiro/steering/api-standards.md
## Based On:
- Template: api-standards.md
- Analyzed: src/api/ directory patterns
- Extracted: REST conventions, error format
## Content:
- Endpoint naming patterns
- Request/response format
- Error handling conventions
- Authentication approach
Review and customize as needed.
```
## Examples
### Success: API Standards
**Input**: "Create API standards steering"
**Action**: Load template, analyze src/api/, extract patterns
**Output**: api-standards.md with project-specific REST conventions
### Success: Testing Strategy
**Input**: "Document our testing approach"
**Action**: Load template, analyze test files, extract patterns
**Output**: testing.md with test organization and mocking strategies
## Safety & Fallback
- **No template**: Generate from scratch based on domain knowledge
- **Security**: Never include secrets (load principles)
- **Validation**: Ensure doesn't duplicate core steering content
## Notes
- Templates are starting points, customize for project
- Follow same granularity principles as core steering
- All steering files loaded as project memory
- Custom files equally important as core files
- Avoid documenting agent-specific tooling directories (e.g. `.cursor/`, `.gemini/`, `.claude/`)
- Light references to `.kiro/specs/` and `.kiro/steering/` are acceptable; avoid other `.kiro/` directories

View File

@ -0,0 +1,143 @@
---
description: Manage .kiro/steering/ as persistent project knowledge
allowed-tools: Bash, Read, Write, Edit, MultiEdit, Glob, Grep, LS
---
# Kiro Steering Management
<background_information>
**Role**: Maintain `.kiro/steering/` as persistent project memory.
**Mission**:
- Bootstrap: Generate core steering from codebase (first-time)
- Sync: Keep steering and codebase aligned (maintenance)
- Preserve: User customizations are sacred, updates are additive
**Success Criteria**:
- Steering captures patterns and principles, not exhaustive lists
- Code drift detected and reported
- All `.kiro/steering/*.md` treated equally (core + custom)
</background_information>
<instructions>
## Scenario Detection
Check `.kiro/steering/` status:
**Bootstrap Mode**: Empty OR missing core files (product.md, tech.md, structure.md)
**Sync Mode**: All core files exist
---
## Bootstrap Flow
1. Load templates from `.kiro/settings/templates/steering/`
2. Analyze codebase (JIT):
- `glob_file_search` for source files
- `read_file` for README, package.json, etc.
- `grep` for patterns
3. Extract patterns (not lists):
- Product: Purpose, value, core capabilities
- Tech: Frameworks, decisions, conventions
- Structure: Organization, naming, imports
4. Generate steering files (follow templates)
5. Load principles from `.kiro/settings/rules/steering-principles.md`
6. Present summary for review
**Focus**: Patterns that guide decisions, not catalogs of files/dependencies.
---
## Sync Flow
1. Load all existing steering (`.kiro/steering/*.md`)
2. Analyze codebase for changes (JIT)
3. Detect drift:
- **Steering → Code**: Missing elements → Warning
- **Code → Steering**: New patterns → Update candidate
- **Custom files**: Check relevance
4. Propose updates (additive, preserve user content)
5. Report: Updates, warnings, recommendations
**Update Philosophy**: Add, don't replace. Preserve user sections.
---
## Granularity Principle
From `.kiro/settings/rules/steering-principles.md`:
> "If new code follows existing patterns, steering shouldn't need updating."
Document patterns and principles, not exhaustive lists.
**Bad**: List every file in directory tree
**Good**: Describe organization pattern with examples
</instructions>
## Tool guidance
- `glob_file_search`: Find source/config files
- `read_file`: Read steering, docs, configs
- `grep`: Search patterns
- `list_dir`: Analyze structure
**JIT Strategy**: Fetch when needed, not upfront.
## Output description
Chat summary only (files updated directly).
### Bootstrap:
```
✅ Steering Created
## Generated:
- product.md: [Brief description]
- tech.md: [Key stack]
- structure.md: [Organization]
Review and approve as Source of Truth.
```
### Sync:
```
✅ Steering Updated
## Changes:
- tech.md: React 18 → 19
- structure.md: Added API pattern
## Code Drift:
- Components not following import conventions
## Recommendations:
- Consider api-standards.md
```
## Examples
### Bootstrap
**Input**: Empty steering, React TypeScript project
**Output**: 3 files with patterns - "Feature-first", "TypeScript strict", "React 19"
### Sync
**Input**: Existing steering, new `/api` directory
**Output**: Updated structure.md, flagged non-compliant files, suggested api-standards.md
## Safety & Fallback
- **Security**: Never include keys, passwords, secrets (see principles)
- **Uncertainty**: Report both states, ask user
- **Preservation**: Add rather than replace when in doubt
## Notes
- All `.kiro/steering/*.md` loaded as project memory
- Templates and principles are external for customization
- Focus on patterns, not catalogs
- "Golden Rule": New code following patterns shouldn't require steering updates
- Avoid documenting agent-specific tooling directories (e.g. `.cursor/`, `.gemini/`, `.claude/`)
- `.kiro/settings/` content should NOT be documented in steering files (settings are metadata, not project knowledge)
- Light references to `.kiro/specs/` and `.kiro/steering/` are acceptable; avoid other `.kiro/` directories

View File

@ -0,0 +1,92 @@
---
description: Interactive technical design quality review and validation
allowed-tools: Read, Glob, Grep
argument-hint: <feature-name>
---
# Technical Design Validation
<background_information>
- **Mission**: Conduct interactive quality review of technical design to ensure readiness for implementation
- **Success Criteria**:
- Critical issues identified (maximum 3 most important concerns)
- Balanced assessment with strengths recognized
- Clear GO/NO-GO decision with rationale
- Actionable feedback for improvements if needed
</background_information>
<instructions>
## Core Task
Interactive design quality review for feature **$1** based on approved requirements and design document.
## Execution Steps
1. **Load Context**:
- Read `.kiro/specs/$1/spec.json` for language and metadata
- Read `.kiro/specs/$1/requirements.md` for requirements
- Read `.kiro/specs/$1/design.md` for design document
- **Load ALL steering context**: Read entire `.kiro/steering/` directory including:
- Default files: `structure.md`, `tech.md`, `product.md`
- All custom steering files (regardless of mode settings)
- This provides complete project memory and context
2. **Read Review Guidelines**:
- Read `.kiro/settings/rules/design-review.md` for review criteria and process
3. **Execute Design Review**:
- Follow design-review.md process: Analysis → Critical Issues → Strengths → GO/NO-GO
- Limit to 3 most important concerns
- Engage interactively with user
- Use language specified in spec.json for output
4. **Provide Decision and Next Steps**:
- Clear GO/NO-GO decision with rationale
- Guide user on proceeding based on decision
## Important Constraints
- **Quality assurance, not perfection seeking**: Accept acceptable risk
- **Critical focus only**: Maximum 3 issues, only those significantly impacting success
- **Interactive approach**: Engage in dialogue, not one-way evaluation
- **Balanced assessment**: Recognize both strengths and weaknesses
- **Actionable feedback**: All suggestions must be implementable
</instructions>
## Tool Guidance
- **Read first**: Load all context (spec, steering, rules) before review
- **Grep if needed**: Search codebase for pattern validation or integration checks
- **Interactive**: Engage with user throughout the review process
## Output Description
Provide output in the language specified in spec.json with:
1. **Review Summary**: Brief overview (2-3 sentences) of design quality and readiness
2. **Critical Issues**: Maximum 3, following design-review.md format
3. **Design Strengths**: 1-2 positive aspects
4. **Final Assessment**: GO/NO-GO decision with rationale and next steps
**Format Requirements**:
- Use Markdown headings for clarity
- Follow design-review.md output format
- Keep summary concise
## Safety & Fallback
### Error Scenarios
- **Missing Design**: If design.md doesn't exist, stop with message: "Run `/kiro:spec-design $1` first to generate design document"
- **Design Not Generated**: If design phase not marked as generated in spec.json, warn but proceed with review
- **Empty Steering Directory**: Warn user that project context is missing and may affect review quality
- **Language Undefined**: Default to English (`en`) if spec.json doesn't specify language
### Next Phase: Task Generation
**If Design Passes Validation (GO Decision)**:
- Review feedback and apply changes if needed
- Run `/kiro:spec-tasks $1` to generate implementation tasks
- Or `/kiro:spec-tasks $1 -y` to auto-approve and proceed directly
**If Design Needs Revision (NO-GO Decision)**:
- Address critical issues identified
- Re-run `/kiro:spec-design $1` with improvements
- Re-validate with `/kiro:validate-design $1`
**Note**: Design validation is recommended but optional. Quality review helps catch issues early.

View File

@ -0,0 +1,88 @@
---
description: Analyze implementation gap between requirements and existing codebase
allowed-tools: Bash, Glob, Grep, Read, Write, Edit, MultiEdit, WebSearch, WebFetch
argument-hint: <feature-name>
---
# Implementation Gap Validation
<background_information>
- **Mission**: Analyze the gap between requirements and existing codebase to inform implementation strategy
- **Success Criteria**:
- Comprehensive understanding of existing codebase patterns and components
- Clear identification of missing capabilities and integration challenges
- Multiple viable implementation approaches evaluated
- Technical research needs identified for design phase
</background_information>
<instructions>
## Core Task
Analyze implementation gap for feature **$1** based on approved requirements and existing codebase.
## Execution Steps
1. **Load Context**:
- Read `.kiro/specs/$1/spec.json` for language and metadata
- Read `.kiro/specs/$1/requirements.md` for requirements
- **Load ALL steering context**: Read entire `.kiro/steering/` directory including:
- Default files: `structure.md`, `tech.md`, `product.md`
- All custom steering files (regardless of mode settings)
- This provides complete project memory and context
2. **Read Analysis Guidelines**:
- Read `.kiro/settings/rules/gap-analysis.md` for comprehensive analysis framework
3. **Execute Gap Analysis**:
- Follow gap-analysis.md framework for thorough investigation
- Analyze existing codebase using Grep and Read tools
- Use WebSearch/WebFetch for external dependency research if needed
- Evaluate multiple implementation approaches (extend/new/hybrid)
- Use language specified in spec.json for output
4. **Generate Analysis Document**:
- Create comprehensive gap analysis following the output guidelines in gap-analysis.md
- Present multiple viable options with trade-offs
- Flag areas requiring further research
## Important Constraints
- **Information over Decisions**: Provide analysis and options, not final implementation choices
- **Multiple Options**: Present viable alternatives when applicable
- **Thorough Investigation**: Use tools to deeply understand existing codebase
- **Explicit Gaps**: Clearly flag areas needing research or investigation
</instructions>
## Tool Guidance
- **Read first**: Load all context (spec, steering, rules) before analysis
- **Grep extensively**: Search codebase for patterns, conventions, and integration points
- **WebSearch/WebFetch**: Research external dependencies and best practices when needed
- **Write last**: Generate analysis only after complete investigation
## Output Description
Provide output in the language specified in spec.json with:
1. **Analysis Summary**: Brief overview (3-5 bullets) of scope, challenges, and recommendations
2. **Document Status**: Confirm analysis approach used
3. **Next Steps**: Guide user on proceeding to design phase
**Format Requirements**:
- Use Markdown headings for clarity
- Keep summary concise (under 300 words)
- Detailed analysis follows gap-analysis.md output guidelines
## Safety & Fallback
### Error Scenarios
- **Missing Requirements**: If requirements.md doesn't exist, stop with message: "Run `/kiro:spec-requirements $1` first to generate requirements"
- **Requirements Not Approved**: If requirements not approved, warn user but proceed (gap analysis can inform requirement revisions)
- **Empty Steering Directory**: Warn user that project context is missing and may affect analysis quality
- **Complex Integration Unclear**: Flag for comprehensive research in design phase rather than blocking
- **Language Undefined**: Default to English (`en`) if spec.json doesn't specify language
### Next Phase: Design Generation
**If Gap Analysis Complete**:
- Review gap analysis insights
- Run `/kiro:spec-design $1` to create technical design document
- Or `/kiro:spec-design $1 -y` to auto-approve requirements and proceed directly
**Note**: Gap analysis is optional but recommended for brownfield projects to inform design decisions.

View File

@ -0,0 +1,138 @@
---
description: Validate implementation against requirements, design, and tasks
allowed-tools: Bash, Glob, Grep, Read, LS
argument-hint: [feature-name] [task-numbers]
---
# Implementation Validation
<background_information>
- **Mission**: Verify that implementation aligns with approved requirements, design, and tasks
- **Success Criteria**:
- All specified tasks marked as completed
- Tests exist and pass for implemented functionality
- Requirements traceability confirmed (EARS requirements covered)
- Design structure reflected in implementation
- No regressions in existing functionality
</background_information>
<instructions>
## Core Task
Validate implementation for feature(s) and task(s) based on approved specifications.
## Execution Steps
### 1. Detect Validation Target
**If no arguments provided** (`$1` empty):
- Parse conversation history for `/kiro:spec-impl <feature> [tasks]` commands
- Extract feature names and task numbers from each execution
- Aggregate all implemented tasks by feature
- Report detected implementations (e.g., "user-auth: 1.1, 1.2, 1.3")
- If no history found, scan `.kiro/specs/` for features with completed tasks `[x]`
**If feature provided** (`$1` present, `$2` empty):
- Use specified feature
- Detect all completed tasks `[x]` in `.kiro/specs/$1/tasks.md`
**If both feature and tasks provided** (`$1` and `$2` present):
- Validate specified feature and tasks only (e.g., `user-auth 1.1,1.2`)
### 2. Load Context
For each detected feature:
- Read `.kiro/specs/<feature>/spec.json` for metadata
- Read `.kiro/specs/<feature>/requirements.md` for requirements
- Read `.kiro/specs/<feature>/design.md` for design structure
- Read `.kiro/specs/<feature>/tasks.md` for task list
- **Load ALL steering context**: Read entire `.kiro/steering/` directory including:
- Default files: `structure.md`, `tech.md`, `product.md`
- All custom steering files (regardless of mode settings)
### 3. Execute Validation
For each task, verify:
#### Task Completion Check
- Checkbox is `[x]` in tasks.md
- If not completed, flag as "Task not marked complete"
#### Test Coverage Check
- Tests exist for task-related functionality
- Tests pass (no failures or errors)
- Use Bash to run test commands (e.g., `npm test`, `pytest`)
- If tests fail or don't exist, flag as "Test coverage issue"
#### Requirements Traceability
- Identify EARS requirements related to the task
- Use Grep to search implementation for evidence of requirement coverage
- If requirement not traceable to code, flag as "Requirement not implemented"
#### Design Alignment
- Check if design.md structure is reflected in implementation
- Verify key interfaces, components, and modules exist
- Use Grep/LS to confirm file structure matches design
- If misalignment found, flag as "Design deviation"
#### Regression Check
- Run full test suite (if available)
- Verify no existing tests are broken
- If regressions detected, flag as "Regression detected"
### 4. Generate Report
Provide summary in the language specified in spec.json:
- Validation summary by feature
- Coverage report (tasks, requirements, design)
- Issues and deviations with severity (Critical/Warning)
- GO/NO-GO decision
## Important Constraints
- **Conversation-aware**: Prioritize conversation history for auto-detection
- **Non-blocking warnings**: Design deviations are warnings unless critical
- **Test-first focus**: Test coverage is mandatory for GO decision
- **Traceability required**: All requirements must be traceable to implementation
</instructions>
## Tool Guidance
- **Conversation parsing**: Extract `/kiro:spec-impl` patterns from history
- **Read context**: Load all specs and steering before validation
- **Bash for tests**: Execute test commands to verify pass status
- **Grep for traceability**: Search codebase for requirement evidence
- **LS/Glob for structure**: Verify file structure matches design
## Output Description
Provide output in the language specified in spec.json with:
1. **Detected Target**: Features and tasks being validated (if auto-detected)
2. **Validation Summary**: Brief overview per feature (pass/fail counts)
3. **Issues**: List of validation failures with severity and location
4. **Coverage Report**: Requirements/design/task coverage percentages
5. **Decision**: GO (ready for next phase) / NO-GO (needs fixes)
**Format Requirements**:
- Use Markdown headings and tables for clarity
- Flag critical issues with ⚠️ or 🔴
- Keep summary concise (under 400 words)
## Safety & Fallback
### Error Scenarios
- **No Implementation Found**: If no `/kiro:spec-impl` in history and no `[x]` tasks, report "No implementations detected"
- **Test Command Unknown**: If test framework unclear, warn and skip test validation (manual verification required)
- **Missing Spec Files**: If spec.json/requirements.md/design.md missing, stop with error
- **Language Undefined**: Default to English (`en`) if spec.json doesn't specify language
### Next Steps Guidance
**If GO Decision**:
- Implementation validated and ready
- Proceed to deployment or next feature
**If NO-GO Decision**:
- Address critical issues listed
- Re-run `/kiro:spec-impl <feature> [tasks]` for fixes
- Re-validate with `/kiro:validate-impl [feature] [tasks]`
**Note**: Validation is recommended after implementation to ensure spec alignment and quality.

64
.claude/commands/plan.md Normal file
View File

@ -0,0 +1,64 @@
---
description: Plan a feature or fix using Spec-Driven Development (CC-SDD / Kiro). Mandatory before code.
argument-hint: [task-description] (optional — falls back to the active ticket)
---
# /plan — Plan before you code (MANDATORY)
You are running the `/plan` slash command. The user typed:
```
/plan $ARGUMENTS
```
**Rule:** No feature without a plan. No code without an approved plan. This command sets up a spec via CC-SDD (Kiro) and walks the user through Requirements → Design → Tasks before any implementation.
## Step 0 — Determine the source description
1. If `$ARGUMENTS` is non-empty → use it verbatim as the task description.
2. Otherwise, look for ticket snapshots in `.ticket/`:
- List files matching `.ticket/*.md` excluding `repo.md` and `.gitkeep`.
- If exactly one snapshot exists → use the body of that ticket as the description (and report which ticket).
- If multiple exist → ask the user which one (`#42`, `#17`, …).
- If none exist → ask the user "What should I plan?" and stop until they answer.
Treat the resulting text as **the task brief** for the rest of this command.
## Step 1 — Activate Plan Mode
Stay in research/read-only mode for the rest of this command. **Do not edit production code, do not run migrations, do not write code files outside `.kiro/specs/`.** Reading code, running `gh`, and creating files under `.kiro/specs/` are permitted.
## Step 2 — Run the Kiro spec flow
Invoke the Kiro slash commands installed by `cc-sdd` (in `.claude/commands/kiro/`). The expected sequence is:
1. **`/kiro:steering`** — only if `.kiro/steering/` is empty. Establishes product/tech/structure steering docs from the codebase. Skip if steering already exists.
2. **`/kiro:spec-init <task brief>`** — creates `.kiro/specs/<feature>/` with `spec.json` and `requirements.md` skeleton.
3. **`/kiro:spec-requirements`** — fills in requirements (EARS format).
4. **`/kiro:validate-gap`** — gap-analysis review of requirements before design (recommended in the project workflow).
5. **`/kiro:spec-design`** — produce the design document.
6. **`/kiro:validate-design`** — design-review gate.
7. **`/kiro:spec-tasks`** — break the design into tasks with parallel-work analysis.
After each Kiro command, **show the resulting artefact and stop for human approval** before moving to the next phase. The plan is not approved until the user explicitly says so.
## Step 3 — Persistence
CC-SDD stores everything under `.kiro/specs/<feature>/`. Do not duplicate plans elsewhere — that directory is the source of truth.
If a `.ticket/<n>.md` snapshot is associated with this work, link it from `spec.json` (or note the ticket number in `requirements.md`) so the trace from issue → spec is preserved.
## Step 4 — Implementation handoff
Implementation is **a separate, explicit step**:
- Use **`/kiro:spec-impl`** to execute tasks against the approved plan.
- Check progress against the plan **after every task** (the project's chosen checkpoint cadence).
- Use **`/kiro:validate-impl`** at the end to verify the implementation matches the spec.
- Use **`/kiro:spec-status`** at any time to see where the spec stands.
If the user asks to "just code it" without going through the spec, push back and remind them of the rule. Approval first, then code.
## Output expectation
Be terse. State which step you ran, what artefact it produced, and what the user needs to review. One short paragraph per phase, not a wall of text.

View File

@ -1,33 +1,79 @@
#!/usr/bin/env bash
# SessionStart hook — print branch + working-tree status to give Claude
# (and the developer) immediate context at the start of a session.
# SessionStart hook — print branch + working-tree status + open Kiro
# specs / cached tickets so context is visible immediately at the start
# of a session.
set -euo pipefail
# Run only inside a git repo
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
exit 0
PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"
# --- Git branch + state -----------------------------------------------------
if git -C "$PROJECT_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
branch="$(git -C "$PROJECT_DIR" symbolic-ref --short HEAD 2>/dev/null || echo 'detached')"
upstream="$(git -C "$PROJECT_DIR" rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || echo '')"
ahead_behind=""
if [ -n "$upstream" ]; then
counts="$(git -C "$PROJECT_DIR" rev-list --left-right --count "${upstream}...HEAD" 2>/dev/null || echo '0 0')"
behind="$(echo "$counts" | awk '{print $1}')"
ahead="$(echo "$counts" | awk '{print $2}')"
if [ "$ahead" != "0" ] || [ "$behind" != "0" ]; then
ahead_behind=" (ahead $ahead, behind $behind vs $upstream)"
fi
fi
dirty_count="$(git -C "$PROJECT_DIR" status --porcelain 2>/dev/null | wc -l | tr -d ' ')"
if [ "$dirty_count" = "0" ]; then
state="clean"
else
state="$dirty_count uncommitted change(s)"
fi
echo "📍 Branch: ${branch}${ahead_behind}${state}"
fi
branch="$(git symbolic-ref --short HEAD 2>/dev/null || echo 'detached')"
upstream="$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || echo '')"
# --- Active tickets ---------------------------------------------------------
shopt -s nullglob 2>/dev/null || true
tickets=("$PROJECT_DIR"/.ticket/*.md)
ticket_list=()
for f in "${tickets[@]}"; do
base="$(basename "$f")"
case "$base" in
repo.md|.gitkeep) continue ;;
*) ticket_list+=("${base%.md}") ;;
esac
done
if [ "${#ticket_list[@]}" -gt 0 ]; then
echo "🎫 Active tickets: ${ticket_list[*]} (use /ticket <n> to add more)"
fi
# Ahead / behind vs upstream
ahead_behind=""
if [ -n "$upstream" ]; then
counts="$(git rev-list --left-right --count "${upstream}...HEAD" 2>/dev/null || echo '0 0')"
behind="$(echo "$counts" | awk '{print $1}')"
ahead="$(echo "$counts" | awk '{print $2}')"
if [ "$ahead" != "0" ] || [ "$behind" != "0" ]; then
ahead_behind=" (ahead $ahead, behind $behind vs $upstream)"
# --- Active Kiro specs ------------------------------------------------------
if [ -d "$PROJECT_DIR/.kiro/specs" ]; then
spec_dirs=("$PROJECT_DIR"/.kiro/specs/*/)
spec_list=()
for d in "${spec_dirs[@]}"; do
[ -d "$d" ] || continue
name="$(basename "$d")"
# Try to read phase from spec.json if jq/python is available
phase=""
if [ -f "$d/spec.json" ] && command -v python3 >/dev/null 2>&1; then
phase="$(python3 -c "
import json, sys
try:
with open(sys.argv[1]) as f: d = json.load(f)
print(d.get('phase') or d.get('status') or '', end='')
except Exception:
pass
" "$d/spec.json" 2>/dev/null || true)"
fi
if [ -n "$phase" ]; then
spec_list+=("$name [$phase]")
else
spec_list+=("$name")
fi
done
if [ "${#spec_list[@]}" -gt 0 ]; then
echo "📘 Open specs: $(printf '%s, ' "${spec_list[@]}" | sed 's/, $//') (use /plan or /kiro:spec-status)"
fi
fi
# Working-tree status
dirty_count="$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')"
if [ "$dirty_count" = "0" ]; then
state="clean"
else
state="$dirty_count uncommitted change(s)"
fi
echo "📍 Branch: ${branch}${ahead_behind}${state}"
exit 0

View File

@ -0,0 +1,73 @@
# Step 4 — Planning Tool Decision
## Date: 2026-05-06
## Decisions
| Question | Choice |
|----------|--------|
| Q1 — Planning tool | **CC-SDD** (Claude Code Spec Driven Development, Kiro flow). Recommended in the Salestech onboarding doc and matches the project's expected `spec-init → spec-design → spec-tasks → spec-impl → spec-validate` workflow. |
| Q2 — Plan persistence | **In-tool**`.kiro/specs/<feature>/`. CC-SDD owns this directory; no parallel `.claude/plans/` needed. |
| Q3 — Checkpoint cadence | **After every task** — strictest setting; matches the project rule "no code without an approved plan". |
## What CC-SDD installed
The user ran `npx cc-sdd@latest --claude --lang en` in the terminal.
The installer added:
- **`.kiro/settings/`** — rules and templates that drive the Kiro flow:
- `rules/` — design-discovery, EARS format, requirements/design review gates, gap analysis, steering principles, tasks generation, parallel-analysis.
- `templates/specs/``requirements.md`, `design.md`, `tasks.md`, `research.md`, `init.json`, `requirements-init.md`.
- `templates/steering/``product.md`, `tech.md`, `structure.md`.
- `templates/steering-custom/` — optional steering docs (api-standards, auth, db, deployment, error-handling, security, testing).
- **`.claude/commands/kiro/`** — slash commands invoked by the Kiro flow:
- `/kiro:steering`, `/kiro:steering-custom`
- `/kiro:spec-init`, `/kiro:spec-requirements`, `/kiro:spec-design`, `/kiro:spec-tasks`, `/kiro:spec-impl`, `/kiro:spec-status`
- `/kiro:validate-gap`, `/kiro:validate-design`, `/kiro:validate-impl`
Notes:
- The installer **did not append to `CLAUDE.md`** in this run, so no
refactor was needed afterwards. (Some CC-SDD versions append; this
one didn't.)
- `.kiro/` is **not** gitignored — specs and steering docs are project
artefacts that need to be shared with the team.
## Slash command added: `/plan`
Created `.claude/commands/plan.md`. Behaviour:
1. **Source description**: uses `$ARGUMENTS`, or falls back to a single
`.ticket/<n>.md` snapshot, or asks the user.
2. **Plan mode**: read-only research; no production-code edits.
3. **Kiro flow**:
`/kiro:steering` (only if `.kiro/steering/` is empty) →
`/kiro:spec-init``/kiro:spec-requirements`
`/kiro:validate-gap``/kiro:spec-design`
`/kiro:validate-design``/kiro:spec-tasks`.
**Stops for human approval after each artefact.**
4. **Persistence**: in `.kiro/specs/<feature>/`. Ticket linkage noted
in `spec.json` / `requirements.md`.
5. **Implementation handoff**: separate, explicit step using
`/kiro:spec-impl`, with `/kiro:validate-impl` at the end and
`/kiro:spec-status` for progress checks.
The command rejects "just code it" requests — approval-first is
enforced.
## SessionStart hook extended
`.claude/hooks/session_start.sh` now also prints:
- **Active tickets** — issue numbers cached under `.ticket/` (excludes
`repo.md`/`.gitkeep`).
- **Open specs** — directory names under `.kiro/specs/`, with phase /
status pulled from each `spec.json` if available.
The branch + working-tree-state line is preserved.
## Open follow-ups
- **Run `/kiro:steering`** in a new Claude session to seed `.kiro/steering/` with product/tech/structure context (recommended in brownfield setups). Out of scope for this onboarding pass — flagged for the developer.
- The Stop hook (quality gate around plans / tests / lint) is built in **Step 6**.
## Next
- Step 5: Agents & Skills (subagents, skills, rules from tech-stack).

View File

@ -0,0 +1,93 @@
# Full Discovery Process for Technical Design
## Objective
Conduct comprehensive research and analysis to ensure the technical design is based on complete, accurate, and up-to-date information.
## Discovery Steps
### 1. Requirements Analysis
**Map Requirements to Technical Needs**
- Extract all functional requirements from EARS format
- Identify non-functional requirements (performance, security, scalability)
- Determine technical constraints and dependencies
- List core technical challenges
### 2. Existing Implementation Analysis
**Understand Current System** (if modifying/extending):
- Analyze codebase structure and architecture patterns
- Map reusable components, services, utilities
- Identify domain boundaries and data flows
- Document integration points and dependencies
- Determine approach: extend vs refactor vs wrap
### 3. Technology Research
**Investigate Best Practices and Solutions**:
- **Use WebSearch** to find:
- Latest architectural patterns for similar problems
- Industry best practices for the technology stack
- Recent updates or changes in relevant technologies
- Common pitfalls and solutions
- **Use WebFetch** to analyze:
- Official documentation for frameworks/libraries
- API references and usage examples
- Migration guides and breaking changes
- Performance benchmarks and comparisons
### 4. External Dependencies Investigation
**For Each External Service/Library**:
- Search for official documentation and GitHub repositories
- Verify API signatures and authentication methods
- Check version compatibility with existing stack
- Investigate rate limits and usage constraints
- Find community resources and known issues
- Document security considerations
- Note any gaps requiring implementation investigation
### 5. Architecture Pattern & Boundary Analysis
**Evaluate Architectural Options**:
- Compare relevant patterns (MVC, Clean, Hexagonal, Event-driven)
- Assess fit with existing architecture and steering principles
- Identify domain boundaries and ownership seams required to avoid team conflicts
- Consider scalability implications and operational concerns
- Evaluate maintainability and team expertise
- Document preferred pattern and rejected alternatives in `research.md`
### 6. Risk Assessment
**Identify Technical Risks**:
- Performance bottlenecks and scaling limits
- Security vulnerabilities and attack vectors
- Integration complexity and coupling
- Technical debt creation vs resolution
- Knowledge gaps and training needs
## Research Guidelines
### When to Search
**Always search for**:
- External API documentation and updates
- Security best practices for authentication/authorization
- Performance optimization techniques for identified bottlenecks
- Latest versions and migration paths for dependencies
**Search if uncertain about**:
- Architectural patterns for specific use cases
- Industry standards for data formats/protocols
- Compliance requirements (GDPR, HIPAA, etc.)
- Scalability approaches for expected load
### Search Strategy
1. Start with official sources (documentation, GitHub)
2. Check recent blog posts and articles (last 6 months)
3. Review Stack Overflow for common issues
4. Investigate similar open-source implementations
## Output Requirements
Capture all findings that impact design decisions in `research.md` using the shared template:
- Key insights affecting architecture, technology alignment, and contracts
- Constraints discovered during research
- Recommended approaches and selected architecture pattern with rationale
- Rejected alternatives and trade-offs (documented in the Design Decisions section)
- Updated domain boundaries that inform Components & Interface Contracts
- Risks and mitigation strategies
- Gaps requiring further investigation during implementation

View File

@ -0,0 +1,49 @@
# Light Discovery Process for Extensions
## Objective
Quickly analyze existing system and integration requirements for feature extensions.
## Focused Discovery Steps
### 1. Extension Point Analysis
**Identify Integration Approach**:
- Locate existing extension points or interfaces
- Determine modification scope (files, components)
- Check for existing patterns to follow
- Identify backward compatibility requirements
### 2. Dependency Check
**Verify Compatibility**:
- Check version compatibility of new dependencies
- Validate API contracts haven't changed
- Ensure no breaking changes in pipeline
### 3. Quick Technology Verification
**For New Libraries Only**:
- Use WebSearch for official documentation
- Verify basic usage patterns
- Check for known compatibility issues
- Confirm licensing compatibility
- Record key findings in `research.md` (technology alignment section)
### 4. Integration Risk Assessment
**Quick Risk Check**:
- Impact on existing functionality
- Performance implications
- Security considerations
- Testing requirements
## When to Escalate to Full Discovery
Switch to full discovery if you find:
- Significant architectural changes needed
- Complex external service integrations
- Security-sensitive implementations
- Performance-critical components
- Unknown or poorly documented dependencies
## Output Requirements
- Clear integration approach (note boundary impacts in `research.md`)
- List of files/components to modify
- New dependencies with versions
- Integration risks and mitigations
- Testing focus areas

View File

@ -0,0 +1,198 @@
# Technical Design Rules and Principles
## Core Design Principles
### 0. Boundary First
- **Boundary is mandatory; owner is optional**
- A design is not ready when it explains components but leaves responsibility seams ambiguous
- Define what the spec owns before elaborating how it works
- Explicitly record what is out of boundary
- Do not leak downstream-specific behavior or assumptions into upstream boundaries
### 1. Type Safety is Mandatory
- **NEVER** use `any` type in TypeScript interfaces
- Define explicit types for all parameters and returns
- Use discriminated unions for error handling
- Specify generic constraints clearly
### 2. Design vs Implementation
- **Focus on WHAT, not HOW**
- Define interfaces and contracts, not code
- Specify behavior through pre/post conditions
- Document architectural decisions, not algorithms
### 3. Visual Communication
- **Simple features**: Basic component diagram or none
- **Medium complexity**: Architecture + data flow
- **High complexity**: Multiple diagrams (architecture, sequence, state)
- **Always pure Mermaid**: No styling, just structure
### 4. Component Design Rules
- **Single Responsibility**: One clear purpose per component
- **Clear Boundaries**: Explicit domain ownership
- **Boundary Commitments First**: Before detailing components, state the responsibility boundary this design commits to
- **Dependency Direction**: Follow architectural layers
- **Interface Segregation**: Minimal, focused interfaces
- **Team-safe Interfaces**: Design boundaries that allow parallel implementation without merge conflicts
- **No Hidden Shared Ownership**: If two areas appear to co-own the same behavior or data, the design is incomplete
- **Research Traceability**: Record boundary decisions and rationale in `research.md`
### 5. Data Modeling Standards
- **Domain First**: Start with business concepts
- **Consistency Boundaries**: Clear aggregate roots
- **Normalization**: Balance between performance and integrity
- **Evolution**: Plan for schema changes
### 6. Error Handling Philosophy
- **Fail Fast**: Validate early and clearly
- **Graceful Degradation**: Partial functionality over complete failure
- **User Context**: Actionable error messages
- **Observability**: Comprehensive logging and monitoring
### 7. Integration Patterns
- **Loose Coupling**: Minimize dependencies
- **Contract First**: Define interfaces before implementation
- **Versioning**: Plan for API evolution
- **Idempotency**: Design for retry safety
- **Contract Visibility**: Surface API and event contracts in design.md while linking extended details from `research.md`
### 8. Dependency Direction
- **Define and enforce the dependency direction** in the architecture section of design.md (e.g., Types → Config → Repository → Service → Runtime → UI)
- Each layer imports only from layers to its left — never upward
- This constraint is not a suggestion; implementation and review should treat violations as errors
- When the File Structure Plan maps files to components, the dependency direction determines which imports are allowed
## Documentation Standards
### Language and Tone
- **Declarative**: "The system authenticates users" not "The system should authenticate"
- **Precise**: Specific technical terms over vague descriptions
- **Concise**: Essential information only
- **Formal**: Professional technical writing
### Structure Requirements
- **Hierarchical**: Clear section organization
- **Traceable**: Requirements to components mapping
- **Complete**: All aspects covered for implementation
- **Consistent**: Uniform terminology throughout
- **Focused**: Keep design.md centered on architecture and contracts; move investigation logs and lengthy comparisons to `research.md`
## Section Authoring Guidance
### Global Ordering
- Default flow: Overview → Goals/Non-Goals → Boundary Commitments → Architecture → File Structure Plan → Components & Interfaces → Optional sections.
- Teams may swap Traceability earlier or place Data Models nearer Architecture when it improves clarity, but keep section headings intact.
- Within each section, follow **Summary → Scope → Decisions → Impacts/Risks** so reviewers can scan consistently.
### Requirement IDs
- Reference requirements as `2.1, 2.3` without prefixes (no “Requirement 2.1”).
- All requirements MUST have numeric IDs. If a requirement lacks a numeric ID, stop and fix `requirements.md` before continuing.
- Use `N.M`-style numeric IDs where `N` is the top-level requirement number from requirements.md (for example, Requirement 1 → 1.1, 1.2; Requirement 2 → 2.1, 2.2).
- Every component, task, and traceability row must reference the same canonical numeric ID.
### Technology Stack
- Include ONLY layers impacted by this feature (frontend, backend, data, messaging, infra).
- For each layer specify tool/library + version + the role it plays; push extended rationale, comparisons, or benchmarks to `research.md`.
- When extending an existing system, highlight deviations from the current stack and list new dependencies.
### System Flows
- Add diagrams only when they clarify behavior:
- **Sequence** for multi-step interactions
- **Process/State** for branching rules or lifecycle
- **Data/Event** for pipelines or async patterns
- Always use pure Mermaid. If no complex flow exists, omit the entire section.
### Requirements Traceability
- Use the standard table (`Requirement | Summary | Components | Interfaces | Flows`) to prove coverage.
- Collapse to bullet form only when a single requirement maps 1:1 to a component.
- Prefer the component summary table for simple mappings; reserve the full traceability table for complex or compliance-sensitive requirements.
- Re-run this mapping whenever requirements or components change to avoid drift.
### Components & Interfaces Authoring
- Boundary Commitments should already make the ownership seam explicit before this section begins.
- Group components by domain/layer and provide one block per component.
- Begin with a summary table listing Component, Domain, Intent, Requirement coverage, key dependencies, and selected contracts.
- Table fields: Intent (one line), Requirements (`2.1, 2.3`), Owner/Reviewers (optional).
- Dependencies table must mark each entry as Inbound/Outbound/External and assign Criticality (`P0` blocking, `P1` high-risk, `P2` informational).
- Summaries of external dependency research stay here; detailed investigation (API signatures, rate limits, migration notes) belongs in `research.md`.
- design.md must remain a self-contained reviewer artifact. Reference `research.md` only for background, and restate any conclusions or decisions here.
- Contracts: tick only the relevant types (Service/API/Event/Batch/State). Unchecked types should not appear later in the component section.
- Service interfaces must declare method signatures, inputs/outputs, and error envelopes. API/Event/Batch contracts require schema tables or bullet lists covering trigger, payload, delivery, idempotency.
- Use **Integration & Migration Notes**, **Validation Hooks**, and **Open Questions / Risks** to document rollout strategy, observability, and unresolved decisions.
- Detail density rules:
- **Full block**: components introducing new boundaries (logic hooks, shared services, external integrations, data layers).
- **Summary-only**: presentational/UI components with no new boundaries (plus a short Implementation Note if needed).
- Implementation Notes must combine Integration / Validation / Risks into a single bulleted subsection to reduce repetition.
- Prefer lists or inline descriptors for short data (dependencies, contract selections). Use tables only when comparing multiple items.
### Shared Interfaces & Props
- Define a base interface (e.g., `BaseUIPanelProps`) for recurring UI components and extend it per component to capture only the deltas.
- Hooks, utilities, and integration adapters that introduce new contracts should still include full TypeScript signatures.
- When reusing a base contract, reference it explicitly (e.g., “Extends `BaseUIPanelProps` with `onSubmitAnswer` callback”) instead of duplicating the code block.
### Data Models
- Domain Model covers aggregates, entities, value objects, domain events, and invariants. Add Mermaid diagrams only when relationships are non-trivial.
- Logical Data Model should articulate structure, indexing, sharding, and storage-specific considerations (event store, KV/wide-column) relevant to the change.
- Data Contracts & Integration section documents API payloads, event schemas, and cross-service synchronization patterns when the feature crosses boundaries.
- Lengthy type definitions or vendor-specific option objects should be placed in the Supporting References section within design.md, linked from the relevant section. Investigation notes stay in `research.md`.
- Supporting References usage is optional; only create it when keeping the content in the main body would reduce readability. All decisions must still appear in the main sections so design.md stands alone.
### Error/Testing/Security/Performance Sections
- Record only feature-specific decisions or deviations. Link or reference organization-wide standards (steering) for baseline practices instead of restating them.
### Diagram & Text Deduplication
- Do not restate diagram content verbatim in prose. Use the text to highlight key decisions, trade-offs, or impacts that are not obvious from the visual.
- When a decision is fully captured in the diagram annotations, a short “Key Decisions” bullet is sufficient.
### General Deduplication
- Avoid repeating the same information across Overview, Architecture, and Components. Reference earlier sections when context is identical.
- If a requirement/component relationship is captured in the summary table, do not rewrite it elsewhere unless extra nuance is added.
## Diagram Guidelines
### When to include a diagram
- **Architecture**: Use a structural diagram when 3+ components or external systems interact.
- **Sequence**: Draw a sequence diagram when calls/handshakes span multiple steps.
- **State / Flow**: Capture complex state machines or business flows in a dedicated diagram.
- **ER**: Provide an entity-relationship diagram for non-trivial data models.
- **Skip**: Minor one-component changes generally do not need diagrams.
### Mermaid requirements
```mermaid
graph TB
Client --> ApiGateway
ApiGateway --> ServiceA
ApiGateway --> ServiceB
ServiceA --> Database
```
- **Plain Mermaid only** avoid custom styling or unsupported syntax.
- **Node IDs** alphanumeric plus underscores only (e.g., `Client`, `ServiceA`). Do not use `@`, `/`, or leading `-`.
- **Labels** simple words. Do not embed parentheses `()`, square brackets `[]`, quotes `"`, or slashes `/`.
- ❌ `DnD[@dnd-kit/core]` → invalid ID (`@`).
- ❌ `UI[KanbanBoard(React)]` → invalid label (`()`).
- ✅ `DndKit[dnd-kit core]` → use plain text in labels, keep technology details in the accompanying description.
- Mermaid strict-mode will otherwise fail with errors like `Expecting 'SQE' ... got 'PS'`; remove punctuation from labels before rendering.
- **Edges** show data or control flow direction.
- **Groups** using Mermaid subgraphs to cluster related components is allowed; use it sparingly for clarity.
## Quality Metrics
### Design Completeness Checklist
- All requirements addressed
- No implementation details leaked
- Clear component boundaries
- Explicit error handling
- Comprehensive test strategy
- Security considered
- Performance targets defined
- Migration path clear (if applicable)
### Common Anti-patterns to Avoid
❌ Mixing design with implementation
❌ Vague interface definitions
❌ Missing error scenarios
❌ Ignored non-functional requirements
❌ Overcomplicated architectures
❌ Tight coupling between components
❌ Missing data consistency strategy
❌ Incomplete dependency analysis

View File

@ -0,0 +1,50 @@
# Design Review Gate
Before writing `design.md`, review the draft design and repair local issues until the design passes or a true spec gap is discovered.
## Requirements Coverage Review
- Every numeric requirement ID from `requirements.md` must appear in the design traceability mapping and be backed by one or more concrete components, contracts, flows, data models, or operational decisions.
- Every requirement that introduces an external dependency, integration point, runtime prerequisite, migration concern, observability need, security constraint, or performance target must be reflected explicitly in `design.md`.
- If coverage is missing because the design draft is incomplete, repair the draft and review again.
- If coverage cannot be completed cleanly because requirements are ambiguous, contradictory, or underspecified, stop and return to the requirements phase instead of inventing design detail.
## Architecture Readiness Review
- Component boundaries must be explicit enough that implementation tasks can be assigned without guessing ownership.
- Interfaces, contracts, state transitions, and integration boundaries must be concrete enough for implementation and validation.
- Build-vs-adopt decisions that materially affect architecture must be captured in `design.md`, with deeper investigation left in `research.md` when present.
- Runtime prerequisites, migrations, rollout constraints, validation hooks, and failure modes must be surfaced when they materially affect implementation order or risk.
## Boundary Readiness Review
- The design must explicitly state what this spec owns.
- The design must explicitly state what is out of boundary.
- Allowed dependencies must be concrete enough that reviewers can detect boundary violations later.
- If data, behavior, or integration responsibility appears shared across multiple areas without a clear seam, stop and repair the design.
- If downstream assumptions are embedded in upstream components "for convenience," stop and repair the design.
- If the boundary cannot be explained in a few direct bullets, it is probably still too vague for task generation.
- If the design reveals multiple independent responsibility seams that could move separately, stop and split the spec or return to roadmap discovery instead of forcing them into one spec.
## Executability Review
- The design must be implementable as a sequence of bounded tasks without hidden prerequisites.
- Parallel-safe boundaries should be visible where the architecture intends concurrent implementation.
- Avoid speculative abstraction: remove components, adapters, or interfaces that exist only for hypothetical future scope.
- If a section is too vague for tasks to reference directly, rewrite it before finalizing the design.
## Mechanical Checks
Before applying judgment, verify these mechanically:
- **Requirements traceability**: Extract all numeric requirement IDs from `requirements.md`. Scan the design draft for each ID. Report any IDs not found in the design.
- **Boundary section populated**: `Boundary Commitments`, `Out of Boundary`, `Allowed Dependencies`, and `Revalidation Triggers` must not be empty or placeholder-only.
- **File Structure Plan populated**: The File Structure Plan section must contain concrete file paths (not just "TBD" or empty). Scan for placeholder text in that section.
- **Boundary ↔ file structure alignment**: The File Structure Plan must reflect the stated responsibility boundary. If files imply broader ownership than the boundary section claims, report a mismatch.
- **No orphan components**: Every component mentioned in the design must appear in the File Structure Plan with a file path. Scan for component names that have no corresponding file entry.
## Review Loop
- Run mechanical checks first, then judgment-based review.
- If issues are local to the draft, repair the draft and re-run the review gate.
- Keep the loop bounded: no more than 2 review-and-repair passes before escalating a real spec gap.
- Write `design.md` only after the review gate passes.

View File

@ -0,0 +1,110 @@
# Design Review Process
## Objective
Conduct interactive quality review of technical design documents to ensure they are solid enough to proceed to implementation with acceptable risk.
## Review Philosophy
- **Quality assurance, not perfection seeking**
- **Critical focus**: Limit to 3 most important concerns
- **Interactive dialogue**: Engage with designer, not one-way evaluation
- **Balanced assessment**: Recognize strengths and weaknesses
- **Clear decision**: Definitive GO/NO-GO with rationale
## Scope & Non-Goals
- Scope: Evaluate the quality of the design document against project context and standards to decide GO/NO-GO.
- Non-Goals: Do not perform implementation-level design, deep technology research, or finalize technology choices. Defer such items to the design phase iteration.
## Core Review Criteria
### 1. Existing Architecture Alignment (Critical)
- Integration with existing system boundaries and layers
- Consistency with established architectural patterns
- Proper dependency direction and coupling management
- Alignment with current module organization
### 2. Design Consistency & Standards
- Adherence to project naming conventions and code standards
- Consistent error handling and logging strategies
- Uniform configuration and dependency management
- Alignment with established data modeling patterns
### 3. Extensibility & Maintainability
- Design flexibility for future requirements
- Clear separation of concerns and single responsibility
- Testability and debugging considerations
- Appropriate complexity for requirements
### 4. Type Safety & Interface Design
- Proper type definitions and interface contracts
- Avoidance of unsafe patterns (e.g., `any` in TypeScript)
- Clear API boundaries and data structures
- Input validation and error handling coverage
## Review Process
### Step 1: Analyze
Analyze design against all review criteria, focusing on critical issues impacting integration, maintainability, complexity, and requirements fulfillment.
### Step 2: Identify Critical Issues (≤3)
For each issue:
```
🔴 **Critical Issue [1-3]**: [Brief title]
**Concern**: [Specific problem]
**Impact**: [Why it matters]
**Suggestion**: [Concrete improvement]
**Traceability**: [Requirement ID/section from requirements.md]
**Evidence**: [Design doc section/heading]
```
### Step 3: Recognize Strengths
Acknowledge 1-2 strong aspects to maintain balanced feedback.
### Step 4: Decide GO/NO-GO
- **GO**: No critical architectural misalignment, requirements addressed, clear implementation path, acceptable risks
- **NO-GO**: Fundamental conflicts, critical gaps, high failure risk, disproportionate complexity
## Traceability & Evidence
- Link each critical issue to the relevant requirement(s) from `requirements.md` (ID or section).
- Cite evidence locations in the design document (section/heading, diagram, or artifact) to support the assessment.
- When applicable, reference constraints from steering context to justify the issue.
## Output Format
### Design Review Summary
2-3 sentences on overall quality and readiness.
### Critical Issues (≤3)
For each: Issue, Impact, Recommendation, Traceability (e.g., 1.1, 1.2), Evidence (design.md section).
### Design Strengths
1-2 positive aspects.
### Final Assessment
Decision (GO/NO-GO), Rationale (1-2 sentences), Next Steps.
### Interactive Discussion
Engage on designer's perspective, alternatives, clarifications, and necessary changes.
## Length & Focus
- Summary: 23 sentences
- Each critical issue: 57 lines total (including Issue/Impact/Recommendation/Traceability/Evidence)
- Overall review: keep concise (~400 words guideline)
## Review Guidelines
1. **Critical Focus**: Only flag issues that significantly impact success
2. **Constructive Tone**: Provide solutions, not just criticism
3. **Interactive Approach**: Engage in dialogue rather than one-way evaluation
4. **Balanced Assessment**: Recognize both strengths and weaknesses
5. **Clear Decision**: Make definitive GO/NO-GO recommendation
6. **Actionable Feedback**: Ensure all suggestions are implementable
## Final Checklist
- **Critical Issues ≤ 3** and each includes Impact and Recommendation
- **Traceability**: Each issue references requirement ID/section
- **Evidence**: Each issue cites design doc location
- **Decision**: GO/NO-GO with clear rationale and next steps

View File

@ -0,0 +1,29 @@
# Design Synthesis
After discovery and before writing the design document, apply these three lenses to the collected findings. This step requires the full picture — do not parallelize.
## 1. Generalization
Look across all requirements as a group. Identify cases where multiple requirements are variations of the same underlying problem.
- If feature A is a special case of a more general capability X, design X with an interface that naturally supports A (and potentially B, C later)
- Keep the implementation scope to what the current requirements demand — generalize the interface, not the implementation
- Record identified generalizations in `research.md` under Design Decisions
## 2. Build vs. Adopt
For each major component in the emerging design, ask: is this problem already solved?
- Search for established standards (RFCs, protocols), battle-tested libraries, or platform-native capabilities that address the requirement
- Prefer adopting existing solutions over building custom ones when they fit the requirements without significant adaptation
- If adopting: verify the solution is actively maintained, compatible with the project's stack (check steering), and meets non-functional requirements
- If building: document why existing solutions were rejected (capture in `research.md`)
## 3. Simplification
For each component and abstraction layer in the emerging design, ask: is this necessary?
- Remove components that exist "just in case" or for hypothetical future requirements not in the current spec
- Flatten unnecessary abstraction layers — if an interface has only one implementation with no foreseeable second, it may not need the indirection
- Prefer fewer, cohesive components over many fine-grained ones
- The right design is the smallest one that satisfies all requirements and remains extensible at the interface level

View File

@ -0,0 +1,49 @@
# EARS Format Guidelines
## Overview
EARS (Easy Approach to Requirements Syntax) is the standard format for acceptance criteria in spec-driven development.
EARS patterns describe the logical structure of a requirement (condition + subject + response) and are not tied to any particular natural language.
All acceptance criteria should be written in the target language configured for the specification (for example, `spec.json.language` / `en`).
Keep EARS trigger keywords and fixed phrases in English (`When`, `If`, `While`, `Where`, `The system shall`, `The [system] shall`) and localize only the variable parts (`[event]`, `[precondition]`, `[trigger]`, `[feature is included]`, `[response/action]`) into the target language. Do not interleave target-language text inside the trigger or fixed English phrases themselves.
## Primary EARS Patterns
### 1. Event-Driven Requirements
- **Pattern**: When [event], the [system] shall [response/action]
- **Use Case**: Responses to specific events or triggers
- **Example**: When user clicks checkout button, the Checkout Service shall validate cart contents
### 2. State-Driven Requirements
- **Pattern**: While [precondition], the [system] shall [response/action]
- **Use Case**: Behavior dependent on system state or preconditions
- **Example**: While payment is processing, the Checkout Service shall display loading indicator
### 3. Unwanted Behavior Requirements
- **Pattern**: If [trigger], the [system] shall [response/action]
- **Use Case**: System response to errors, failures, or undesired situations
- **Example**: If invalid credit card number is entered, then the website shall display error message
### 4. Optional Feature Requirements
- **Pattern**: Where [feature is included], the [system] shall [response/action]
- **Use Case**: Requirements for optional or conditional features
- **Example**: Where the car has a sunroof, the car shall have a sunroof control panel
### 5. Ubiquitous Requirements
- **Pattern**: The [system] shall [response/action]
- **Use Case**: Always-active requirements and fundamental system properties
- **Example**: The mobile phone shall have a mass of less than 100 grams
## Combined Patterns
- While [precondition], when [event], the [system] shall [response/action]
- When [event] and [additional condition], the [system] shall [response/action]
## Subject Selection Guidelines
- **Software Projects**: Use concrete system/service name (e.g., "Checkout Service", "User Auth Module")
- **Process/Workflow**: Use responsible team/role (e.g., "Support Team", "Review Process")
- **Non-Software**: Use appropriate subject (e.g., "Marketing Campaign", "Documentation")
## Quality Criteria
- Requirements must be testable, verifiable, and describe a single behavior.
- Use objective language: "shall" for mandatory behavior, "should" for recommendations; avoid ambiguous terms.
- Follow EARS syntax: [condition], the [system] shall [response/action].

View File

@ -0,0 +1,144 @@
# Gap Analysis Process
## Objective
Analyze the gap between requirements and existing codebase to inform implementation strategy decisions.
## Analysis Framework
### 1. Current State Investigation
- Scan for domain-related assets:
- Key files/modules and directory layout
- Reusable components/services/utilities
- Dominant architecture patterns and constraints
- Extract conventions:
- Naming, layering, dependency direction
- Import/export patterns and dependency hotspots
- Testing placement and approach
- Note integration surfaces:
- Data models/schemas, API clients, auth mechanisms
### 2. Requirements Feasibility Analysis
- From EARS requirements, list technical needs:
- Data models, APIs/services, UI/components
- Business rules/validation
- Non-functionals: security, performance, scalability, reliability
- Identify gaps and constraints:
- Missing capabilities in current codebase
- Unknowns to be researched later (mark as "Research Needed")
- Constraints from existing architecture and patterns
- Note complexity signals:
- Simple CRUD / algorithmic logic / workflows / external integrations
### 3. Implementation Approach Options
#### Option A: Extend Existing Components
**When to consider**: Feature fits naturally into existing structure
- **Which files/modules to extend**:
- Identify specific files requiring changes
- Assess impact on existing functionality
- Evaluate backward compatibility concerns
- **Compatibility assessment**:
- Check if extension respects existing interfaces
- Verify no breaking changes to consumers
- Assess test coverage impact
- **Complexity and maintainability**:
- Evaluate cognitive load of additional functionality
- Check if single responsibility principle is maintained
- Assess if file size remains manageable
**Trade-offs**:
- ✅ Minimal new files, faster initial development
- ✅ Leverages existing patterns and infrastructure
- ❌ Risk of bloating existing components
- ❌ May complicate existing logic
#### Option B: Create New Components
**When to consider**: Feature has distinct responsibility or existing components are already complex
- **Rationale for new creation**:
- Clear separation of concerns justifies new file
- Existing components are already complex
- Feature has distinct lifecycle or dependencies
- **Integration points**:
- How new components connect to existing system
- APIs or interfaces exposed
- Dependencies on existing components
- **Responsibility boundaries**:
- Clear definition of what new component owns
- Interfaces with existing components
- Data flow and control flow
**Trade-offs**:
- ✅ Clean separation of concerns
- ✅ Easier to test in isolation
- ✅ Reduces complexity in existing components
- ❌ More files to navigate
- ❌ Requires careful interface design
#### Option C: Hybrid Approach
**When to consider**: Complex features requiring both extension and new creation
- **Combination strategy**:
- Which parts extend existing components
- Which parts warrant new components
- How they interact
- **Phased implementation**:
- Initial phase: minimal viable changes
- Subsequent phases: refactoring or new components
- Migration strategy if needed
- **Risk mitigation**:
- Incremental rollout approach
- Feature flags or configuration
- Rollback strategy
**Trade-offs**:
- ✅ Balanced approach for complex features
- ✅ Allows iterative refinement
- ❌ More complex planning required
- ❌ Potential for inconsistency if not well-coordinated
### 4. Out-of-Scope for Gap Analysis
- Defer deep research activities to the design phase.
- Record unknowns as concise "Research Needed" items only.
### 5. Implementation Complexity & Risk
- Effort:
- S (13 days): existing patterns, minimal deps, straightforward integration
- M (37 days): some new patterns/integrations, moderate complexity
- L (12 weeks): significant functionality, multiple integrations or workflows
- XL (2+ weeks): architectural changes, unfamiliar tech, broad impact
- Risk:
- High: unknown tech, complex integrations, architectural shifts, unclear perf/security path
- Medium: new patterns with guidance, manageable integrations, known perf solutions
- Low: extend established patterns, familiar tech, clear scope, minimal integration
### Output Checklist
- Requirement-to-Asset Map with gaps tagged (Missing / Unknown / Constraint)
- Options A/B/C with short rationale and trade-offs
- Effort (S/M/L/XL) and Risk (High/Medium/Low) with one-line justification each
- Recommendations for design phase:
- Preferred approach and key decisions
- Research items to carry forward
## Principles
- **Information over decisions**: Provide analysis and options, not final choices
- **Multiple viable options**: Offer credible alternatives when applicable
- **Explicit gaps and assumptions**: Flag unknowns and constraints clearly
- **Context-aware**: Align with existing patterns and architecture limits
- **Transparent effort and risk**: Justify labels succinctly

View File

@ -0,0 +1,51 @@
# Requirements Review Gate
Before writing `requirements.md`, review the draft requirements and repair local issues until the draft passes or a true scope ambiguity is discovered.
## Boundary Continuity
Use boundary terminology consistently across phases without turning requirements into design:
- **Discovery** identifies `Boundary Candidates`
- **Requirements** make inclusion, exclusion, and adjacent expectations explicit when scope could be misread
- **Design** turns those into `Boundary Commitments`
- **Tasks** use `_Boundary:_` to constrain executable work
Requirements should clarify the feature boundary in user- or operator-observable terms, not in architecture ownership or implementation detail.
## Scope and Coverage Review
- The draft must cover the feature's core user journeys, major scope boundaries, primary error cases, and meaningful edge conditions that are visible to the user or operator.
- If the feature touches adjacent systems, specs, or workflows, the draft must make clear what this feature expects from them and what it does not own when that distinction affects user-visible behavior or operator expectations.
- Business/domain rules, compliance constraints, security/privacy expectations, and operational constraints that materially shape user-visible behavior must be reflected explicitly when they are in scope.
- If coverage is missing because the draft is incomplete, repair the draft and review again.
- If coverage cannot be completed cleanly because the project description or steering context is ambiguous, contradictory, or underspecified, stop and ask the user to clarify instead of guessing.
## EARS and Testability Review
- Every acceptance criterion must follow the EARS rules defined in `ears-format.md`.
- Every requirement must be testable, observable, and specific enough that later design and validation can verify it.
- Remove implementation details that belong in `design.md` rather than `requirements.md`.
- Requirement headings must use numeric IDs only; do not mix numeric and alphabetic labels.
## Structure and Quality Review
- Group related behaviors into coherent requirement areas without duplicating the same obligation across multiple sections.
- Make inclusion/exclusion boundaries explicit when the feature scope could otherwise be misread.
- Keep boundary statements lightweight and observable: describe feature responsibility and adjacent expectations without prescribing components, layers, or internal ownership.
- Ensure non-functional expectations remain user-observable or operator-observable; move technology choices and internal architecture detail out of requirements.
- Normalize vague language such as "fast", "robust", or "secure" into concrete user-visible expectations whenever the source material supports it.
## Mechanical Checks
Before applying judgment, verify these mechanically:
- **Numeric IDs present**: Every requirement heading has a numeric ID (1, 1.1, 2, etc.). Scan the draft for headings without IDs.
- **Acceptance criteria exist**: Every requirement has at least one EARS-format acceptance criterion. Scan for requirements with no "When/If/While/Where" acceptance statements.
- **No implementation language**: Scan for technology-specific terms (database names, framework names, API patterns) that belong in design, not requirements. Flag any found.
## Review Loop
- Run mechanical checks first, then judgment-based review.
- If issues are local to the draft, repair the draft and re-run the review gate.
- Keep the loop bounded: no more than 2 review-and-repair passes before escalating a real ambiguity back to the user.
- Write `requirements.md` only after the review gate passes.

View File

@ -0,0 +1,90 @@
# Steering Principles
Steering files are **project memory**, not exhaustive specifications.
---
## Content Granularity
### Golden Rule
> "If new code follows existing patterns, steering shouldn't need updating."
### ✅ Document
- Organizational patterns (feature-first, layered)
- Naming conventions (PascalCase rules)
- Import strategies (absolute vs relative)
- Architectural decisions (state management)
- Technology standards (key frameworks)
### ❌ Avoid
- Complete file listings
- Every component description
- All dependencies
- Implementation details
- Agent-specific tooling directories (e.g. `.cursor/`, `.gemini/`, `.claude/`)
- Detailed documentation of `.kiro/` metadata directories (settings, automation)
### Example Comparison
**Bad** (Specification-like):
```markdown
- /components/Button.tsx - Primary button with variants
- /components/Input.tsx - Text input with validation
- /components/Modal.tsx - Modal dialog
... (50+ files)
```
**Good** (Project Memory):
```markdown
## UI Components (`/components/ui/`)
Reusable, design-system aligned primitives
- Named by function (Button, Input, Modal)
- Export component + TypeScript interface
- No business logic
```
---
## Security
Never include:
- API keys, passwords, credentials
- Database URLs, internal IPs
- Secrets or sensitive data
---
## Quality Standards
- **Single domain**: One topic per file
- **Concrete examples**: Show patterns with code
- **Explain rationale**: Why decisions were made
- **Maintainable size**: 100-200 lines typical
---
## Preservation (when updating)
- Preserve user sections and custom examples
- Additive by default (add, don't replace)
- Add `updated_at` timestamp
- Note why changes were made
---
## Notes
- Templates are starting points, customize as needed
- Follow same granularity principles as core steering
- All steering files loaded as project memory
- Light references to `.kiro/specs/` and `.kiro/steering/` are acceptable; avoid other `.kiro/` directories
- Custom files equally important as core files
---
## File-Specific Focus
- **product.md**: Purpose, value, business context (not exhaustive features)
- **tech.md**: Key frameworks, standards, conventions (not all dependencies)
- **structure.md**: Organization patterns, naming rules (not directory trees)
- **Custom files**: Specialized patterns (API, testing, security, etc.)

View File

@ -0,0 +1,222 @@
# Task Generation Rules
## Core Principles
### 1. Natural Language Descriptions
Focus on capabilities and outcomes, not code structure.
**Describe**:
- What functionality to achieve
- Business logic and behavior
- Features and capabilities
- Domain language and concepts
- Data relationships and workflows
**Avoid**:
- File paths and directory structure
- Function/method names and signatures
- Type definitions and interfaces
- Class names and API contracts
- Specific data structures
**Rationale**: Implementation details (files, methods, types) are defined in design.md. Tasks describe the functional work to be done.
### 2. Task Ordering Principle
**Order implies dependency**: Task N implicitly depends on all tasks before it. This is the primary dependency mechanism.
**Tasks must follow this phase order**:
1. **Foundation**: Environment setup, test infrastructure, shared utilities, database schema, configuration
2. **Core**: Primary feature implementation (parallel-capable tasks grouped here)
3. **Integration**: Wiring components together, cross-boundary connections
4. **Validation**: E2E tests, edge cases, regression checks
**Rationale**: Foundation work unblocks everything else. Placing setup tasks early prevents downstream blocking. Core tasks can often run in parallel because foundation is already complete.
### 3. Task Integration & Progression
**Every task must**:
- Build on previous outputs (no orphaned code)
- Connect to the overall system (no hanging features)
- Progress incrementally (no big jumps in complexity)
- Respect architecture boundaries defined in design.md (Architecture Pattern & Boundary Map)
- Honor interface contracts documented in design.md
- Use major task summaries sparingly—omit detail bullets if the work is fully captured by child tasks.
**End with integration tasks** to wire everything together.
### 4. Dependency Declaration
**Default**: Sequential ordering handles most dependencies (task N depends on tasks before it).
**Explicit declaration required when**:
- A task depends on a specific task in a different major-task group (cross-boundary)
- The dependency is non-obvious from ordering alone
- A task can skip ahead of its position (declared via `(P)`) but still needs specific prior work
**Format**: `_Depends: 1.2, 2.3_` — placed alongside `_Requirements:_` in task detail sections.
**Do not over-annotate**: If a task simply depends on the task directly before it, ordering alone is sufficient.
### 5. Boundary Scope
**Each task should declare its component boundary** using design.md component/module names:
- `_Boundary: AuthService_` or `_Boundary: API Layer, UserRepository_`
- Helps validate parallel safety: tasks with non-overlapping boundaries are parallel candidates
- Helps agents understand scope: what to touch and what not to touch
**When to use**: Required for tasks marked `(P)` to validate parallel safety. Omit for sequential tasks where scope is obvious from the description.
**Boundary rule**:
- Each executable task should stay within a single responsibility boundary
- If work must cross boundaries, make it an explicit integration task rather than a normal implementation task
- Do not hide cross-boundary coordination inside a task that appears local
### 6. Flexible Task Sizing
**Guidelines**:
- **Major tasks**: As many sub-tasks as logically needed (group by cohesion)
- **Sub-tasks**: 1-3 hours each, 3-10 details per sub-task
- Balance between too granular and too broad
**Don't force arbitrary numbers** - let logical grouping determine structure.
### 7. Requirements Mapping
**End each task detail section with**:
- `_Requirements: X.X, Y.Y_` listing **only numeric requirement IDs** (comma-separated). Never append descriptive text, parentheses, translations, or free-form labels.
- For cross-cutting requirements, list every relevant requirement ID. All requirements MUST have numeric IDs in requirements.md. If an ID is missing, stop and correct requirements.md before generating tasks.
- Reference components/interfaces from design.md when helpful (e.g., `_Contracts: AuthService API`)
### 7.5 Observable Completion
**Each executable task must include at least one detail bullet that describes the observable completed state**:
- Phrase it as a deliverable, runtime behavior, persisted state, UI state, endpoint behavior, test result, or integration outcome
- Avoid vague bullets like "implement support", "wire things up", or "handle logic" unless paired with a concrete observable result
- Prefer making one detail bullet clearly answer: "What will be true when this task is done?"
- Keep this within the existing task body; do not add extra bookkeeping fields
### 8. Code-Only Focus
**Include ONLY**:
- Coding tasks (implementation)
- Testing tasks (unit, integration, E2E)
- Technical setup tasks (infrastructure, configuration)
**Exclude**:
- Deployment tasks
- Documentation tasks
- User testing
- Marketing/business activities
## Task Plan Review Gate
Before writing `tasks.md`, review the draft task plan and repair local issues until the plan passes or a true spec gap is discovered.
### Coverage Review
- Every requirement ID from `requirements.md` must appear in at least one task.
- Every design component, interface/contract, integration point, runtime prerequisite, and validation concern from `design.md` must be represented by at least one task.
- If coverage is missing because the task plan is incomplete, repair the draft tasks and review again.
- If coverage cannot be added cleanly because requirements or design are ambiguous, contradictory, or underspecified, stop and return to the requirements/design phase instead of papering over the gap in `tasks.md`.
### Executability Review
- Every sub-task must be executable as written, usually within 1-3 hours.
- Every sub-task must produce a verifiable deliverable (behavior, artifact, endpoint, UI state, config, migration, test, or integration result).
- Every executable sub-task must include at least one detail bullet that states the observable completion condition.
- Split tasks that combine multiple independently verifiable outcomes.
- Split tasks that combine multiple responsibility boundaries unless they are explicit integration tasks.
- If many tasks require broad `_Boundary:_` scopes or repeated cross-boundary coordination, stop and return to design or roadmap decomposition instead of forcing the spec through task generation.
- Merge or collapse tasks that are too small, bookkeeping-only, or not meaningful execution units.
- Make implicit prerequisites explicit as preceding tasks.
- Re-check `_Depends:_`, `_Boundary:_`, and `(P)` markers after edits so concurrency claims still match the design boundaries and dependency graph.
### Review Loop
- Run the review gate on the draft task plan before writing `tasks.md`.
- If issues are task-plan-local, repair the draft and re-run the review gate.
- Keep the loop bounded: no more than 2 review-and-repair passes before escalating a real spec gap.
- Write `tasks.md` only after the review gate passes.
### Optional Test Coverage Tasks
- When the design already guarantees functional coverage and rapid MVP delivery is prioritized, mark purely test-oriented follow-up work (e.g., baseline rendering/unit tests) as **optional** using the `- [ ]*` checkbox form.
- Only apply the optional marker when the sub-task directly references acceptance criteria from requirements.md in its detail bullets.
- Never mark implementation work or integration-critical verification as optional—reserve `*` for auxiliary/deferrable test coverage that can be revisited post-MVP.
## Task Hierarchy Rules
### Maximum 2 Levels
- **Level 1**: Major tasks (1, 2, 3, 4...)
- **Level 2**: Sub-tasks (1.1, 1.2, 2.1, 2.2...)
- **No deeper nesting** (no 1.1.1)
- If a major task would contain only a single actionable item, collapse the structure and promote the sub-task to the major level (e.g., replace `1.1` with `1.`).
- When a major task exists purely as a container, keep the checkbox description concise and avoid duplicating detailed bullets—reserve specifics for its sub-tasks.
### Sequential Numbering
- Major tasks MUST increment: 1, 2, 3, 4, 5...
- Sub-tasks reset per major task: 1.1, 1.2, then 2.1, 2.2...
- Never repeat major task numbers
### Parallel Analysis (default)
- Assume parallel analysis is enabled unless explicitly disabled (e.g. `--sequential` flag).
- `(P)` means: this task has no dependency on its immediately preceding peers and can run concurrently with them.
- Identify tasks that can run concurrently when **all** conditions hold:
- No data dependency on other pending tasks
- No shared file or resource contention
- No prerequisite review/approval from another task
- `_Boundary:_` annotations confirm non-overlapping component scopes
- Foundation-phase tasks (see Task Ordering Principle) are rarely `(P)` — they establish shared prerequisites.
- Core-phase tasks are the primary candidates for `(P)` since foundation is already complete.
- Validate that identified parallel tasks operate within separate boundaries defined in the Architecture Pattern & Boundary Map.
- Confirm API/event contracts from design.md do not overlap in ways that cause conflicts.
- `(P)` tasks with cross-boundary dependencies must declare `_Depends: X.X_` explicitly.
- Append `(P)` immediately after the task number for each parallel-capable task:
- Example: `- [ ] 2.1 (P) Build background worker`
- Apply to both major tasks and sub-tasks when appropriate.
- If sequential mode is requested, omit `(P)` markers entirely.
- Group parallel tasks logically (same parent when possible) and highlight any ordering caveats in detail bullets.
- Explicitly call out dependencies that prevent `(P)` even when tasks look similar.
### Checkbox Format
```markdown
- [ ] 1. Foundation: environment and test infrastructure setup
- [ ] 1.1 Sub-task description
- Detail item 1
- Detail item 2
- Observable completion condition
- _Requirements: X.X_
- [ ] 2. Core feature A
- [ ] 2.1 (P) Sub-task description
- Detail items...
- Observable completion condition
- _Requirements: Y.Y_
- _Boundary: AuthService_
- [ ] 2.2 (P) Sub-task description
- Detail items...
- Observable completion condition
- _Requirements: Z.Z_
- _Boundary: UserRepository_
- [ ] 3. Integration and wiring
- [ ] 3.1 Sub-task description
- Detail items...
- Observable completion condition
- _Depends: 2.1, 2.2_
- _Requirements: W.W_
```
## Requirements Coverage
**Mandatory Check**:
- ALL requirements from requirements.md MUST be covered
- Cross-reference every requirement ID with task mappings
- If gaps found: Return to requirements or design phase
- No requirement should be left without corresponding tasks
Use `N.M`-style numeric requirement IDs where `N` is the top-level requirement number from requirements.md (for example, Requirement 1 → 1.1, 1.2; Requirement 2 → 2.1, 2.2), and `M` is a local index within that requirement group.
Document any intentionally deferred requirements with rationale.

View File

@ -0,0 +1,41 @@
# Parallel Task Analysis Rules
## Purpose
Provide a consistent way to identify implementation tasks that can be safely executed in parallel while generating `tasks.md`.
## Relationship to Task Ordering
`(P)` means: this task has no dependency on its immediately preceding peers and can run concurrently with them. The Task Ordering Principle (see tasks-generation.md) ensures Foundation-phase tasks run first, making Core-phase tasks the primary `(P)` candidates.
## When to Consider Tasks Parallel
Only mark a task as parallel-capable when **all** of the following are true:
1. **No data dependency** on pending tasks.
2. **No conflicting files or shared mutable resources** are touched.
3. **No prerequisite review/approval** from another task is required beforehand.
4. **Foundation work complete**: Environment/setup work needed by this task is already satisfied by earlier Foundation-phase tasks.
5. **Non-overlapping boundaries**: `_Boundary:_` annotations confirm tasks operate on separate components.
## Marking Convention
- Append `(P)` immediately after the numeric identifier for each qualifying task.
- Example: `- [ ] 2.1 (P) Build background worker for emails`
- Apply `(P)` to both major tasks and sub-tasks when appropriate.
- If sequential execution is requested (e.g. via `--sequential` flag), omit `(P)` markers entirely.
- Keep `(P)` **outside** of checkbox brackets to avoid confusion with completion state.
## Grouping & Ordering Guidelines
- Group parallel tasks under the same parent whenever the work belongs to the same theme.
- List obvious prerequisites or caveats in the detail bullets (e.g., "Requires schema migration from 1.2").
- When two tasks look similar but are not parallel-safe, call out the blocking dependency explicitly.
- Skip marking container-only major tasks (those without their own actionable detail bullets) with `(P)`—evaluate parallel execution at the sub-task level instead.
## Quality Checklist
Before marking a task with `(P)`, ensure you have:
- Verified that running this task concurrently will not create merge or deployment conflicts.
- Confirmed `_Boundary:_` annotations show non-overlapping component scopes.
- Captured any shared state expectations in the detail bullets.
- Confirmed that the implementation can be tested independently.
- Added `_Depends: X.X_` if this `(P)` task still requires specific prior work from a different major-task group.
If any check fails, **do not** mark the task with `(P)` and explain the dependency in the task details.

View File

@ -0,0 +1,331 @@
# Design Document Template
---
**Purpose**: Provide sufficient detail to ensure implementation consistency across different implementers, preventing interpretation drift.
**Approach**:
- Include essential sections that directly inform implementation decisions
- Omit optional sections unless critical to preventing implementation errors
- Match detail level to feature complexity
- Use diagrams and tables over lengthy prose
**Warning**: Approaching 1000 lines indicates excessive feature complexity that may require design simplification or splitting into multiple specs.
---
> Sections may be reordered (e.g., surfacing Requirements Traceability earlier or moving Data Models nearer Architecture) when it improves clarity. Within each section, keep the flow **Summary → Scope → Decisions → Impacts/Risks** so reviewers can scan consistently.
## Overview
2-3 paragraphs max
**Purpose**: This feature delivers [specific value] to [target users].
**Users**: [Target user groups] will utilize this for [specific workflows].
**Impact** (if applicable): Changes the current [system state] by [specific modifications].
### Goals
- Primary objective 1
- Primary objective 2
- Success criteria
### Non-Goals
- Explicitly excluded functionality
- Future considerations outside current scope
- Integration points deferred
## Boundary Commitments
State the responsibility boundary of this spec in concrete terms. Treat this as the anchor for architecture, tasks, and later validation.
### This Spec Owns
- Capabilities and behaviors this spec is responsible for
- Data it owns or is authoritative for
- Interfaces or contracts it defines or stabilizes
### Out of Boundary
- Related concerns this spec explicitly does NOT own
- Work deferred to another spec, existing subsystem, or later phase
- Changes this spec must not absorb as "just one more thing"
### Allowed Dependencies
- Upstream systems/specs/components this design may depend on
- Shared infrastructure this design may use
- Dependency constraints that must not be violated
### Revalidation Triggers
List the kinds of changes that should force dependent specs or consumers to re-check integration.
- Contract shape changes
- Data ownership changes
- Dependency direction changes
- Startup/runtime prerequisite changes
## Architecture
> Reference detailed discovery notes in `research.md` only for background; keep design.md self-contained for reviewers by capturing all decisions and contracts here.
> Capture key decisions in text and let diagrams carry structural detail—avoid repeating the same information in prose.
> Supporting sections below should remain as light as possible unless they materially clarify the responsibility boundary, dependency rules, or integration seams.
### Existing Architecture Analysis (if applicable)
When modifying existing systems:
- Current architecture patterns and constraints
- Existing domain boundaries to be respected
- Integration points that must be maintained
- Technical debt addressed or worked around
### Architecture Pattern & Boundary Map
**RECOMMENDED**: Include Mermaid diagram showing the chosen architecture pattern and system boundaries (required for complex features, optional for simple additions)
**Architecture Integration**:
- Selected pattern: [name and brief rationale]
- Domain/feature boundaries: [how responsibilities are separated to avoid conflicts]
- Existing patterns preserved: [list key patterns]
- New components rationale: [why each is needed]
- Steering compliance: [principles maintained]
### Technology Stack
| Layer | Choice / Version | Role in Feature | Notes |
|-------|------------------|-----------------|-------|
| Frontend / CLI | | | |
| Backend / Services | | | |
| Data / Storage | | | |
| Messaging / Events | | | |
| Infrastructure / Runtime | | | |
> Keep rationale concise here and, when more depth is required (trade-offs, benchmarks), add a short summary plus pointer to the Supporting References section and `research.md` for raw investigation notes.
## File Structure Plan
Map the directory structure and file responsibilities for this feature. This section directly drives task `_Boundary:_` annotations and implementation Task Briefs. Use the appropriate level of detail:
- **Small features**: List individual files with responsibilities
- **Large features**: Describe directory-level structure + per-domain/module pattern, list only non-obvious files individually
### Directory Structure
```
src/
├── domain-a/ # Domain A responsibility
│ ├── controller.ts # Endpoint handlers
│ ├── service.ts # Business logic
│ └── types.ts # Domain types
├── domain-b/ # Domain B (same pattern as domain-a)
└── shared/
└── cross-cutting.ts # Non-obvious: why this exists
```
> For repeated structures, describe the pattern once (e.g., "domain-b follows same pattern as domain-a"). List individual files only when their responsibility isn't obvious from the path.
### Modified Files
- `path/to/existing.ts` — What changes and why
> Each file should have one clear responsibility. Group files that change together. For repeated structures, describe the pattern once rather than listing every file.
> Avoid duplicating what Components and Interfaces already describes — focus on the physical file layout that Components maps to.
## System Flows
Provide only the diagrams needed to explain non-trivial flows. Use pure Mermaid syntax. Common patterns:
- Sequence (multi-party interactions)
- Process / state (branching logic or lifecycle)
- Data / event flow (pipelines, async messaging)
Skip this section entirely for simple CRUD changes.
> Describe flow-level decisions (e.g., gating conditions, retries) briefly after the diagram instead of restating each step.
## Requirements Traceability
Use this section for complex or compliance-sensitive features where requirements span multiple domains. Straightforward 1:1 mappings can rely on the Components summary table.
Map each requirement ID (e.g., `2.1`) to the design elements that realize it.
| Requirement | Summary | Components | Interfaces | Flows |
|-------------|---------|------------|------------|-------|
| 1.1 | | | | |
| 1.2 | | | | |
> Omit this section only when a single component satisfies a single requirement without cross-cutting concerns.
## Components and Interfaces
Provide a quick reference before diving into per-component details.
- Summaries can be a table or compact list. Example table:
| Component | Domain/Layer | Intent | Req Coverage | Key Dependencies (P0/P1) | Contracts |
|-----------|--------------|--------|--------------|--------------------------|-----------|
| ExampleComponent | UI | Displays XYZ | 1, 2 | GameProvider (P0), MapPanel (P1) | Service, State |
- Only components introducing new boundaries (e.g., logic hooks, external integrations, persistence) require full detail blocks. Simple presentation components can rely on the summary row plus a short Implementation Note.
Group detailed blocks by domain or architectural layer. For each detailed component, list requirement IDs as `2.1, 2.3` (omit “Requirement”). When multiple UI components share the same contract, reference a base interface/props definition instead of duplicating code blocks.
### [Domain / Layer]
#### [Component Name]
| Field | Detail |
|-------|--------|
| Intent | 1-line description of the responsibility |
| Requirements | 2.1, 2.3 |
| Owner / Reviewers | (optional) |
**Responsibilities & Constraints**
- Primary responsibility
- Domain boundary and transaction scope
- Data ownership / invariants
**Dependencies**
- Inbound: Component/service name — purpose (Criticality)
- Outbound: Component/service name — purpose (Criticality)
- External: Service/library — purpose (Criticality)
Summarize external dependency findings here; deeper investigation (API signatures, rate limits, migration notes) lives in `research.md`.
**Contracts**: Service [ ] / API [ ] / Event [ ] / Batch [ ] / State [ ] ← check only the ones that apply.
##### Service Interface
```typescript
interface [ComponentName]Service {
methodName(input: InputType): Result<OutputType, ErrorType>;
}
```
- Preconditions:
- Postconditions:
- Invariants:
##### API Contract
| Method | Endpoint | Request | Response | Errors |
|--------|----------|---------|----------|--------|
| POST | /api/resource | CreateRequest | Resource | 400, 409, 500 |
##### Event Contract
- Published events:
- Subscribed events:
- Ordering / delivery guarantees:
##### Batch / Job Contract
- Trigger:
- Input / validation:
- Output / destination:
- Idempotency & recovery:
##### State Management
- State model:
- Persistence & consistency:
- Concurrency strategy:
**Implementation Notes**
- Integration:
- Validation:
- Risks:
## Data Models
Focus on the portions of the data landscape that change with this feature.
### Domain Model
- Aggregates and transactional boundaries
- Entities, value objects, domain events
- Business rules & invariants
- Optional Mermaid diagram for complex relationships
### Logical Data Model
**Structure Definition**:
- Entity relationships and cardinality
- Attributes and their types
- Natural keys and identifiers
- Referential integrity rules
**Consistency & Integrity**:
- Transaction boundaries
- Cascading rules
- Temporal aspects (versioning, audit)
### Physical Data Model
**When to include**: When implementation requires specific storage design decisions
**For Relational Databases**:
- Table definitions with data types
- Primary/foreign keys and constraints
- Indexes and performance optimizations
- Partitioning strategy for scale
**For Document Stores**:
- Collection structures
- Embedding vs referencing decisions
- Sharding key design
- Index definitions
**For Event Stores**:
- Event schema definitions
- Stream aggregation strategies
- Snapshot policies
- Projection definitions
**For Key-Value/Wide-Column Stores**:
- Key design patterns
- Column families or value structures
- TTL and compaction strategies
### Data Contracts & Integration
**API Data Transfer**
- Request/response schemas
- Validation rules
- Serialization format (JSON, Protobuf, etc.)
**Event Schemas**
- Published event structures
- Schema versioning strategy
- Backward/forward compatibility rules
**Cross-Service Data Management**
- Distributed transaction patterns (Saga, 2PC)
- Data synchronization strategies
- Eventual consistency handling
Skip subsections that are not relevant to this feature.
## Error Handling
### Error Strategy
Concrete error handling patterns and recovery mechanisms for each error type.
### Error Categories and Responses
**User Errors** (4xx): Invalid input → field-level validation; Unauthorized → auth guidance; Not found → navigation help
**System Errors** (5xx): Infrastructure failures → graceful degradation; Timeouts → circuit breakers; Exhaustion → rate limiting
**Business Logic Errors** (422): Rule violations → condition explanations; State conflicts → transition guidance
**Process Flow Visualization** (when complex business logic exists):
Include Mermaid flowchart only for complex error scenarios with business workflows.
### Monitoring
Error tracking, logging, and health monitoring implementation.
## Testing Strategy
### Default sections (adapt names/sections to fit the domain)
- Unit Tests: 35 items from core functions/modules (e.g., auth methods, subscription logic)
- Integration Tests: 35 cross-component flows (e.g., webhook handling, notifications)
- E2E/UI Tests (if applicable): 35 critical user paths (e.g., forms, dashboards)
- Performance/Load (if applicable): 34 items (e.g., concurrency, high-volume ops)
## Optional Sections (include when relevant)
### Security Considerations
_Use this section for features handling auth, sensitive data, external integrations, or user permissions. Capture only decisions unique to this feature; defer baseline controls to steering docs._
- Threat modeling, security controls, compliance requirements
- Authentication and authorization patterns
- Data protection and privacy considerations
### Performance & Scalability
_Use this section when performance targets, high load, or scaling concerns exist. Record only feature-specific targets or trade-offs and rely on steering documents for general practices._
- Target metrics and measurement strategies
- Scaling approaches (horizontal/vertical)
- Caching strategies and optimization techniques
### Migration Strategy
Include a Mermaid flowchart showing migration phases when schema/data movement is required.
- Phase breakdown, rollback triggers, validation checkpoints
## Supporting References (Optional)
- Create this section only when keeping the information in the main body would hurt readability (e.g., very long TypeScript definitions, vendor option matrices, exhaustive schema tables). Keep decision-making context in the main sections so the design stays self-contained.
- Link to the supporting references from the main text instead of inlining large snippets.
- Background research notes and comparisons continue to live in `research.md`, but their conclusions must be summarized in the main design.

View File

@ -0,0 +1,24 @@
{
"feature_name": "{{FEATURE_NAME}}",
"created_at": "{{TIMESTAMP}}",
"updated_at": "{{TIMESTAMP}}",
"language": "en",
"phase": "initialized",
"approvals": {
"requirements": {
"generated": false,
"approved": false
},
"design": {
"generated": false,
"approved": false
},
"tasks": {
"generated": false,
"approved": false
}
},
"ready_for_implementation": false
}

View File

@ -0,0 +1,9 @@
# Requirements Document
## Project Description (Input)
{{PROJECT_DESCRIPTION}}
## Requirements
<!-- Will be generated in /kiro-spec-requirements phase -->

View File

@ -0,0 +1,32 @@
# Requirements Document
## Introduction
{{INTRODUCTION}}
<!-- Optional when scope could be misread or the feature touches adjacent systems/specs -->
## Boundary Context (Optional)
- **In scope**: {{IN_SCOPE_BEHAVIORS}}
- **Out of scope**: {{OUT_OF_SCOPE_BEHAVIORS}}
- **Adjacent expectations**: {{ADJACENT_SYSTEM_OR_SPEC_EXPECTATIONS}}
## Requirements
### Requirement 1: {{REQUIREMENT_AREA_1}}
<!-- Requirement headings MUST include a leading numeric ID only (for example: "Requirement 1: ...", "1. Overview", "2 Feature: ..."). Alphabetic IDs like "Requirement A" are not allowed. -->
**Objective:** As a {{ROLE}}, I want {{CAPABILITY}}, so that {{BENEFIT}}
#### Acceptance Criteria
1. When [event], the [system] shall [response/action]
2. If [trigger], then the [system] shall [response/action]
3. While [precondition], the [system] shall [response/action]
4. Where [feature is included], the [system] shall [response/action]
5. The [system] shall [response/action]
### Requirement 2: {{REQUIREMENT_AREA_2}}
**Objective:** As a {{ROLE}}, I want {{CAPABILITY}}, so that {{BENEFIT}}
#### Acceptance Criteria
1. When [event], the [system] shall [response/action]
2. When [event] and [condition], the [system] shall [response/action]
<!-- Additional requirements follow the same pattern -->

View File

@ -0,0 +1,61 @@
# Research & Design Decisions Template
---
**Purpose**: Capture discovery findings, architectural investigations, and rationale that inform the technical design.
**Usage**:
- Log research activities and outcomes during the discovery phase.
- Document design decision trade-offs that are too detailed for `design.md`.
- Provide references and evidence for future audits or reuse.
---
## Summary
- **Feature**: `<feature-name>`
- **Discovery Scope**: New Feature / Extension / Simple Addition / Complex Integration
- **Key Findings**:
- Finding 1
- Finding 2
- Finding 3
## Research Log
Document notable investigation steps and their outcomes. Group entries by topic for readability.
### [Topic or Question]
- **Context**: What triggered this investigation?
- **Sources Consulted**: Links, documentation, API references, benchmarks
- **Findings**: Concise bullet points summarizing the insights
- **Implications**: How this affects architecture, contracts, or implementation
_Repeat the subsection for each major topic._
## Architecture Pattern Evaluation
List candidate patterns or approaches that were considered. Use the table format where helpful.
| Option | Description | Strengths | Risks / Limitations | Notes |
|--------|-------------|-----------|---------------------|-------|
| Hexagonal | Ports & adapters abstraction around core domain | Clear boundaries, testable core | Requires adapter layer build-out | Aligns with existing steering principle X |
## Design Decisions
Record major decisions that influence `design.md`. Focus on choices with significant trade-offs.
### Decision: `<Title>`
- **Context**: Problem or requirement driving the decision
- **Alternatives Considered**:
1. Option A — short description
2. Option B — short description
- **Selected Approach**: What was chosen and how it works
- **Rationale**: Why this approach fits the current project context
- **Trade-offs**: Benefits vs. compromises
- **Follow-up**: Items to verify during implementation or testing
_Repeat the subsection for each decision._
## Risks & Mitigations
- Risk 1 — Proposed mitigation
- Risk 2 — Proposed mitigation
- Risk 3 — Proposed mitigation
## References
Provide canonical links and citations (official docs, standards, ADRs, internal guidelines).
- [Title](https://example.com) — brief note on relevance
- ...

View File

@ -0,0 +1,24 @@
# Implementation Plan
## Task Format Template
Use whichever pattern fits the work breakdown:
### Major task only
- [ ] {{NUMBER}}. {{TASK_DESCRIPTION}}{{PARALLEL_MARK}}
- {{DETAIL_ITEM_1}} *(Include details only when needed. If the task stands alone, omit bullet items.)*
- _Requirements: {{REQUIREMENT_IDS}}_
### Major + Sub-task structure
- [ ] {{MAJOR_NUMBER}}. {{MAJOR_TASK_SUMMARY}}
- [ ] {{MAJOR_NUMBER}}.{{SUB_NUMBER}} {{SUB_TASK_DESCRIPTION}}{{SUB_PARALLEL_MARK}}
- {{DETAIL_ITEM_1}}
- {{DETAIL_ITEM_2}}
- {{OBSERVABLE_COMPLETION_ITEM}} *(At least one detail item should state the observable completion condition for this task.)*
- _Requirements: {{REQUIREMENT_IDS}}_ *(IDs only; do not add descriptions or parentheses.)*
- _Boundary: {{COMPONENT_NAMES}}_ *(Only for (P) tasks. Omit when scope is obvious.)*
- _Depends: {{TASK_IDS}}_ *(Only for non-obvious cross-boundary dependencies. Most tasks omit this.)*
> **Parallel marker**: Append ` (P)` only to tasks that can be executed in parallel. Omit the marker when running in `--sequential` mode.
>
> **Optional test coverage**: When a sub-task is deferrable test work tied to acceptance criteria, mark the checkbox as `- [ ]*` and explain the referenced requirements in the detail bullets.

View File

@ -0,0 +1,69 @@
# API Standards
[Purpose: consistent API patterns for naming, structure, auth, versioning, and errors]
## Philosophy
- Prefer predictable, resource-oriented design
- Be explicit in contracts; minimize breaking changes
- Secure by default (auth first, least privilege)
## Endpoint Pattern
```
/{version}/{resource}[/{id}][/{sub-resource}]
```
Examples:
- `/api/v1/users`
- `/api/v1/users/:id`
- `/api/v1/users/:id/posts`
HTTP verbs:
- GET (read, safe, idempotent)
- POST (create)
- PUT/PATCH (update)
- DELETE (remove, idempotent)
## Request/Response
Request (typical):
```json
{ "data": { ... }, "metadata": { "requestId": "..." } }
```
Success:
```json
{ "data": { ... }, "meta": { "timestamp": "...", "version": "..." } }
```
Error:
```json
{ "error": { "code": "ERROR_CODE", "message": "...", "field": "optional" } }
```
(See error-handling for rules.)
## Status Codes (pattern)
- 2xx: Success (200 read, 201 create, 204 delete)
- 4xx: Client issues (400 validation, 401/403 auth, 404 missing)
- 5xx: Server issues (500 generic, 503 unavailable)
Choose the status that best reflects the outcome.
## Authentication
- Credentials in standard location
```
Authorization: Bearer {token}
```
- Reject unauthenticated before business logic
## Versioning
- Version via URL/header/media-type
- Breaking change → new version
- Non-breaking → same version
- Provide deprecation window and comms
## Pagination/Filtering (if applicable)
- Pagination: `page`, `pageSize` or cursor-based
- Filtering: explicit query params
- Sorting: `sort=field:asc|desc`
Return pagination metadata in `meta`.
---
_Focus on patterns and decisions, not endpoint catalogs._

View File

@ -0,0 +1,67 @@
# Authentication & Authorization Standards
[Purpose: unify auth model, token/session lifecycle, permission checks, and security]
## Philosophy
- Clear separation: authentication (who) vs authorization (what)
- Secure by default: least privilege, fail closed, short-lived tokens
- UX-aware: friction where risk is high, smooth otherwise
## Authentication
### Method (choose + rationale)
- Options: JWT, Session, OAuth2, hybrid
- Choice: [our method] because [reason]
### Flow (high-level)
```
1) User proves identity (credentials or provider)
2) Server verifies and issues token/session
3) Client sends token per request
4) Server verifies token and proceeds
```
### Token/Session Lifecycle
- Storage: httpOnly cookie or Authorization header
- Expiration: short-lived access, longer refresh (if used)
- Refresh: rotate tokens; respect revocation
- Revocation: blacklist/rotate on logout/compromise
### Security Pattern
- Enforce TLS; never expose tokens to JS when avoidable
- Bind token to audience/issuer; include minimal claims
- Consider device binding and IP/risk checks for sensitive actions
## Authorization
### Permission Model
- Choose one: RBAC / ABAC / ownership-based / hybrid
- Define roles/attributes centrally; avoid hardcoding across codebase
### Checks (where to enforce)
- Route/middleware: coarse-grained gate
- Domain/service: fine-grained decisions
- UI: conditional rendering (no security reliance)
Example pattern:
```typescript
requirePermission('resource:action'); // route
if (!user.can('resource:action')) throw ForbiddenError(); // domain
```
### Ownership
- Pattern: owner OR privileged role can act
- Verify on entity boundary before mutation
## Passwords & MFA
- Passwords: strong policy, hashed (bcrypt/argon2), never plaintext
- Reset: time-limited token, single-use, notify user
- MFA: step-up for risky operations (policy-driven)
## API-to-API Auth
- Use API keys or OAuth client credentials
- Scope keys minimally; rotate and audit usage
- Rate limit by identity (user/key)
---
_Focus on patterns and decisions. No library-specific code._

View File

@ -0,0 +1,46 @@
# Database Standards
[Purpose: guide schema design, queries, migrations, and integrity]
## Philosophy
- Model the domain first; optimize after correctness
- Prefer explicit constraints; let database enforce invariants
- Query only what you need; measure before optimizing
## Naming & Types
- Tables: `snake_case`, plural (`users`, `order_items`)
- Columns: `snake_case` (`created_at`, `user_id`)
- FKs: `{table}_id` referencing `{table}.id`
- Types: timezone-aware timestamps; strong IDs; precise money types
## Relationships
- 1:N: FK in child
- N:N: join table with compound key
- 1:1: FK + UNIQUE
## Migrations
- Immutable migrations; always add rollback
- Small, focused steps; test on non-prod first
- Naming: `{seq}_{action}_{object}` (e.g., `002_add_email_index`)
## Query Patterns
- ORM for simple CRUD and safety; raw SQL for complex/perf-critical
- Avoid N+1 (eager load/batching); paginate large sets
- Index FKs and frequently filtered/sorted columns
## Connection & Transactions
- Use pooling (size/timeouts based on workload)
- One connection per unit of work; close/return promptly
- Wrap multi-step changes in transactions
## Data Integrity
- Use NOT NULL/UNIQUE/CHECK/FK constraints
- Validate at DB when appropriate (defense in depth)
- Prefer generated columns for consistent derivations
## Backup & Recovery
- Regular backups with retention; test restores
- Document RPO/RTO targets; monitor backup jobs
---
_Focus on patterns and decisions. No environment-specific settings._

View File

@ -0,0 +1,54 @@
# Deployment Standards
[Purpose: safe, repeatable releases with clear environment and pipeline patterns]
## Philosophy
- Automate; test before deploy; verify after deploy
- Prefer incremental rollout with fast rollback
- Production changes must be observable and reversible
## Environments
- Dev: fast iteration; debugging enabled
- Staging: mirrors prod; release validation
- Prod: hardened; monitored; least privilege
## CI/CD Flow
```
Code → Test → Build → Scan → Deploy (staged) → Verify
```
Principles:
- Fail fast on tests/scans; block deploy
- Artifact builds are reproducible (lockfiles, pinned versions)
- Manual approval for prod; auditable trail
## Deployment Strategies
- Rolling: gradual instance replacement
- Blue-Green: switch traffic between two pools
- Canary: small % users first, expand on health
Choose per risk profile; document default.
## Zero-Downtime & Migrations
- Health checks gate traffic; graceful shutdown
- Backwards-compatible DB changes during rollout
- Separate migration step; test rollback paths
## Rollback
- Keep previous version ready; automate revert
- Rollback faster than fix-forward; document triggers
## Configuration & Secrets
- 12-factor config via env; never commit secrets
- Secret manager; rotate; least privilege; audit access
- Validate required env vars at startup
## Health & Monitoring
- Endpoints: `/health`, `/health/live`, `/health/ready`
- Monitor latency, error rate, throughput, saturation
- Alerts on SLO breaches/spikes; tune to avoid fatigue
## Incident Response & DR
- Standard playbook: detect → assess → mitigate → communicate → resolve → post-mortem
- Backups with retention; test restore; defined RPO/RTO
---
_Focus on rollout patterns and safeguards. No provider-specific steps._

View File

@ -0,0 +1,59 @@
# Error Handling Standards
[Purpose: unify how errors are classified, shaped, propagated, logged, and monitored]
## Philosophy
- Fail fast where possible; degrade gracefully at system boundaries
- Consistent error shape across the stack (human + machine readable)
- Handle known errors close to source; surface unknowns to a global handler
## Classification (decide handling by source)
- Client: Input/validation/user action issues → 4xx
- Server: System failures/unexpected exceptions → 5xx
- Business: Rule/state violations → 4xx (e.g., 409)
- External: 3rd-party/network failures → map to 5xx or 4xx with context
## Error Shape (single canonical format)
```json
{
"error": {
"code": "ERROR_CODE",
"message": "Human-readable message",
"requestId": "trace-id",
"timestamp": "ISO-8601"
}
}
```
Principles: stable code enums, no secrets, include trace info.
## Propagation (where to convert)
- API layer: Convert domain errors → HTTP status + canonical body
- Service layer: Throw typed business errors, avoid stringly-typed errors
- Data/external layer: Wrap provider errors with safe, actionable codes
- Unknown errors: Bubble to global handler → 500 + generic message
Example pattern:
```typescript
try { return await useCase(); }
catch (e) {
if (e instanceof BusinessError) return respondMapped(e);
logError(e); return respondInternal();
}
```
## Logging (context over noise)
Log: operation, userId (if available), code, message, stack, requestId, minimal context.
Do not log: passwords, tokens, secrets, full PII, full bodies with sensitive data.
Levels: ERROR (failures), WARN (recoverable/edge), INFO (key events), DEBUG (diagnostics).
## Retry (only when safe)
Retry when: network/timeouts/transient 5xx AND operation is idempotent.
Do not retry: 4xx, business errors, non-idempotent flows.
Strategy: exponential backoff + jitter, capped attempts; require idempotency keys.
## Monitoring & Health
Track: error rates by code/category, latency, saturation; alert on spikes/SLI breaches.
Expose health: `/health` (live), `/health/ready` (ready). Link errors to traces.
---
_Focus on patterns and decisions. No implementation details or exhaustive lists._

View File

@ -0,0 +1,55 @@
# Security Standards
[Purpose: define security posture with patterns for validation, authz, secrets, and data]
## Philosophy
- Defense in depth; least privilege; secure by default; fail closed
- Validate at boundaries; sanitize for context; never trust input
- Separate authentication (who) and authorization (what)
## Input & Output
- Validate at API boundaries and UI forms; enforce types and constraints
- Sanitize/escape based on destination (HTML, SQL, shell, logs)
- Prefer allow-lists over block-lists; reject early with minimal detail
## Authentication & Authorization
- Authentication: verify identity; issue short-lived tokens/sessions
- Authorization: check permissions before actions; deny by default
- Centralize policies; avoid duplicating checks across code
Pattern:
```typescript
if (!user.hasPermission('resource:action')) throw ForbiddenError();
```
## Secrets & Configuration
- Never commit secrets; store in secret manager or env
- Rotate regularly; audit access; scope minimal
- Validate required env vars at startup; fail fast on missing
## Sensitive Data
- Minimize collection; mask/redact in logs; encrypt at rest and in transit
- Restrict access by role/need-to-know; track access to sensitive records
## Session/Token Security
- httpOnly + secure cookies where possible; TLS everywhere
- Short expiration; rotate on refresh; revoke on logout/compromise
- Bind tokens to audience/issuer; include minimal claims
## Logging (security-aware)
- Log auth attempts, permission denials, and sensitive operations
- Never log passwords, tokens, secrets, full PII; avoid full bodies
- Include requestId and context to correlate events
## Headers & Transport
- Enforce TLS; HSTS
- Set security headers (CSP, X-Frame-Options, X-Content-Type-Options)
- Prefer modern crypto; disable weak protocols/ciphers
## Vulnerability Posture
- Prefer secure libraries; keep dependencies updated
- Static/dynamic scans in CI; track and remediate
- Educate team on common classes; encode as patterns above
---
_Focus on patterns and principles. Link concrete configs to ops docs._

View File

@ -0,0 +1,47 @@
# Testing Standards
[Purpose: guide what to test, where tests live, and how to structure them]
## Philosophy
- Test behavior, not implementation
- Prefer fast, reliable tests; minimize brittle mocks
- Cover critical paths deeply; breadth over 100% pursuit
## Organization
Options:
- Co-located: `component.tsx` + `component.test.tsx`
- Separate: `/src/...` and `/tests/...`
Pick one as default; allow exceptions with rationale.
Naming:
- Files: `*.test.*` or `*.spec.*`
- Suites: what is under test; Cases: expected behavior
## Test Types
- Unit: single unit, mocked dependencies, very fast
- Integration: multiple units together, mock externals only
- E2E: full flows, minimal mocks, only for critical journeys
## Structure (AAA)
```typescript
it('does X when Y', () => {
// Arrange
const input = setup();
// Act
const result = act(input);
// Assert
expect(result).toEqual(expected);
});
```
## Mocking & Data
- Mock externals (API/DB); never mock the system under test
- Use factories/fixtures; reset state between tests
- Keep test data minimal and intention-revealing
## Coverage
- Target: [% overall]; higher for critical domains
- Enforce thresholds in CI; exceptions require review rationale
---
_Focus on patterns and decisions. Tool-specific config lives elsewhere._

View File

@ -0,0 +1,18 @@
# Product Overview
[Brief description of what this product does and who it serves]
## Core Capabilities
[3-5 key capabilities, not exhaustive features]
## Target Use Cases
[Primary scenarios this product addresses]
## Value Proposition
[What makes this product unique or valuable]
---
_Focus on patterns and purpose, not exhaustive feature lists_

View File

@ -0,0 +1,41 @@
# Project Structure
## Organization Philosophy
[Describe approach: feature-first, layered, domain-driven, etc.]
## Directory Patterns
### [Pattern Name]
**Location**: `/path/`
**Purpose**: [What belongs here]
**Example**: [Brief example]
### [Pattern Name]
**Location**: `/path/`
**Purpose**: [What belongs here]
**Example**: [Brief example]
## Naming Conventions
- **Files**: [Pattern, e.g., PascalCase, kebab-case]
- **Components**: [Pattern]
- **Functions**: [Pattern]
## Import Organization
```typescript
// Example import patterns
import { Something } from '@/path' // Absolute
import { Local } from './local' // Relative
```
**Path Aliases**:
- `@/`: [Maps to]
## Code Organization Principles
[Key architectural patterns and dependency rules]
---
_Document patterns, not file trees. New files following patterns shouldn't require updates_

View File

@ -0,0 +1,45 @@
# Technology Stack
## Architecture
[High-level system design approach]
## Core Technologies
- **Language**: [e.g., TypeScript, Python]
- **Framework**: [e.g., React, Next.js, Django]
- **Runtime**: [e.g., Node.js 20+]
## Key Libraries
[Only major libraries that influence development patterns]
## Development Standards
### Type Safety
[e.g., TypeScript strict mode, no `any`]
### Code Quality
[e.g., ESLint, Prettier rules]
### Testing
[e.g., Jest, coverage requirements]
## Development Environment
### Required Tools
[Key tools and version requirements]
### Common Commands
```bash
# Dev: [command]
# Build: [command]
# Test: [command]
```
## Key Technical Decisions
[Important architectural choices and rationale]
---
_Document standards and patterns, not every dependency_