Add Kiro steering files, hooks, and scripts (#812)

Co-authored-by: Sungmin Hong <hsungmin@amazon.com>
This commit is contained in:
Himanshu Sharma
2026-03-22 21:55:47 -07:00
committed by GitHub
parent 535120d6b1
commit bacc585b87
29 changed files with 1241 additions and 0 deletions

93
.kiro/hooks/README.md Normal file
View File

@@ -0,0 +1,93 @@
# Hooks in Kiro
Kiro supports **two types of hooks**:
1. **IDE Hooks** (this directory) - Standalone `.kiro.hook` files that work in the Kiro IDE
2. **CLI Hooks** - Embedded in agent configuration files for CLI usage
## IDE Hooks (Standalone Files)
IDE hooks are `.kiro.hook` files in `.kiro/hooks/` that appear in the Agent Hooks panel in the Kiro IDE.
### Format
```json
{
"version": "1.0.0",
"enabled": true,
"name": "hook-name",
"description": "What this hook does",
"when": {
"type": "fileEdited",
"patterns": ["*.ts", "*.tsx"]
},
"then": {
"type": "runCommand",
"command": "npx tsc --noEmit",
"timeout": 30
}
}
```
### Required Fields
- `version` - Hook version (e.g., "1.0.0")
- `enabled` - Whether the hook is active (true/false)
- `name` - Hook identifier (kebab-case)
- `description` - Human-readable description
- `when` - Trigger configuration
- `then` - Action to perform
### Available Trigger Types
- `fileEdited` - When a file matching patterns is edited
- `fileCreated` - When a file matching patterns is created
- `fileDeleted` - When a file matching patterns is deleted
- `userTriggered` - Manual trigger from Agent Hooks panel
- `promptSubmit` - When user submits a prompt
- `agentStop` - When agent finishes responding
- `preToolUse` - Before a tool is executed (requires `toolTypes`)
- `postToolUse` - After a tool is executed (requires `toolTypes`)
### Action Types
- `runCommand` - Execute a shell command
- Optional `timeout` field (in seconds)
- `askAgent` - Send a prompt to the agent
### Environment Variables
When hooks run, these environment variables are available:
- `$KIRO_HOOK_FILE` - Path to the file that triggered the hook (for file events)
## CLI Hooks (Embedded in Agents)
CLI hooks are embedded in agent configuration files (`.kiro/agents/*.json`) for use with `kiro-cli`.
### Format
```json
{
"name": "my-agent",
"hooks": {
"agentSpawn": [
{
"command": "git status"
}
],
"postToolUse": [
{
"matcher": "fs_write",
"command": "npx tsc --noEmit"
}
]
}
}
```
See `.kiro/agents/tdd-guide-with-hooks.json` for a complete example.
## Documentation
- IDE Hooks: https://kiro.dev/docs/hooks/
- CLI Hooks: https://kiro.dev/docs/cli/hooks/

View File

@@ -0,0 +1,14 @@
{
"name": "auto-format",
"version": "1.0.0",
"enabled": true,
"description": "Automatically format TypeScript and JavaScript files on save",
"when": {
"type": "fileEdited",
"patterns": ["*.ts", "*.tsx", "*.js"]
},
"then": {
"type": "askAgent",
"prompt": "A TypeScript or JavaScript file was just saved. If there are any obvious formatting issues (indentation, trailing whitespace, import ordering), fix them now."
}
}

View File

@@ -0,0 +1,14 @@
{
"name": "code-review-on-write",
"version": "1.0.0",
"enabled": true,
"description": "Performs a quick code review after write operations to catch common issues",
"when": {
"type": "postToolUse",
"toolTypes": ["write"]
},
"then": {
"type": "askAgent",
"prompt": "Code was just written or modified. Perform a quick review checking for: 1) Common security issues (SQL injection, XSS, etc.), 2) Error handling, 3) Code clarity and maintainability, 4) Potential bugs or edge cases. Only comment if you find issues worth addressing."
}
}

View File

@@ -0,0 +1,14 @@
{
"version": "1.0.0",
"enabled": true,
"name": "console-log-check",
"description": "Check for console.log statements in JavaScript and TypeScript files to prevent debug code from being committed.",
"when": {
"type": "fileEdited",
"patterns": ["*.js", "*.ts", "*.tsx"]
},
"then": {
"type": "askAgent",
"prompt": "A JavaScript or TypeScript file was just saved. Check if it contains any console.log statements that should be removed before committing. If found, flag them and offer to remove them."
}
}

View File

@@ -0,0 +1,14 @@
{
"name": "doc-file-warning",
"version": "1.0.0",
"enabled": true,
"description": "Warn before creating documentation files to avoid unnecessary documentation",
"when": {
"type": "preToolUse",
"toolTypes": ["write"]
},
"then": {
"type": "askAgent",
"prompt": "You are about to create or modify a file. If this is a documentation file (README, CHANGELOG, docs/, etc.) that was not explicitly requested by the user, consider whether it's truly necessary. Documentation should be created only when:\n\n1. Explicitly requested by the user\n2. Required for project setup or usage\n3. Part of a formal specification or requirement\n\nIf you're creating documentation that wasn't requested, briefly explain why it's necessary or skip it. Proceed with the write operation if appropriate."
}
}

View File

@@ -0,0 +1,13 @@
{
"name": "extract-patterns",
"version": "1.0.0",
"enabled": true,
"description": "Suggest patterns to add to lessons-learned.md after agent execution completes",
"when": {
"type": "agentStop"
},
"then": {
"type": "askAgent",
"prompt": "Review the conversation that just completed. If you identified any genuinely useful patterns, code style preferences, common pitfalls, or architecture decisions that would benefit future work on this project, suggest adding them to .kiro/steering/lessons-learned.md. Only suggest patterns that are:\n\n1. Project-specific (not general best practices already covered in other steering files)\n2. Repeatedly applicable (not one-off solutions)\n3. Non-obvious (insights that aren't immediately apparent)\n4. Actionable (clear guidance for future development)\n\nIf no such patterns emerged from this conversation, simply respond with 'No new patterns to extract.' Do not force pattern extraction from every interaction."
}
}

View File

@@ -0,0 +1,14 @@
{
"name": "git-push-review",
"version": "1.0.0",
"enabled": true,
"description": "Reviews shell commands before execution to catch potentially destructive git operations",
"when": {
"type": "preToolUse",
"toolTypes": ["shell"]
},
"then": {
"type": "askAgent",
"prompt": "A shell command is about to be executed. If this is a git push or other potentially destructive operation, verify that: 1) All tests pass, 2) Code has been reviewed, 3) Commit messages are clear, 4) The target branch is correct. If it's a routine command, proceed without comment."
}
}

View File

@@ -0,0 +1,13 @@
{
"version": "1.0.0",
"enabled": true,
"name": "quality-gate",
"description": "Run a full quality gate check (build, type check, lint, tests). Trigger manually from the Agent Hooks panel.",
"when": {
"type": "userTriggered"
},
"then": {
"type": "runCommand",
"command": "bash .kiro/scripts/quality-gate.sh"
}
}

View File

@@ -0,0 +1,13 @@
{
"name": "session-summary",
"version": "1.0.0",
"enabled": true,
"description": "Generate a brief summary of what was accomplished after agent execution completes",
"when": {
"type": "agentStop"
},
"then": {
"type": "askAgent",
"prompt": "Provide a brief 2-3 sentence summary of what was accomplished in this conversation. Focus on concrete outcomes: files created/modified, problems solved, decisions made. Keep it concise and actionable."
}
}

View File

@@ -0,0 +1,14 @@
{
"name": "tdd-reminder",
"version": "1.0.0",
"enabled": true,
"description": "Reminds the agent to consider writing tests when new TypeScript files are created",
"when": {
"type": "fileCreated",
"patterns": ["*.ts", "*.tsx"]
},
"then": {
"type": "askAgent",
"prompt": "A new TypeScript file was just created. Consider whether this file needs corresponding test coverage. If it contains logic that should be tested, suggest creating a test file following TDD principles."
}
}

View File

@@ -0,0 +1,14 @@
{
"version": "1.0.0",
"enabled": true,
"name": "typecheck-on-edit",
"description": "Run TypeScript type checking when TypeScript files are edited to catch type errors early.",
"when": {
"type": "fileEdited",
"patterns": ["*.ts", "*.tsx"]
},
"then": {
"type": "askAgent",
"prompt": "A TypeScript file was just saved. Check for any obvious type errors or type safety issues in the modified file and flag them if found."
}
}

70
.kiro/scripts/format.sh Executable file
View File

@@ -0,0 +1,70 @@
#!/bin/bash
# ─────────────────────────────────────────────────────────────
# Format — auto-format a file using detected formatter
# Detects: biome or prettier
# Used by: .kiro/hooks/auto-format.json (fileEdited)
# ─────────────────────────────────────────────────────────────
set -o pipefail
# ── Validate input ───────────────────────────────────────────
if [ -z "$1" ]; then
echo "Usage: format.sh <file>"
echo "Example: format.sh src/index.ts"
exit 1
fi
FILE="$1"
if [ ! -f "$FILE" ]; then
echo "Error: File not found: $FILE"
exit 1
fi
# ── Detect formatter ─────────────────────────────────────────
detect_formatter() {
if [ -f "biome.json" ] || [ -f "biome.jsonc" ]; then
echo "biome"
elif [ -f ".prettierrc" ] || [ -f ".prettierrc.js" ] || [ -f ".prettierrc.json" ] || [ -f ".prettierrc.yml" ] || [ -f "prettier.config.js" ] || [ -f "prettier.config.mjs" ]; then
echo "prettier"
elif command -v biome &>/dev/null; then
echo "biome"
elif command -v prettier &>/dev/null; then
echo "prettier"
else
echo "none"
fi
}
FORMATTER=$(detect_formatter)
# ── Format file ──────────────────────────────────────────────
case "$FORMATTER" in
biome)
if command -v npx &>/dev/null; then
echo "Formatting $FILE with Biome..."
npx biome format --write "$FILE"
exit $?
else
echo "Error: npx not found (required for Biome)"
exit 1
fi
;;
prettier)
if command -v npx &>/dev/null; then
echo "Formatting $FILE with Prettier..."
npx prettier --write "$FILE"
exit $?
else
echo "Error: npx not found (required for Prettier)"
exit 1
fi
;;
none)
echo "No formatter detected (biome.json, .prettierrc, or installed formatter)"
echo "Skipping format for: $FILE"
exit 0
;;
esac

