Add Kiro IDE support (.kiro/) (#548)

Co-authored-by: Sungmin Hong <hsungmin@amazon.com>
This commit is contained in:
Himanshu Sharma
2026-03-20 01:50:35 -07:00
committed by GitHub
parent c8f631b046
commit ce828c1c3c
85 changed files with 12110 additions and 0 deletions

View File

@@ -0,0 +1,53 @@
---
inclusion: auto
description: Core coding style rules including immutability, file organization, error handling, and code quality standards.
---
# Coding Style
## Immutability (CRITICAL)
ALWAYS create new objects, NEVER mutate existing ones:
```
// Pseudocode
WRONG: modify(original, field, value) → changes original in-place
CORRECT: update(original, field, value) → returns new copy with change
```
Rationale: Immutable data prevents hidden side effects, makes debugging easier, and enables safe concurrency.
## File Organization
MANY SMALL FILES > FEW LARGE FILES:
- High cohesion, low coupling
- 200-400 lines typical, 800 max
- Extract utilities from large modules
- Organize by feature/domain, not by type
## Error Handling
ALWAYS handle errors comprehensively:
- Handle errors explicitly at every level
- Provide user-friendly error messages in UI-facing code
- Log detailed error context on the server side
- Never silently swallow errors
## Input Validation
ALWAYS validate at system boundaries:
- Validate all user input before processing
- Use schema-based validation where available
- Fail fast with clear error messages
- Never trust external data (API responses, user input, file content)
## Code Quality Checklist
Before marking work complete:
- [ ] Code is readable and well-named
- [ ] Functions are small (<50 lines)
- [ ] Files are focused (<800 lines)
- [ ] No deep nesting (>4 levels)
- [ ] Proper error handling
- [ ] No hardcoded values (use constants or config)
- [ ] No mutation (immutable patterns used)

View File

@@ -0,0 +1,44 @@
---
inclusion: manual
description: Development mode context for active feature implementation and coding work
---
# Development Mode
Use this context when actively implementing features or writing code.
## Focus Areas
- Write clean, maintainable code
- Follow TDD workflow when appropriate
- Implement incrementally with frequent testing
- Consider edge cases and error handling
- Document complex logic inline
## Workflow
1. Understand requirements thoroughly
2. Plan implementation approach
3. Write tests first (when using TDD)
4. Implement minimal working solution
5. Refactor for clarity and maintainability
6. Verify all tests pass
## Code Quality
- Prioritize readability over cleverness
- Keep functions small and focused
- Use meaningful variable and function names
- Add comments for non-obvious logic
- Follow project coding standards
## Testing
- Write unit tests for business logic
- Test edge cases and error conditions
- Ensure tests are fast and reliable
- Use descriptive test names
## Invocation
Use `#dev-mode` to activate this context when starting development work.

View File

@@ -0,0 +1,34 @@
---
inclusion: auto
description: Development workflow guidelines for planning, TDD, code review, and commit pipeline
---
# Development Workflow
> This rule extends the git workflow rule with the full feature development process that happens before git operations.
The Feature Implementation Workflow describes the development pipeline: planning, TDD, code review, and then committing to git.
## Feature Implementation Workflow
1. **Plan First**
- Use **planner** agent to create implementation plan
- Identify dependencies and risks
- Break down into phases
2. **TDD Approach**
- Use **tdd-guide** agent
- Write tests first (RED)
- Implement to pass tests (GREEN)
- Refactor (IMPROVE)
- Verify 80%+ coverage
3. **Code Review**
- Use **code-reviewer** agent immediately after writing code
- Address CRITICAL and HIGH issues
- Fix MEDIUM issues when possible
4. **Commit & Push**
- Detailed commit messages
- Follow conventional commits format
- See the git workflow rule for commit message format and PR process

View File

@@ -0,0 +1,29 @@
---
inclusion: auto
description: Git workflow guidelines for conventional commits and pull request process
---
# Git Workflow
## Commit Message Format
```
<type>: <description>
<optional body>
```
Types: feat, fix, refactor, docs, test, chore, perf, ci
Note: Attribution disabled globally via ~/.claude/settings.json.
## Pull Request Workflow
When creating PRs:
1. Analyze full commit history (not just latest commit)
2. Use `git diff [base-branch]...HEAD` to see all changes
3. Draft comprehensive PR summary
4. Include test plan with TODOs
5. Push with `-u` flag if new branch
> For the full development process (planning, TDD, code review) before git operations,
> see the development workflow rule.

View File

@@ -0,0 +1,45 @@
---
inclusion: fileMatch
fileMatchPattern: "*.go"
description: Go-specific patterns including functional options, small interfaces, and dependency injection
---
# Go Patterns
> This file extends the common patterns with Go specific content.
## Functional Options
```go
type Option func(*Server)
func WithPort(port int) Option {
return func(s *Server) { s.port = port }
}
func NewServer(opts ...Option) *Server {
s := &Server{port: 8080}
for _, opt := range opts {
opt(s)
}
return s
}
```
## Small Interfaces
Define interfaces where they are used, not where they are implemented.
## Dependency Injection
Use constructor functions to inject dependencies:
```go
func NewUserService(repo UserRepository, logger Logger) *UserService {
return &UserService{repo: repo, logger: logger}
}
```
## Reference
See skill: `golang-patterns` for comprehensive Go patterns including concurrency, error handling, and package organization.

View File

@@ -0,0 +1,84 @@
---
inclusion: auto
description: Project-specific patterns, preferences, and lessons learned over time (user-editable)
---
# Lessons Learned
This file captures project-specific patterns, coding preferences, common pitfalls, and architectural decisions that emerge during development. It serves as a workaround for continuous learning by allowing you to document patterns manually.
**How to use this file:**
1. The `extract-patterns` hook will suggest patterns after agent sessions
2. Review suggestions and add genuinely useful patterns below
3. Edit this file directly to capture team conventions
4. Keep it focused on project-specific insights, not general best practices
---
## Project-Specific Patterns
*Document patterns unique to this project that the team should follow.*
### Example: API Error Handling
```typescript
// Always use our custom ApiError class for consistent error responses
throw new ApiError(404, 'Resource not found', { resourceId });
```
---
## Code Style Preferences
*Document team preferences that go beyond standard linting rules.*
### Example: Import Organization
```typescript
// Group imports: external, internal, types
import { useState } from 'react';
import { Button } from '@/components/ui';
import type { User } from '@/types';
```
---
## Kiro Hooks
### `install.sh` is additive-only — it won't update existing installations
The installer skips any file that already exists in the target (`if [ ! -f ... ]`). Running it against a folder that already has `.kiro/` will not overwrite or update hooks, agents, or steering files. To push updates to an existing project, manually copy the changed files or remove the target files first before re-running the installer.
### README.md mirrors hook configurations — keep them in sync
The hooks table and Example 5 in README.md document the action type (`runCommand` vs `askAgent`) and behavior of each hook. When changing a hook's `then.type` or behavior, update both the hook file and the corresponding README entries to avoid misleading documentation.
### Prefer `askAgent` over `runCommand` for file-event hooks
`runCommand` hooks on `fileEdited` or `fileCreated` events spawn a new terminal session every time they fire, creating friction. Use `askAgent` instead so the agent handles the task inline. Reserve `runCommand` for `userTriggered` hooks where a manual, isolated terminal run is intentional (e.g., `quality-gate`).
---
## Common Pitfalls
*Document mistakes that have been made and how to avoid them.*
### Example: Database Transactions
- Always wrap multiple database operations in a transaction
- Remember to handle rollback on errors
- Don't forget to close connections in finally blocks
---
## Architecture Decisions
*Document key architectural decisions and their rationale.*
### Example: State Management
- **Decision**: Use Zustand for global state, React Context for component trees
- **Rationale**: Zustand provides better performance and simpler API than Redux
- **Trade-offs**: Less ecosystem tooling than Redux, but sufficient for our needs
---
## Notes
- Keep entries concise and actionable
- Remove patterns that are no longer relevant
- Update patterns as the project evolves
- Focus on what's unique to this project

View File

@@ -0,0 +1,36 @@
---
inclusion: auto
description: Common design patterns including repository pattern, API response format, and skeleton project approach
---
# Common Patterns
## Skeleton Projects
When implementing new functionality:
1. Search for battle-tested skeleton projects
2. Use parallel agents to evaluate options:
- Security assessment
- Extensibility analysis
- Relevance scoring
- Implementation planning
3. Clone best match as foundation
4. Iterate within proven structure
## Design Patterns
### Repository Pattern
Encapsulate data access behind a consistent interface:
- Define standard operations: findAll, findById, create, update, delete
- Concrete implementations handle storage details (database, API, file, etc.)
- Business logic depends on the abstract interface, not the storage mechanism
- Enables easy swapping of data sources and simplifies testing with mocks
### API Response Format
Use a consistent envelope for all API responses:
- Include a success/status indicator
- Include the data payload (nullable on error)
- Include an error message field (nullable on success)
- Include metadata for paginated responses (total, page, limit)

View File

@@ -0,0 +1,54 @@
---
inclusion: auto
description: Performance optimization guidelines including model selection strategy, context window management, and build troubleshooting
---
# Performance Optimization
## Model Selection Strategy
**Claude Haiku 4.5** (90% of Sonnet capability, 3x cost savings):
- Lightweight agents with frequent invocation
- Pair programming and code generation
- Worker agents in multi-agent systems
**Claude Sonnet 4.5** (Best coding model):
- Main development work
- Orchestrating multi-agent workflows
- Complex coding tasks
**Claude Opus 4.5** (Deepest reasoning):
- Complex architectural decisions
- Maximum reasoning requirements
- Research and analysis tasks
## Context Window Management
Avoid last 20% of context window for:
- Large-scale refactoring
- Feature implementation spanning multiple files
- Debugging complex interactions
Lower context sensitivity tasks:
- Single-file edits
- Independent utility creation
- Documentation updates
- Simple bug fixes
## Extended Thinking
Extended thinking is enabled by default in Kiro, reserving tokens for internal reasoning.
For complex tasks requiring deep reasoning:
1. Ensure extended thinking is enabled
2. Use structured approach for planning
3. Use multiple critique rounds for thorough analysis
4. Use sub-agents for diverse perspectives
## Build Troubleshooting
If build fails:
1. Use build-error-resolver agent
2. Analyze error messages
3. Fix incrementally
4. Verify after each fix

View File

@@ -0,0 +1,40 @@
---
inclusion: fileMatch
fileMatchPattern: "*.py"
description: Python patterns extending common rules
---
# Python Patterns
> This file extends the common patterns rule with Python specific content.
## Protocol (Duck Typing)
```python
from typing import Protocol
class Repository(Protocol):
def find_by_id(self, id: str) -> dict | None: ...
def save(self, entity: dict) -> dict: ...
```
## Dataclasses as DTOs
```python
from dataclasses import dataclass
@dataclass
class CreateUserRequest:
name: str
email: str
age: int | None = None
```
## Context Managers & Generators
- Use context managers (`with` statement) for resource management
- Use generators for lazy evaluation and memory-efficient iteration
## Reference
See skill: `python-patterns` for comprehensive patterns including decorators, concurrency, and package organization.

View File

@@ -0,0 +1,62 @@
---
inclusion: manual
description: Research mode context for exploring technologies, architectures, and design decisions
---
# Research Mode
Use this context when researching technologies, evaluating options, or making architectural decisions.
## Research Process
1. Define the problem or question clearly
2. Identify evaluation criteria
3. Research available options
4. Compare options against criteria
5. Document findings and recommendations
6. Consider trade-offs and constraints
## Evaluation Criteria
### Technical Fit
- Does it solve the problem effectively?
- Is it compatible with existing stack?
- What are the technical constraints?
### Maturity & Support
- Is the technology mature and stable?
- Is there active community support?
- Is documentation comprehensive?
- Are there known issues or limitations?
### Performance & Scalability
- What are the performance characteristics?
- How does it scale?
- What are the resource requirements?
### Developer Experience
- Is it easy to learn and use?
- Are there good tooling and IDE support?
- What's the debugging experience like?
### Long-term Viability
- Is the project actively maintained?
- What's the adoption trend?
- Are there migration paths if needed?
### Cost & Licensing
- What are the licensing terms?
- What are the operational costs?
- Are there vendor lock-in concerns?
## Documentation
- Document decision rationale
- List pros and cons of each option
- Include relevant benchmarks or comparisons
- Note any assumptions or constraints
- Provide recommendations with justification
## Invocation
Use `#research-mode` to activate this context when researching or evaluating options.

View File

@@ -0,0 +1,56 @@
---
inclusion: manual
description: Code review mode context for thorough quality and security assessment
---
# Review Mode
Use this context when conducting code reviews or quality assessments.
## Review Process
1. Gather context — Check git diff to see all changes
2. Understand scope — Identify which files changed and why
3. Read surrounding code — Don't review in isolation
4. Apply review checklist — Work through each category
5. Report findings — Use severity levels
## Review Checklist
### Correctness
- Does the code do what it's supposed to do?
- Are edge cases handled properly?
- Is error handling appropriate?
### Security
- Are inputs validated and sanitized?
- Are secrets properly managed?
- Are there any injection vulnerabilities?
- Is authentication/authorization correct?
### Performance
- Are there obvious performance issues?
- Are database queries optimized?
- Is caching used appropriately?
### Maintainability
- Is the code readable and well-organized?
- Are functions and classes appropriately sized?
- Is there adequate documentation?
- Are naming conventions followed?
### Testing
- Are there sufficient tests?
- Do tests cover edge cases?
- Are tests clear and maintainable?
## Severity Levels
- **Critical**: Security vulnerabilities, data loss risks
- **High**: Bugs that break functionality, major performance issues
- **Medium**: Code quality issues, maintainability concerns
- **Low**: Style inconsistencies, minor improvements
## Invocation
Use `#review-mode` to activate this context when reviewing code.

View File

@@ -0,0 +1,34 @@
---
inclusion: auto
description: Security best practices including mandatory checks, secret management, and security response protocol.
---
# Security Guidelines
## Mandatory Security Checks
Before ANY commit:
- [ ] No hardcoded secrets (API keys, passwords, tokens)
- [ ] All user inputs validated
- [ ] SQL injection prevention (parameterized queries)
- [ ] XSS prevention (sanitized HTML)
- [ ] CSRF protection enabled
- [ ] Authentication/authorization verified
- [ ] Rate limiting on all endpoints
- [ ] Error messages don't leak sensitive data
## Secret Management
- NEVER hardcode secrets in source code
- ALWAYS use environment variables or a secret manager
- Validate that required secrets are present at startup
- Rotate any secrets that may have been exposed
## Security Response Protocol
If security issue found:
1. STOP immediately
2. Use **security-reviewer** agent
3. Fix CRITICAL issues before continuing
4. Rotate any exposed secrets
5. Review entire codebase for similar issues

View File

@@ -0,0 +1,67 @@
---
inclusion: fileMatch
fileMatchPattern: "*.swift"
description: Swift-specific patterns including protocol-oriented design, value types, actor pattern, and dependency injection
---
# Swift Patterns
> This file extends the common patterns with Swift specific content.
## Protocol-Oriented Design
Define small, focused protocols. Use protocol extensions for shared defaults:
```swift
protocol Repository: Sendable {
associatedtype Item: Identifiable & Sendable
func find(by id: Item.ID) async throws -> Item?
func save(_ item: Item) async throws
}
```
## Value Types
- Use structs for data transfer objects and models
- Use enums with associated values to model distinct states:
```swift
enum LoadState<T: Sendable>: Sendable {
case idle
case loading
case loaded(T)
case failed(Error)
}
```
## Actor Pattern
Use actors for shared mutable state instead of locks or dispatch queues:
```swift
actor Cache<Key: Hashable & Sendable, Value: Sendable> {
private var storage: [Key: Value] = [:]
func get(_ key: Key) -> Value? { storage[key] }
func set(_ key: Key, value: Value) { storage[key] = value }
}
```
## Dependency Injection
Inject protocols with default parameters -- production uses defaults, tests inject mocks:
```swift
struct UserService {
private let repository: any UserRepository
init(repository: any UserRepository = DefaultUserRepository()) {
self.repository = repository
}
}
```
## References
See skill: `swift-actor-persistence` for actor-based persistence patterns.
See skill: `swift-protocol-di-testing` for protocol-based DI and testing.

34
.kiro/steering/testing.md Normal file
View File

@@ -0,0 +1,34 @@
---
inclusion: auto
description: Testing requirements including 80% coverage, TDD workflow, and test types.
---
# Testing Requirements
## Minimum Test Coverage: 80%
Test Types (ALL required):
1. **Unit Tests** - Individual functions, utilities, components
2. **Integration Tests** - API endpoints, database operations
3. **E2E Tests** - Critical user flows (framework chosen per language)
## Test-Driven Development
MANDATORY workflow:
1. Write test first (RED)
2. Run test - it should FAIL
3. Write minimal implementation (GREEN)
4. Run test - it should PASS
5. Refactor (IMPROVE)
6. Verify coverage (80%+)
## Troubleshooting Test Failures
1. Use **tdd-guide** agent
2. Check test isolation
3. Verify mocks are correct
4. Fix implementation, not tests (unless tests are wrong)
## Agent Support
- **tdd-guide** - Use PROACTIVELY for new features, enforces write-tests-first

View File

@@ -0,0 +1,51 @@
---
inclusion: fileMatch
fileMatchPattern: "*.ts,*.tsx"
description: TypeScript and JavaScript patterns extending common rules
---
# TypeScript/JavaScript Patterns
> This file extends the common patterns rule with TypeScript/JavaScript specific content.
## API Response Format
```typescript
interface ApiResponse<T> {
success: boolean
data?: T
error?: string
meta?: {
total: number
page: number
limit: number
}
}
```
## Custom Hooks Pattern
```typescript
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay)
return () => clearTimeout(handler)
}, [value, delay])
return debouncedValue
}
```
## Repository Pattern
```typescript
interface Repository<T> {
findAll(filters?: Filters): Promise<T[]>
findById(id: string): Promise<T | null>
create(data: CreateDto): Promise<T>
update(id: string, data: UpdateDto): Promise<T>
delete(id: string): Promise<void>
}
```

View File

@@ -0,0 +1,98 @@
---
inclusion: fileMatch
fileMatchPattern: "*.ts,*.tsx,*.js,*.jsx"
description: TypeScript/JavaScript security best practices extending common security rules with language-specific concerns
---
# TypeScript/JavaScript Security
> This file extends the common security rule with TypeScript/JavaScript specific content.
## Secret Management
```typescript
// NEVER: Hardcoded secrets
const apiKey = "sk-proj-xxxxx"
const dbPassword = "mypassword123"
// ALWAYS: Environment variables
const apiKey = process.env.OPENAI_API_KEY
const dbPassword = process.env.DATABASE_PASSWORD
if (!apiKey) {
throw new Error('OPENAI_API_KEY not configured')
}
```
## XSS Prevention
```typescript
// NEVER: Direct HTML injection
element.innerHTML = userInput
// ALWAYS: Sanitize or use textContent
import DOMPurify from 'dompurify'
element.innerHTML = DOMPurify.sanitize(userInput)
// OR
element.textContent = userInput
```
## Prototype Pollution
```typescript
// NEVER: Unsafe object merging
function merge(target: any, source: any) {
for (const key in source) {
target[key] = source[key] // Dangerous!
}
}
// ALWAYS: Validate keys
function merge(target: any, source: any) {
for (const key in source) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
continue
}
target[key] = source[key]
}
}
```
## SQL Injection (Node.js)
```typescript
// NEVER: String concatenation
const query = `SELECT * FROM users WHERE id = ${userId}`
// ALWAYS: Parameterized queries
const query = 'SELECT * FROM users WHERE id = ?'
db.query(query, [userId])
```
## Path Traversal
```typescript
// NEVER: Direct path construction
const filePath = `./uploads/${req.params.filename}`
// ALWAYS: Validate and sanitize
import path from 'path'
const filename = path.basename(req.params.filename)
const filePath = path.join('./uploads', filename)
```
## Dependency Security
```bash
# Regular security audits
npm audit
npm audit fix
# Use lock files
npm ci # Instead of npm install in CI/CD
```
## Agent Support
- Use **security-reviewer** agent for comprehensive security audits
- Invoke via `/agent swap security-reviewer` or use the security-review skill