diff --git a/.claude/agents-en/requirement-analyzer.md b/.claude/agents-en/requirement-analyzer.md index 3c92695..744728b 100644 --- a/.claude/agents-en/requirement-analyzer.md +++ b/.claude/agents-en/requirement-analyzer.md @@ -45,34 +45,13 @@ Scale determination and required document details follow @docs/rules/documentati ## Conditions Requiring ADR -Detailed ADR creation conditions are defined in @docs/rules/documentation-criteria.md. +Detailed ADR creation conditions follow @docs/rules/documentation-criteria.md. ### Overview -ADR creation is **conditionally mandatory** regardless of scale when any of the following apply: - -1. **Type System Changes** - - Nested types with 3+ levels (e.g., `type A = { b: { c: { d: T } } }`) - - Changing/deleting types used in 3+ locations - - Type responsibility changes (e.g., DTO→Entity) - -2. **Data Flow Changes** - - Storage location changes (DB→File, Memory→Cache) - - Processing order changes with 3+ steps - - Data passing method changes (props→Context, direct reference→events) - -3. **Architecture Changes** - - Layer addition, responsibility changes, component relocation - -4. **External Dependency Changes** - - Library/framework/external API introduction or replacement - -5. **Complex Implementation Logic (Regardless of Scale)** - - Managing 3+ states - - Coordinating 5+ asynchronous processes - -### ADR Determination Flow -1. Does it match any of the above conditions? → Yes: ADR mandatory / No: Next -2. Apply document requirements based on scale +- Type system changes (3+ level nesting, types used in 3+ locations) +- Data flow changes (storage location, processing order, passing methods) +- Architecture changes (layer addition, responsibility changes) +- External dependency changes (libraries, frameworks, APIs) ## Ensuring Determination Consistency diff --git a/.claude/commands-en/build.md b/.claude/commands-en/build.md index a2bdf8a..00204e7 100644 --- a/.claude/commands-en/build.md +++ b/.claude/commands-en/build.md @@ -2,8 +2,6 @@ description: Execute decomposed tasks in autonomous execution mode --- -**Command Context**: This command is dedicated to the implementation phase with autonomous execution. - Strictly follow @docs/guides/sub-agents.md and act as an orchestrator. Work plan: $ARGUMENTS @@ -22,8 +20,6 @@ Before starting any task, always: Verify approval status before proceeding. Once confirmed, initiate autonomous execution mode. -**Scope**: From task decomposition through implementation completion. Immediate halt upon detecting requirement changes. - ## Output Example Implementation phase completed. - Task decomposition: Generated under docs/plans/tasks/ diff --git a/docs/design/template-en.md b/docs/design/template-en.md index ba00687..7b3a913 100644 --- a/docs/design/template-en.md +++ b/docs/design/template-en.md @@ -14,11 +14,11 @@ ### Agreement Checklist #### Scope -- [ ] [Functions/components to change] -- [ ] [Functions to add] +- [ ] [Features/components to change] +- [ ] [Features to add] #### Non-Scope (Explicitly not changing) -- [ ] [Functions/components not to change] +- [ ] [Features/components not to change] - [ ] [Existing logic to preserve] #### Constraints @@ -28,11 +28,11 @@ ### Problem to Solve -[Specific problems or challenges this feature aims to solve] +[Specific problems or challenges this feature aims to address] ### Current Challenges -[Problems or limitations in the current system] +[Current system issues or limitations] ### Requirements @@ -42,58 +42,87 @@ #### Non-Functional Requirements -- **Performance**: [Requirements for response time, throughput, etc.] +- **Performance**: [Response time, throughput requirements] - **Scalability**: [Requirements for handling increased load] -- **Reliability**: [Requirements for error rate, availability, etc.] -- **Maintainability**: [Code understandability, ease of modification] +- **Reliability**: [Error rate, availability requirements] +- **Maintainability**: [Code readability and changeability] ## Acceptance Criteria -Define specific and verifiable conditions for determining successful implementation of each functional requirement. -These conditions serve as the basis for test cases and are used to objectively judge implementation completion. -(Note: Checkboxes remain empty at design time since implementation is not yet complete) +Define specific and verifiable conditions that determine successful implementation for each functional requirement. +These conditions serve as the basis for test cases and are used to objectively determine implementation completion. +(Note: Checkboxes remain empty at design time as implementation is not yet complete) - [ ] [Specific acceptance criteria for functional requirement 1] - Example: "When user clicks login button, authentication succeeds with correct credentials" - - Example: "When invalid credentials are entered, appropriate error message displays" + - Example: "When credentials are invalid, appropriate error message is displayed" - [ ] [Specific acceptance criteria for functional requirement 2] - - Example: "In data list screen, pagination displays 10 items per page" - - Example: "When typing in search field, real-time filtering occurs" + - Example: "Data list screen displays with pagination of 10 items per page" + - Example: "When input is entered in search field, real-time filtering is applied" ## Existing Codebase Analysis ### Implementation Path Mapping | Type | Path | Description | |------|------|-------------| -| Existing | src/[actual path] | [Current implementation] | -| New | src/[planned path] | [Planned new creation] | +| Existing | src/[actual-path] | [Current implementation] | +| New | src/[planned-path] | [Planned new creation] | -### Integration Points -| Integration Point | Location | Old Implementation | New Implementation | Switch Method | -|------------------|----------|-------------------|-------------------|---------------| -| Point 1 | [Class/Function] | [Existing process] | [New process] | [DI/Factory etc.] | -| Point 2 | [Another location] | [Existing] | [New] | [Method] | +### Integration Points (Include even for new implementations) +- **Integration Target**: [What to connect with] +- **Invocation Method**: [How it will be invoked] -### Main Components +## Design -#### Component 1 +### Change Impact Map + +```yaml +Change Target: [Component/feature to change] +Direct Impact: + - [Files/functions requiring direct changes] + - [Interface change points] +Indirect Impact: + - [Data format changes] + - [Processing time changes] +No Ripple Effect: + - [Explicitly specify unaffected features] +``` + +### Architecture Overview + +[How this feature is positioned within the overall system] + +### Data Flow + +``` +[Express data flow using diagrams or pseudo-code] +``` -**Responsibility**: [What this component is responsible for] +### Integration Points List -**Input/Output**: -- Input: [What it receives] -- Output: [What it returns] +| Integration Point | Location | Old Implementation | New Implementation | Switching Method | +|-------------------|----------|-------------------|-------------------|------------------| +| Integration Point 1 | [Class/Function] | [Existing Process] | [New Process] | [DI/Factory etc.] | +| Integration Point 2 | [Another Location] | [Existing] | [New] | [Method] | -**Dependencies**: [What other components it depends on] +### Main Components + +#### Component 1 + +- **Responsibility**: [Scope of responsibility for this component] +- **Interface**: [APIs and type definitions provided] +- **Dependencies**: [Relationships with other components] #### Component 2 -[Same format] +- **Responsibility**: [Scope of responsibility for this component] +- **Interface**: [APIs and type definitions provided] +- **Dependencies**: [Relationships with other components] -## Type Definitions +### Type Definitions ```typescript -// Include main type definitions here +// Record major type definitions here ``` ### Data Contract @@ -108,17 +137,17 @@ Input: Output: Type: [TypeScript type definition] - Guarantees: [Conditions always satisfied] + Guarantees: [Conditions that must always be met] On Error: [Exception/null/default value] Invariants: - - [Conditions that remain unchanged before/after processing] + - [Conditions that remain unchanged before and after processing] ``` ### State Transitions and Invariants (When Applicable) ```yaml -State Definitions: +State Definition: - Initial State: [Initial values and conditions] - Possible States: [List of states] @@ -131,28 +160,28 @@ System Invariants: ### Error Handling -[Types of errors and handling methods] +[Types of errors and how to handle them] -### Security Considerations +### Logging and Monitoring -[Security measures, authentication, authorization, data protection] +[What to record in logs and how to monitor] ## Implementation Plan ### Phase Division #### Phase 1: [Phase Name] -**Purpose**: [What this phase aims to achieve] +**Purpose**: [What to achieve in this phase] -**Implementation Content**: +**Implementation Items**: - [Implementation item 1] - [Implementation item 2] -(Duration goes to work plan) +(Timeline goes to work plan document) -**Phase Completion Criteria**: -- [ ] [Functional completion criteria] -- [ ] [Quality completion criteria] +**Phase Completion Conditions**: +- [ ] [Functional completion conditions] +- [ ] [Quality completion conditions] **E2E Verification Procedures**: 1. [Operation verification steps] @@ -160,15 +189,15 @@ System Invariants: 3. [Performance verification (when applicable)] #### Phase 2: [Phase Name] -**Purpose**: [What this phase aims to achieve] +**Purpose**: [What to achieve in this phase] -**Implementation Content**: +**Implementation Items**: - [Implementation item 1] - [Implementation item 2] -**Phase Completion Criteria**: -- [ ] [Functional completion criteria] -- [ ] [Quality completion criteria] +**Phase Completion Conditions**: +- [ ] [Functional completion conditions] +- [ ] [Quality completion conditions] **E2E Verification Procedures**: 1. [Operation verification steps] @@ -176,60 +205,66 @@ System Invariants: ### Migration Strategy -[Technical migration approach, backward compatibility assurance methods] +[Technical migration approach, ensuring backward compatibility] ## Test Strategy -### Test Categories +### Basic Test Design Policy + +Automatically derive test cases from acceptance criteria: +- Create at least one test case for each acceptance criterion +- Implement measurable standards from acceptance criteria as assertions -#### Unit Tests -- [Testing scope and methods] -- Target coverage: [percentage] +### Unit Tests -#### Integration Tests -- [What integration points to test] +[Unit testing policy and coverage goals] +- Verify individual elements of functional acceptance criteria -#### E2E Tests -- [Main scenarios to test] +### Integration Tests -### Test Data +[Integration testing policy and important test cases] +- Verify combined operations of functional acceptance criteria -[Test data requirements and preparation methods] +### E2E Tests -## Performance and Monitoring +[E2E testing policy] +- Verify entire scenarios of acceptance criteria +- Confirm functional operation from user perspective -### Performance Targets +### Performance Tests -- Response time: [target value] -- Throughput: [target value] -- Resource usage: [memory, CPU, etc.] +[Performance testing methods and standards] +- Verify performance standards of non-functional acceptance criteria -### Monitoring +## Security Considerations -[Metrics to monitor, logging strategy] +[Security concerns and countermeasures] -## Deployment and Operations +## Future Extensibility -### Deployment Strategy +[Considerations for future feature additions or changes] -[Deployment method, rollback plan] +## Alternative Solutions -### Feature Flags +### Alternative 1 -[If feature flags are used, describe control method] +- **Overview**: [Description of alternative solution] +- **Advantages**: [Advantages] +- **Disadvantages**: [Disadvantages] +- **Reason for Rejection**: [Why it wasn't adopted] ## Risks and Mitigation | Risk | Impact | Probability | Mitigation | |------|--------|-------------|------------| -| [Risk 1] | [High/Medium/Low] | [High/Medium/Low] | [Countermeasure] | -| [Risk 2] | [High/Medium/Low] | [High/Medium/Low] | [Countermeasure] | +| [Risk 1] | High/Medium/Low | High/Medium/Low | [Countermeasure] | -## Open Questions +## References -- [ ] [Question 1] -- [ ] [Question 2] +- [Related documentation and links] -## References +## Update History -- [Related documentation, technical articles, etc.] \ No newline at end of file +| Date | Version | Changes | Author | +|------|---------|---------|--------| +| YYYY-MM-DD | 1.0 | Initial version | [Name] | \ No newline at end of file diff --git a/docs/guides/en/sub-agents.md b/docs/guides/en/sub-agents.md index 83d7d5a..3e85139 100644 --- a/docs/guides/en/sub-agents.md +++ b/docs/guides/en/sub-agents.md @@ -277,22 +277,6 @@ Stop autonomous execution and escalate to user in the following cases: - **Stopping is mandatory**: Always wait for human response at the following timings - **Confirmation → Agreement cycle**: After document generation, proceed to next step after agreement or fix instructions in update mode - **Specific questions**: Make decisions easy with options (A/B/C) or comparison tables -- **Dialogue over efficiency**: Get confirmation early to prevent rework - -### Major Stop Points -- **After requirement-analyzer completion**: Confirmation of requirement analysis results and questions -- **After PRD creation → document-reviewer execution**: Requirement understanding and consistency confirmation (confirm with question list) -- **After ADR creation → document-reviewer execution**: Technical direction and consistency confirmation (present multiple options with comparison table) - - When user approves: Main AI (me) updates Status: Accepted - - When user rejects: Main AI (me) updates Status: Rejected -- **After Design Doc creation → document-reviewer execution**: Design content and consistency confirmation -- **After plan creation**: Batch approval for entire implementation phase (confirm with plan summary) - -### Stop Points During Autonomous Execution -- **When requirement change detected**: Match in requirement change checklist → Return to requirement-analyzer -- **When critical error occurs**: Error report → Wait for response instructions -- **When user interrupts**: Explicit stop instruction → Situation confirmation - ## 🎯 My Action Checklist When receiving a task, I check the following: diff --git a/docs/plans/template-en.md b/docs/plans/template-en.md index ce9967e..44bdcc5 100644 --- a/docs/plans/template-en.md +++ b/docs/plans/template-en.md @@ -103,9 +103,6 @@ Related Issue/PR: #XXX (if any) - [ ] Lint check pass - [ ] Build success -## Progress Tracking -[Track work progress and record any issues encountered] - ## Completion Criteria - [ ] All phases completed - [ ] Each phase's E2E verification procedures executed @@ -113,6 +110,18 @@ Related Issue/PR: #XXX (if any) - [ ] Staged quality checks completed (zero errors) - [ ] All tests pass - [ ] Necessary documentation updated +- [ ] User review approval obtained + +## Progress Tracking +### Phase 1 +- Start: YYYY-MM-DD HH:MM +- Complete: YYYY-MM-DD HH:MM +- Notes: [Any special remarks] + +### Phase 2 +- Start: YYYY-MM-DD HH:MM +- Complete: YYYY-MM-DD HH:MM +- Notes: [Any special remarks] ## Notes -[Record important decisions, changes, or considerations during implementation] \ No newline at end of file +[Special notes, reference information, important points, etc.] \ No newline at end of file diff --git a/docs/rules-en/rules-index.yaml b/docs/rules-en/rules-index.yaml index 2095096..b60f6cb 100644 --- a/docs/rules-en/rules-index.yaml +++ b/docs/rules-en/rules-index.yaml @@ -4,14 +4,18 @@ rules: typescript: file: "typescript.md" - tags: [implementation, type-safety, async, refactoring, coding-style] - typical-use: "TypeScript code creation, modification, and refactoring" + tags: [implementation, type-safety, async, refactoring, coding-style, functional-programming, dependency-injection, branded-types] + typical-use: "TypeScript code creation, modification, refactoring, modern type features utilization" size: medium key-references: - "YAGNI Principle - Kent Beck" - "Clean Code - Robert C. Martin" - "DRY Principle - The Pragmatic Programmer" - "Refactoring - Martin Fowler" + - "TypeScript 4.9 satisfies Operator - Microsoft" + - "Branded Types - TypeScript Community" + - "Effect-TS / fp-ts - Functional Programming" + - "Dependency Injection - Martin Fowler" sections: - "Basic Principles" - "Comment Writing Rules" @@ -24,7 +28,7 @@ rules: typescript-testing: file: "typescript-testing.md" tags: [quality, testing, tdd, coverage, vitest, implementation, debugging, refactoring] - typical-use: "Test creation, TDD practice, quality checks, test-first for implementation/modification" + typical-use: "Test creation, quality checks, development steps for code/bug fixes, refactoring, and new feature implementation" size: medium key-references: - "Test-Driven Development - Kent Beck" @@ -34,6 +38,7 @@ rules: sections: - "Test Framework" - "Basic Testing Policy" + - "Red-Green-Refactor Process (Test-First Development)" - "Test Design Principles" - "Test Helper Utilization Rules" - "Test Implementation Conventions" @@ -67,13 +72,11 @@ rules: key-references: - "ADR Format - Michael Nygard" - "Single Data Source Principle - Single Source of Truth" - - "Dependency Injection (DI) - Martin Fowler" sections: - "Basic Technology Stack Policy" - "Environment Variable Management and Security" - "Architecture Design" - - "Dependency Injection (DI) Pattern" - - "Design Documents and Processes" + - "Unified Data Flow Principles" - "Build and Testing" project-context: @@ -91,39 +94,23 @@ rules: documentation-criteria: file: "documentation-criteria.md" tags: [documentation, adr, prd, design-doc, work-plan, decision-matrix] - typical-use: "Document creation decisions, ADR/PRD/Design Doc requirements, scale determination" + typical-use: "Implementation start scale assessment, document creation decisions, ADR/PRD/Design Doc/work plan creation criteria" size: medium key-references: - "ADR Methodology - Michael Nygard" - "Design Doc Culture - Google Engineering Practices" - - "Product Requirements - Marty Cagan" - - "MoSCoW Method - DSDM Consortium" + - "Single Source of Truth" sections: - "Creation Decision Matrix" - - "ADR Creation Conditions" + - "ADR Creation Conditions (Required if Any Apply)" - "Detailed Document Definitions" - "Creation Process" - "Storage Locations" + - "ADR Status" + - "AI Automation Rules" - "Diagram Requirements" - "Common ADR Relationships" - implementation-approach: - file: "architecture/implementation-approach.md" - tags: [architecture, implementation, task-decomposition, strategy-patterns, strangler-pattern, facade-pattern, design, planning, confirmation-levels] - typical-use: "Implementation strategy pattern selection, Strangler/Facade pattern application decisions, Verification level (L1/L2/L3) definitions, Design Doc strategy selection" - size: medium - key-references: - - "Strangler Fig Pattern - Martin Fowler" - - "Feature Slicing - Martin Fowler" - - "Walking Skeleton - Alistair Cockburn" - - "Facade Pattern - Gang of Four" - sections: - - "Meta-cognitive Strategy Selection Process" - - "Verification Level Definitions" - - "Integration Point Definitions" - - "Anti-patterns" - - "Guidelines for Meta-cognitive Execution" - vertical-slice-architecture: file: "architecture/vertical-slice/rules.md" tags: [architecture, vertical-slice, llm-optimized, single-file, implementation] @@ -158,4 +145,21 @@ rules: - "Coding Conventions" - "Quality Management" - "LLM Implementation Guidelines" - - "Summary" \ No newline at end of file + - "Summary" + + implementation-approach: + file: "architecture/implementation-approach.md" + tags: [architecture, implementation, task-decomposition, strategy-patterns, strangler-pattern, facade-pattern, design, planning, confirmation-levels] + typical-use: "Implementation strategy selection, task decomposition, design decisions, large-scale change planning" + size: medium + key-references: + - "Strangler Fig Pattern - Martin Fowler" + - "Feature Slicing - Martin Fowler" + - "Walking Skeleton - Alistair Cockburn" + - "Facade Pattern - Gang of Four" + sections: + - "Meta-cognitive Strategy Selection Process" + - "Verification Level Definitions" + - "Integration Point Definitions" + - "Anti-patterns" + - "Guidelines for Meta-cognitive Execution" \ No newline at end of file diff --git a/docs/rules-en/technical-spec.md b/docs/rules-en/technical-spec.md index da5f6d4..2d95373 100644 --- a/docs/rules-en/technical-spec.md +++ b/docs/rules-en/technical-spec.md @@ -26,50 +26,13 @@ Select appropriate architecture patterns according to project requirements and s - **Hybrid Progressive Architecture**: Progressive evolution from small to large scale - **Architecture Consistency**: Strictly follow the selected pattern -## Dependency Injection (DI) Pattern +## Unified Data Flow Principles -### Overview -Utilizing Dependency Injection patterns enables: -- Improved testability -- Loose coupling between modules -- Easy implementation replacement - -### Implementation Method -Select appropriate DI patterns or DI libraries according to project scale and requirements. - -## Design Documents and Processes - -### PRD/ADR/Design Doc/work plan Creation Process - -#### Cases Requiring Creation -1. **New Feature Addition**: PRD → ADR (if architectural changes) → Design Doc → work plan → Implementation -2. **Large-scale Changes (6+ files)**: ADR → Design Doc → work plan (mandatory) → Implementation -3. **Medium-scale Changes (3-5 files)**: Consider Design Doc creation → work plan (recommended) → Implementation -4. **Small-scale Modifications (1-2 files)**: Direct implementation - -#### About work plans -- **Storage Location**: `docs/plans/` (excluded by .gitignore) -- **Naming Convention**: `YYYYMMDD-{feature|fix|refactor}-{brief-description}.md` -- **Template**: `docs/plans/template-en.md` -- **Operational Flow**: - 1. Create when starting medium-scale or larger changes - 2. Update progress when each phase completes (checkboxes) - 3. Delete after all tasks complete with user approval - -#### ADR (Architecture Decision Record) -Record important technical decisions to enable future implementers to understand the background of decision-making. - -### Data Flow Unification Principles - -#### Basic Principles -1. **Single Data Source**: Store same information in only one place -2. **Structured Data Priority**: Use parsed objects instead of JSON strings -3. **Clear Responsibility Separation**: Clearly define responsibilities of each layer - -#### Data Flow Best Practices -- **Input Point Validation**: Validate data at input layer and pass internally in type-safe form -- **Centralized Transformation**: Consolidate data transformation logic in dedicated utilities -- **Structured Logging**: Output structured logs at each stage of data flow +### Data Flow Consistency +Maintain consistent data flow throughout the application: +- **Single Source of Truth**: Each piece of data has one authoritative source +- **Unidirectional Flow**: Data flows in a predictable direction +- **Immutable Updates**: Prefer immutable data transformations ## Build and Testing diff --git a/docs/rules-en/typescript-testing.md b/docs/rules-en/typescript-testing.md index cbe6119..5676f15 100644 --- a/docs/rules-en/typescript-testing.md +++ b/docs/rules-en/typescript-testing.md @@ -28,17 +28,26 @@ - Use actual dependencies (DB, API, etc.) - Verify major functional flows -## Test Design Principles +## Red-Green-Refactor Process (Test-First Development) + +**Recommended Principle**: Always start code changes with tests -### Red-Green-Refactor Process (TDD) +**Background**: +- Ensure behavior before changes, prevent regression +- Clarify expected behavior before implementation +- Ensure safety during refactoring -**Principle**: Start all new features and bug fixes with tests +**Development Steps**: +1. **Red**: Write test for expected behavior (it fails) +2. **Green**: Pass test with minimal implementation +3. **Refactor**: Improve code while maintaining passing tests -1. **Red**: Write failing tests -2. **Green**: Pass tests with minimal implementation -3. **Refactor**: Improve code while tests pass +**NG Cases (Test-first not required)**: +- Pure configuration file changes (.env, config, etc.) +- Documentation-only updates (README, comments, etc.) +- Emergency production incident response (post-incident tests mandatory) -**Exceptions**: Configuration changes, documentation updates, refactoring covered by existing tests, emergency response (tests required after) +## Test Design Principles ### Test Case Structure - Tests consist of three stages: "Arrange," "Act," "Assert" diff --git a/docs/rules-en/typescript.md b/docs/rules-en/typescript.md index c904126..5e29798 100644 --- a/docs/rules-en/typescript.md +++ b/docs/rules-en/typescript.md @@ -21,6 +21,29 @@ 3. **Union Types・Intersection Types**: Combinations of multiple types 4. **Type Assertions (Last Resort)**: Only when type is certain +**Modern Type Features** +- **satisfies Operator**: Type check while preserving type inference + ```typescript + const config = { port: 3000 } satisfies Config // ✅ Preserves inference + const config: Config = { port: 3000 } // ❌ Loses inference + ``` +- **const Assertion**: Ensure immutability with literal types + ```typescript + const ROUTES = { HOME: '/' } as const satisfies Routes // ✅ Immutable and type-safe + ``` +- **Branded Types**: Distinguish meaning for same primitive types + ```typescript + type UserId = string & { __brand: 'UserId' } + type OrderId = string & { __brand: 'OrderId' } + // UserId and OrderId are incompatible - prevents mixing + ``` +- **Template Literal Types**: Express string patterns with types + ```typescript + type Route = `/${string}` + type HttpMethod = 'GET' | 'POST' + type Endpoint = `${HttpMethod} ${Route}` + ``` + **Type Safety in Implementation** - API Communication: Always receive responses as `unknown`, validate with type guards - Form Input: External input as `unknown`, type determined after validation @@ -38,6 +61,37 @@ Input Layer (`unknown`) → Type Guard → Business Layer (Type Guaranteed) → ## Coding Conventions +**Class Usage Criteria** +- **Classes Allowed**: + - Framework requirements (NestJS Controller/Service, TypeORM Entity, etc.) + - Custom error class definitions +- **Classes Prohibited**: Use functions and interfaces for everything else + ```typescript + // ✅ Functions and interfaces + interface UserService { create(data: UserData): User } + const userService: UserService = { create: (data) => {...} } + // ❌ Unnecessary class + class UserService { create(data: UserData) {...} } + ``` + +**Function Design** +- **0-2 parameters maximum**: Use object for 3+ parameters + ```typescript + // ✅ Object parameter + function createUser({ name, email, role }: CreateUserParams) {} + // ❌ Multiple parameters + function createUser(name: string, email: string, role: string) {} + ``` + +**Dependency Injection** +- **Inject external dependencies as parameters**: Ensure testability and modularity + ```typescript + // ✅ Receive dependency as parameter + function createService(repository: Repository) { return {...} } + // ❌ Direct import dependency + import { userRepository } from './infrastructure/repository' + ``` + **Asynchronous Processing** - Promise Handling: Always use `async/await` - Error Handling: Always handle with `try-catch` @@ -58,6 +112,17 @@ Input Layer (`unknown`) → Type Guard → Business Layer (Type Guaranteed) → **Absolute Rule**: Error suppression prohibited. All errors must have log output and appropriate handling. +**Result Type Pattern**: Express errors with types for explicit handling +```typescript +type Result = { ok: true; value: T } | { ok: false; error: E } + +// Example: Express error possibility with types +function parseUser(data: unknown): Result { + if (!isValid(data)) return { ok: false, error: new ValidationError() } + return { ok: true, value: data as User } +} +``` + **Custom Error Classes** ```typescript export class AppError extends Error { @@ -85,11 +150,11 @@ Never include sensitive information (password, token, apiKey, secret, creditCard ## Refactoring Techniques **Basic Policy** -- Test First: Create tests to protect existing behavior first - Small Steps: Maintain always-working state through gradual improvements - Safe Changes: Minimize the scope of changes at once +- Behavior Guarantee: Ensure existing behavior remains unchanged while proceeding -**Implementation Procedure**: Understand Current State → Create Protective Tests → Gradual Changes → Verification → Final Confirmation +**Implementation Procedure**: Understand Current State → Gradual Changes → Behavior Verification → Final Validation **Priority**: Duplicate Code Removal > Large Function Division > Complex Conditional Branch Simplification > Type Safety Improvement diff --git a/docs/rules-ja/rules-index.yaml b/docs/rules-ja/rules-index.yaml index 5c2bbdb..ae4b1af 100644 --- a/docs/rules-ja/rules-index.yaml +++ b/docs/rules-ja/rules-index.yaml @@ -4,14 +4,18 @@ rules: typescript: file: "typescript.md" - tags: [implementation, type-safety, async, refactoring, coding-style] - typical-use: "TypeScriptコードの作成・修正・リファクタリング" + tags: [implementation, type-safety, async, refactoring, coding-style, functional-programming, dependency-injection, branded-types] + typical-use: "TypeScriptコードの作成・修正・リファクタリング、モダンな型機能活用" size: medium key-references: - "YAGNI原則 - Kent Beck" - "Clean Code - Robert C. Martin" - "DRY原則 - The Pragmatic Programmer" - "Refactoring - Martin Fowler" + - "TypeScript 4.9 satisfies演算子 - Microsoft" + - "Branded Types - TypeScript Community" + - "Effect-TS / fp-ts - 関数型プログラミング" + - "Dependency Injection - Martin Fowler" sections: - "基本原則" - "コメント記述ルール" @@ -24,7 +28,7 @@ rules: typescript-testing: file: "typescript-testing.md" tags: [quality, testing, tdd, coverage, vitest, implementation, debugging, refactoring] - typical-use: "テスト作成、TDD実践、品質チェック、実装・修正時のテストファースト" + typical-use: "テスト作成、品質チェック、コード修正・バグ修正・リファクタリング・新機能実装時の開発ステップ" size: medium key-references: - "Test-Driven Development - Kent Beck" @@ -34,6 +38,7 @@ rules: sections: - "テストフレームワーク" - "テストの基本方針" + - "Red-Green-Refactorプロセス(テストファースト開発)" - "テストの設計原則" - "テストヘルパーの活用ルール" - "テストの実装規約" @@ -67,13 +72,11 @@ rules: key-references: - "ADRフォーマット - Michael Nygard" - "単一データソース原則 - Single Source of Truth" - - "依存性注入(DI) - Martin Fowler" sections: - "技術スタックの基本方針" - "環境変数管理とセキュリティ" - "アーキテクチャ設計" - - "依存性注入(DI)パターン" - - "設計ドキュメントとプロセス" + - "データフロー統一原則" - "ビルドとテスト" project-context: @@ -91,7 +94,7 @@ rules: documentation-criteria: file: "documentation-criteria.md" tags: [documentation, decision-making, adr, prd, design-doc, planning, process] - typical-use: "ドキュメント作成判定、ADR/PRD/Design Doc/作業計画書の作成基準" + typical-use: "実装開始時の規模判定、ドキュメント作成判定、ADR/PRD/Design Doc/作業計画書の作成基準" size: medium key-references: - "ADR手法 - Michael Nygard" @@ -147,7 +150,7 @@ rules: implementation-approach: file: "architecture/implementation-approach.md" tags: [architecture, implementation, task-decomposition, strategy-patterns, strangler-pattern, facade-pattern, design, planning, confirmation-levels] - typical-use: "実装戦略パターンの選択、ストラングラー・ファサードパターンの適用判断、確認レベル(L1/L2/L3)定義、Design Doc作成時の戦略選択" + typical-use: "実装戦略の選択、タスク分解、設計判断、大規模変更の計画" size: medium key-references: - "Strangler Fig Pattern - Martin Fowler" diff --git a/docs/rules-ja/typescript-testing.md b/docs/rules-ja/typescript-testing.md index 5be9d15..f997d35 100644 --- a/docs/rules-ja/typescript-testing.md +++ b/docs/rules-ja/typescript-testing.md @@ -28,17 +28,26 @@ - 実際の依存関係を使用(DBやAPI等) - 主要な機能フローの検証 -## テストの設計原則 +## Red-Green-Refactorプロセス(テストファースト開発) -### Red-Green-Refactorプロセス(TDD) +**推奨原則**: コード変更は必ずテストから始める -**原則**: すべての新機能・バグ修正はテストから始める +**背景**: +- 変更前の動作を保証し、リグレッションを防止 +- 期待する動作を明確化してから実装 +- リファクタリング時の安全性を確保 -1. **Red**: 失敗するテストを書く +**開発ステップ**: +1. **Red**: 期待する動作のテストを書く(失敗する) 2. **Green**: 最小限の実装でテストを通す -3. **Refactor**: テストが通る状態でコード改善 +3. **Refactor**: テストが通る状態を維持しながらコード改善 + +**NGケース(テストファースト不要)**: +- 純粋な設定ファイル変更(.env、config等) +- ドキュメントのみの更新(README、コメント等) +- 緊急本番障害対応(ただし事後テスト必須) -**例外**: 設定変更、ドキュメント更新、既存テストでカバー済みのリファクタリング、緊急対応(事後テスト必須) +## テストの設計原則 ### テストケースの構造 - テストは「準備(Arrange)」「実行(Act)」「検証(Assert)」の3段階で構成 diff --git a/docs/rules-ja/typescript.md b/docs/rules-ja/typescript.md index 8b20c05..8211468 100644 --- a/docs/rules-ja/typescript.md +++ b/docs/rules-ja/typescript.md @@ -21,6 +21,29 @@ 3. **ユニオン型・インターセクション型**: 複数の型の組み合わせ 4. **型アサーション(最終手段)**: 型が確実な場合のみ +**モダンな型機能の活用** +- **satisfies演算子**: 型推論を維持しつつ型チェック + ```typescript + const config = { port: 3000 } satisfies Config // ✅ 型推論維持 + const config: Config = { port: 3000 } // ❌ 型推論失われる + ``` +- **const assertion**: リテラル型で不変性を保証 + ```typescript + const ROUTES = { HOME: '/' } as const satisfies Routes // ✅ 不変かつ型安全 + ``` +- **ブランド型**: 同じプリミティブ型でも意味を区別 + ```typescript + type UserId = string & { __brand: 'UserId' } + type OrderId = string & { __brand: 'OrderId' } + // UserIdとOrderIdは互換性なし - 混同を防止 + ``` +- **テンプレートリテラル型**: 文字列パターンを型で表現 + ```typescript + type Route = `/${string}` + type HttpMethod = 'GET' | 'POST' + type Endpoint = `${HttpMethod} ${Route}` + ``` + **実装での型安全性** - API通信: レスポンスは必ず`unknown`で受け、型ガードで検証 - フォーム入力: 外部入力は`unknown`、バリデーション後に型確定 @@ -38,6 +61,37 @@ ## コーディング規約 +**クラス使用の判断基準** +- **クラス使用を許可**: + - フレームワーク要求時(NestJSのController/Service、TypeORMのEntity等) + - カスタムエラークラス定義時 +- **クラス使用を禁止**: 上記以外は関数とinterfaceで実装 + ```typescript + // ✅ 関数とinterface + interface UserService { create(data: UserData): User } + const userService: UserService = { create: (data) => {...} } + // ❌ 不要なクラス + class UserService { create(data: UserData) {...} } + ``` + +**関数設計** +- **引数は0-2個まで**: 3個以上はオブジェクト化 + ```typescript + // ✅ オブジェクト引数 + function createUser({ name, email, role }: CreateUserParams) {} + // ❌ 多数の引数 + function createUser(name: string, email: string, role: string) {} + ``` + +**依存性注入** +- **外部依存は引数で注入**: テスト可能性とモジュール性確保 + ```typescript + // ✅ 依存性を引数で受け取る + function createService(repository: Repository) { return {...} } + // ❌ 直接importした実装に依存 + import { userRepository } from './infrastructure/repository' + ``` + **非同期処理** - Promise処理: 必ず`async/await`を使用 - エラーハンドリング: 必ず`try-catch`でハンドリング @@ -58,6 +112,17 @@ **絶対ルール**: エラーの握りつぶし禁止。すべてのエラーは必ずログ出力と適切な処理を行う。 +**Result型パターン**: エラーを型で表現し、明示的に処理 +```typescript +type Result = { ok: true; value: T } | { ok: false; error: E } + +// 使用例:エラーの可能性を型で表現 +function parseUser(data: unknown): Result { + if (!isValid(data)) return { ok: false, error: new ValidationError() } + return { ok: true, value: data as User } +} +``` + **カスタムエラークラス** ```typescript export class AppError extends Error { @@ -85,11 +150,11 @@ export class AppError extends Error { ## リファクタリング手法 **基本方針** -- テストファースト: 既存動作を保護するテストを先に作成 - 小さなステップ: 段階的改善により、常に動作する状態を維持 - 安全な変更: 一度に変更する範囲を最小限に抑制 +- 動作保証: 既存の動作を変えないことを確認しながら進める -**実施手順**: 現状把握 → 保護テスト作成 → 段階的変更 → 検証 → 最終確認 +**実施手順**: 現状把握 → 段階的変更 → 動作確認 → 最終検証 **優先順位**: 重複コード削除 > 長大な関数分割 > 複雑な条件分岐簡素化 > 型安全性向上 diff --git a/package-lock.json b/package-lock.json index 9f59ec7..8c13596 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ai-coding-project-boilerplate", - "version": "1.6.4", + "version": "1.6.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ai-coding-project-boilerplate", - "version": "1.6.4", + "version": "1.6.5", "hasInstallScript": true, "license": "MIT", "bin": { diff --git a/package.json b/package.json index 24515cd..82573bc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ai-coding-project-boilerplate", - "version": "1.6.4", + "version": "1.6.5", "description": "TypeScript project boilerplate optimized for Claude Code development with comprehensive development rules, architecture patterns, and quality assurance tools", "main": "dist/index.js", "keywords": [