120
.kiro/scripts/quality-gate.sh Executable file
View File

@@ -0,0 +1,120 @@
#!/bin/bash
# ─────────────────────────────────────────────────────────────
# Quality Gate — full project quality check
# Runs: build, type check, lint, tests
# Used by: .kiro/hooks/quality-gate.json (userTriggered)
# ─────────────────────────────────────────────────────────────
set -o pipefail
PASS="✓"
FAIL="✗"
SKIP="○"
PASSED=0
FAILED=0
SKIPPED=0
# ── Package manager detection ────────────────────────────────
detect_pm() {
if [ -f "pnpm-lock.yaml" ]; then
echo "pnpm"
elif [ -f "yarn.lock" ]; then
echo "yarn"
elif [ -f "bun.lockb" ] || [ -f "bun.lock" ]; then
echo "bun"
elif [ -f "package-lock.json" ]; then
echo "npm"
elif command -v pnpm &>/dev/null; then
echo "pnpm"
elif command -v yarn &>/dev/null; then
echo "yarn"
elif command -v bun &>/dev/null; then
echo "bun"
else
echo "npm"
fi
}
PM=$(detect_pm)
echo "📦 Package manager: $PM"
echo ""
# ── Helper: run a check ─────────────────────────────────────
run_check() {
local label="$1"
shift
if output=$("$@" 2>&1); then
echo "$PASS $label"
PASSED=$((PASSED + 1))
else
echo "$FAIL $label"
echo "$output" | head -20
FAILED=$((FAILED + 1))
fi
}
# ── 1. Build ─────────────────────────────────────────────────
if [ -f "package.json" ] && grep -q '"build"' package.json 2>/dev/null; then
run_check "Build" $PM run build
else
echo "$SKIP Build (no build script found)"
SKIPPED=$((SKIPPED + 1))
fi
# ── 2. Type check ───────────────────────────────────────────
if command -v npx &>/dev/null && [ -f "tsconfig.json" ]; then
run_check "Type check" npx tsc --noEmit
elif [ -f "pyrightconfig.json" ] || [ -f "mypy.ini" ]; then
if command -v pyright &>/dev/null; then
run_check "Type check" pyright
elif command -v mypy &>/dev/null; then
run_check "Type check" mypy .
else
echo "$SKIP Type check (pyright/mypy not installed)"
SKIPPED=$((SKIPPED + 1))
fi
else
echo "$SKIP Type check (no TypeScript or Python type config found)"
SKIPPED=$((SKIPPED + 1))
fi
# ── 3. Lint ──────────────────────────────────────────────────
if [ -f "biome.json" ] || [ -f "biome.jsonc" ]; then
run_check "Lint (Biome)" npx biome check .
elif [ -f ".eslintrc" ] || [ -f ".eslintrc.js" ] || [ -f ".eslintrc.json" ] || [ -f ".eslintrc.yml" ] || [ -f "eslint.config.js" ] || [ -f "eslint.config.mjs" ]; then
run_check "Lint (ESLint)" npx eslint .
elif command -v ruff &>/dev/null && [ -f "pyproject.toml" ]; then
run_check "Lint (Ruff)" ruff check .
elif command -v golangci-lint &>/dev/null && [ -f "go.mod" ]; then
run_check "Lint (golangci-lint)" golangci-lint run
else
echo "$SKIP Lint (no linter config found)"
SKIPPED=$((SKIPPED + 1))
fi
# ── 4. Tests ─────────────────────────────────────────────────
if [ -f "package.json" ] && grep -q '"test"' package.json 2>/dev/null; then
run_check "Tests" $PM run test
elif [ -f "pyproject.toml" ] && command -v pytest &>/dev/null; then
run_check "Tests" pytest
elif [ -f "go.mod" ] && command -v go &>/dev/null; then
run_check "Tests" go test ./...
else
echo "$SKIP Tests (no test runner found)"
SKIPPED=$((SKIPPED + 1))
fi
# ── Summary ──────────────────────────────────────────────────
echo ""
echo "─────────────────────────────────────"
TOTAL=$((PASSED + FAILED + SKIPPED))
echo "Results: $PASSED passed, $FAILED failed, $SKIPPED skipped ($TOTAL total)"
if [ "$FAILED" -gt 0 ]; then
echo "Quality gate: FAILED"
exit 1
else
echo "Quality gate: PASSED"
exit 0
fi

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