diff --git a/.claude/agents-en/code-reviewer.md b/.claude/agents-en/code-reviewer.md index 0dcfb34..8f67f72 100644 --- a/.claude/agents-en/code-reviewer.md +++ b/.claude/agents-en/code-reviewer.md @@ -11,7 +11,7 @@ Operates in an independent context without CLAUDE.md principles, executing auton ## Initial Required Tasks Load and follow these rule files before starting: -- @docs/rules/ai-development-guide.md - AI Development Guide, pre-implementation existing code investigation process +- @docs/rules/coding-standards.md - Universal Coding Standards, pre-implementation existing code investigation process - @docs/rules/technical-spec.md - Technical Specifications - @docs/rules/typescript.md - TypeScript Development Rules - @docs/rules/project-context.md - Project Context @@ -96,7 +96,7 @@ Load and follow these rule files before starting: - [ ] Component dependencies correct - [ ] Responsibilities properly separated - [ ] Existing codebase analysis section includes similar functionality investigation results -- [ ] No unnecessary duplicate implementations (Pattern 5 from @docs/rules/ai-development-guide.md) +- [ ] No unnecessary duplicate implementations (Pattern 5 from @docs/rules/coding-standards.md) ### Quality Validation - [ ] Comprehensive error handling diff --git a/.claude/agents-en/quality-fixer-frontend.md b/.claude/agents-en/quality-fixer-frontend.md index 521cca0..1b57a93 100644 --- a/.claude/agents-en/quality-fixer-frontend.md +++ b/.claude/agents-en/quality-fixer-frontend.md @@ -27,11 +27,11 @@ Executes quality checks and provides a state where all checks complete with zero ## Initial Required Tasks Load and follow these rule files before starting: +- @docs/rules/coding-standards.md - Universal Coding Standards (Anti-patterns, Rule of Three, Debugging, Type Safety) - @docs/rules/frontend/typescript.md - Frontend TypeScript Development Rules (React function components, Props-driven design) - @docs/rules/frontend/typescript-testing.md - Frontend Testing Rules (React Testing Library, MSW, 60% coverage) -- @docs/rules/frontend/ai-development-guide.md - Frontend Quality Check Command Reference +- @docs/rules/frontend/technical-spec.md - Frontend Quality Check Commands and Build/Test Configuration - @docs/rules/project-context.md - Project Context -- @docs/rules/frontend/technical-spec.md - Frontend Technical Specifications (environment variables, build requirements) - @docs/rules/architecture/ files (if present) - Load project-specific architecture rules when defined - Apply rules based on adopted architecture patterns diff --git a/.claude/agents-en/quality-fixer.md b/.claude/agents-en/quality-fixer.md index c54734c..f424d29 100644 --- a/.claude/agents-en/quality-fixer.md +++ b/.claude/agents-en/quality-fixer.md @@ -27,9 +27,10 @@ Executes quality checks and provides a state where `npm run check:all` completes ## Initial Required Tasks Load and follow these rule files before starting: +- @docs/rules/coding-standards.md - Universal Coding Principles and Anti-patterns - @docs/rules/typescript.md - TypeScript Development Rules - @docs/rules/typescript-testing.md - Testing Rules -- @docs/rules/ai-development-guide.md - Quality Check Command Reference +- @docs/rules/technical-spec.md - Quality Check Commands and Build/Test Configuration - @docs/rules/project-context.md - Project Context - @docs/rules/architecture/ files (if present) - Load project-specific architecture rules when defined diff --git a/.claude/agents-en/requirement-analyzer.md b/.claude/agents-en/requirement-analyzer.md index b9b7c0d..7f194c8 100644 --- a/.claude/agents-en/requirement-analyzer.md +++ b/.claude/agents-en/requirement-analyzer.md @@ -13,7 +13,7 @@ Operates in an independent context without CLAUDE.md principles, executing auton Before starting work, be sure to read and follow these rule files: - @docs/rules/project-context.md - Project context - @docs/rules/technical-spec.md - Technical specifications (refer to documentation process) -- @docs/rules/ai-development-guide.md - AI development guide (refer to escalation criteria) +- @docs/rules/coding-standards.md - Universal Coding Standards (refer to escalation criteria and anti-patterns) - @docs/rules/documentation-criteria.md - Documentation creation criteria (scale determination and ADR conditions) ## Responsibilities diff --git a/.claude/agents-en/task-decomposer.md b/.claude/agents-en/task-decomposer.md index f444751..78ec0af 100644 --- a/.claude/agents-en/task-decomposer.md +++ b/.claude/agents-en/task-decomposer.md @@ -11,7 +11,7 @@ Operates in an independent context without CLAUDE.md principles, executing auton ## Initial Mandatory Tasks Before starting work, be sure to read and follow these rule files: -- @docs/rules/ai-development-guide.md - Task management principles +- @docs/rules/coding-standards.md - Universal Coding Standards (task management principles, implementation completeness) - @docs/rules/documentation-criteria.md - Documentation creation criteria - @docs/rules/typescript-testing.md - TDD process (Red-Green-Refactor) - @docs/rules/project-context.md - Generic design guidelines considering future extensions diff --git a/.claude/agents-en/task-executor-frontend.md b/.claude/agents-en/task-executor-frontend.md index b26eebe..4fd69a0 100644 --- a/.claude/agents-en/task-executor-frontend.md +++ b/.claude/agents-en/task-executor-frontend.md @@ -21,7 +21,7 @@ Load and follow these rule files before starting: - Component hierarchy, feature-based structure, etc. - **@docs/rules/frontend/typescript.md** - Frontend TypeScript development rules (React function components, Props-driven design, type safety) - **@docs/rules/frontend/typescript-testing.md** - Frontend testing rules (React Testing Library, MSW, 60% coverage, Co-location principle) -- **@docs/rules/frontend/ai-development-guide.md** - Frontend AI development guide, pre-implementation existing code investigation process +- **@docs/rules/coding-standards.md** - Universal Coding Standards, pre-implementation existing code investigation process **Follow**: All rules for implementation, testing, and code quality **Exception**: Quality assurance process and commits are out of scope diff --git a/.claude/agents-en/task-executor.md b/.claude/agents-en/task-executor.md index 43b11bd..4e6ad7a 100644 --- a/.claude/agents-en/task-executor.md +++ b/.claude/agents-en/task-executor.md @@ -21,7 +21,7 @@ Load and follow these rule files before starting: - Layered architecture, clean architecture, hexagonal, etc. - **@docs/rules/typescript.md** - TypeScript development rules (type definitions, any prohibition, error handling) - **@docs/rules/typescript-testing.md** - Testing rules (TDD methodology, test structure, assertion approach) -- **@docs/rules/ai-development-guide.md** - AI development guide, pre-implementation existing code investigation process +- **@docs/rules/coding-standards.md** - Universal Coding Standards, pre-implementation existing code investigation process **Follow**: All rules for implementation, testing, and code quality **Exception**: Quality assurance process (Phase 1-6) and commits are out of scope diff --git a/.claude/agents-en/technical-designer-frontend.md b/.claude/agents-en/technical-designer-frontend.md index cd23236..485ac77 100644 --- a/.claude/agents-en/technical-designer-frontend.md +++ b/.claude/agents-en/technical-designer-frontend.md @@ -14,7 +14,7 @@ Before starting work, be sure to read and follow these rule files: - @docs/rules/documentation-criteria.md - Documentation creation criteria - @docs/rules/frontend/technical-spec.md - Frontend technical specifications (React, build tool, environment variables) - @docs/rules/frontend/typescript.md - Frontend TypeScript development rules (function components, Props-driven design) -- @docs/rules/frontend/ai-development-guide.md - Frontend AI development guide, pre-implementation existing code investigation process +- @docs/rules/coding-standards.md - Universal Coding Standards, pre-implementation existing code investigation process - @docs/rules/project-context.md - Project context - @docs/rules/architecture/implementation-approach.md - Metacognitive strategy selection process (used for implementation approach decisions) - @docs/rules/architecture/ architecture rule files (if exist) @@ -61,7 +61,7 @@ Must be performed before Design Doc creation: - List major public Props of target component (about 5 important ones if over 10) - Identify usage sites with `Grep: " Large Function Division > Complex Conditional Branch Simplification > Type Safety Improvement ## Situations Requiring Technical Decisions @@ -236,7 +242,7 @@ Structured impact report (mandatory): ``` ## Impact Analysis ### Direct Impact: ClassA, ClassB (with reasons) -### Indirect Impact: SystemX, PrefabY (with integration paths) +### Indirect Impact: SystemX, ComponentY (with integration paths) ### Processing Flow: Input → Process1 → Process2 → Output ``` @@ -256,4 +262,82 @@ Target: Code, documentation, configuration files In use? No → Delete immediately (remains in Git history) Yes → Working? No → Delete + Reimplement Yes → Fix -``` \ No newline at end of file +``` + +## Red-Green-Refactor Process (Test-First Development) + +**Recommended Principle**: Always start code changes with tests + +**Background**: +- Ensure behavior before changes, prevent regression +- Clarify expected behavior before implementation +- Ensure safety during refactoring + +**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 + +**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) + +## Test Design Principles + +### Test Case Structure +- Tests consist of three stages: "Arrange," "Act," "Assert" +- Clear naming that shows purpose of each test +- One test case verifies only one behavior + +### Test Data Management +- Manage test data in dedicated directories +- Define test-specific environment variable values +- Always mock sensitive information +- Keep test data minimal, using only data directly related to test case verification purposes + +### Mock and Stub Usage Policy + +✅ **Recommended: Mock external dependencies in unit tests** +- Merit: Ensures test independence and reproducibility +- Practice: Mock DB, API, file system, and other external dependencies + +❌ **Avoid: Actual external connections in unit tests** +- Reason: Slows test speed and causes environment-dependent problems + +### Test Failure Response Decision Criteria + +**Fix tests**: Wrong expected values, references to non-existent features, dependence on implementation details, implementation only for tests +**Fix implementation**: Valid specifications, business logic, important edge cases +**When in doubt**: Confirm with user + +## Test Helper Utilization Rules + +### Basic Principles +Use test helpers to reduce duplication and improve maintainability. + +### Decision Criteria +| Mock Characteristics | Response Policy | +|---------------------|-----------------| +| **Simple and stable** | Consolidate in common helpers | +| **Complex or frequently changing** | Individual implementation | +| **Duplicated in 3+ places** | Consider consolidation | +| **Test-specific logic** | Individual implementation | + +## Test Granularity Principles + +### Core Principle: Observable Behavior Only +**MUST Test**: Public APIs, return values, exceptions, external calls, persisted state +**MUST NOT Test**: Private methods, internal state, algorithm implementation details + +```typescript +// ✅ Test observable behavior +expect(calculateTotal(100, 0.1)).toBe(110) + +// ❌ Test implementation details +expect((calculator as any).internalState).toBe(someValue) +``` + +## Continuity Test Scope + +Limited to verifying existing feature impact when adding new features. Long-term operations and load testing are infrastructure responsibilities, not test scope. diff --git a/docs/rules-en/frontend/ai-development-guide.md b/docs/rules-en/frontend/ai-development-guide.md deleted file mode 100644 index 7697d2d..0000000 --- a/docs/rules-en/frontend/ai-development-guide.md +++ /dev/null @@ -1,262 +0,0 @@ -# AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection (Frontend) - -## Technical Anti-patterns (Red Flag Patterns) - -Immediately stop and reconsider design when detecting the following patterns: - -### Code Quality Anti-patterns -1. **Writing similar code 3 or more times** - Violates Rule of Three -2. **Multiple responsibilities mixed in a single component** - Violates Single Responsibility Principle (SRP) -3. **Defining same content in multiple components** - Violates DRY principle -4. **Making changes without checking dependencies** - Potential for unexpected impacts -5. **Disabling code with comments** - Should use version control -6. **Error suppression** - Hiding problems creates technical debt -7. **Excessive use of type assertions (as)** - Abandoning type safety -8. **Prop drilling through 3+ levels** - Should use Context API or state management -9. **Massive components (300+ lines)** - Split into smaller components - -### Design Anti-patterns -- **"Make it work for now" thinking** - Accumulation of technical debt -- **Patchwork implementation** - Unplanned additions to existing components -- **Optimistic implementation of uncertain technology** - Designing unknown elements assuming "it'll probably work" -- **Symptomatic fixes** - Surface-level fixes that don't solve root causes -- **Unplanned large-scale changes** - Lack of incremental approach - -## Fallback Design Principles - -### Core Principle: Fail-Fast -Design philosophy that prioritizes improving primary code reliability over fallback implementations. - -### Criteria for Fallback Implementation -- **Default Prohibition**: Do not implement unconditional fallbacks on errors -- **Exception Approval**: Implement only when explicitly defined in Design Doc -- **Layer Responsibilities**: - - Component Layer: Use Error Boundary for error handling - - Hook Layer: Implement decisions based on business requirements - -### Detection of Excessive Fallbacks -- Require design review when writing the 3rd catch statement in the same feature -- Verify Design Doc definition before implementing fallbacks -- Properly log errors and make failures explicit - -## Rule of Three - Criteria for Code Duplication - -How to handle duplicate code based on Martin Fowler's "Refactoring": - -| Duplication Count | Action | Reason | -|-------------------|--------|--------| -| 1st time | Inline implementation | Cannot predict future changes | -| 2nd time | Consider future consolidation | Pattern beginning to emerge | -| 3rd time | Implement commonalization | Pattern established | - -### Criteria for Commonalization - -**Cases for Commonalization** -- Business logic duplication -- Complex processing algorithms -- Component patterns (form fields, cards, etc.) -- Custom hooks -- Validation rules - -**Cases to Avoid Commonalization** -- Accidental matches (coincidentally same code) -- Possibility of evolving in different directions -- Significant readability decrease from commonalization -- Simple helpers in test code - -### Implementation Example -```typescript -// ❌ Immediate commonalization on 1st duplication -function UserEmailInput() { /* ... */ } -function ContactEmailInput() { /* ... */ } - -// ✅ Commonalize on 3rd occurrence -function EmailInput({ context }: { context: 'user' | 'contact' | 'admin' }) { /* ... */ } -``` - -## Common Failure Patterns and Avoidance Methods - -### Pattern 1: Error Fix Chain -**Symptom**: Fixing one error causes new errors -**Cause**: Surface-level fixes without understanding root cause -**Avoidance**: Identify root cause with 5 Whys before fixing - -### Pattern 2: Abandoning Type Safety -**Symptom**: Excessive use of any type or as -**Cause**: Impulse to avoid type errors -**Avoidance**: Handle safely with unknown type and type guards - -### Pattern 3: Implementation Without Sufficient Testing -**Symptom**: Many bugs after implementation -**Cause**: Ignoring Red-Green-Refactor process -**Avoidance**: Always start with failing tests - -### Pattern 4: Ignoring Technical Uncertainty -**Symptom**: Frequent unexpected errors when introducing new technology -**Cause**: Assuming "it should work according to official documentation" without prior investigation -**Avoidance**: -- Record certainty evaluation at the beginning of task files - ``` - Certainty: low (Reason: new experimental feature with limited production examples) - Exploratory implementation: true - Fallback: use established patterns - ``` -- For low certainty cases, create minimal verification code first - -### Pattern 5: Insufficient Existing Code Investigation -**Symptom**: Duplicate implementations, architecture inconsistency, integration failures -**Cause**: Insufficient understanding of existing code before implementation -**Avoidance Methods**: -- Before implementation, always search for similar functionality (using domain, responsibility, component patterns as keywords) -- Similar functionality found → Use that implementation (do not create new implementation) -- Similar functionality is technical debt → Create ADR improvement proposal before implementation -- No similar functionality exists → Implement new functionality following existing design philosophy -- Record all decisions and rationale in "Existing Codebase Analysis" section of Design Doc - -## Debugging Techniques - -### 1. Error Analysis Procedure -1. Read error message (first line) accurately -2. Focus on first and last of stack trace -3. Identify first line where your code appears -4. Check React DevTools for component hierarchy - -### 2. 5 Whys - Root Cause Analysis -``` -Symptom: Component not rendering -Why1: Props are undefined → Why2: Parent component didn't pass props -Why3: Parent using old prop names → Why4: Component interface was updated -Why5: No update to parent after refactoring -Root cause: Incomplete refactoring, missing call-site updates -``` - -### 3. Minimal Reproduction Code -To isolate problems, attempt reproduction with minimal code: -- Remove unrelated components -- Replace API calls with mocks -- Create minimal configuration that reproduces problem -- Use React DevTools to inspect component tree - -### 4. Debug Log Output -```typescript -console.log('DEBUG:', { - context: 'user-form-submission', - props: { email, name }, - state: currentState, - timestamp: new Date().toISOString() -}) -``` - -## Quality Check Command Reference - -### Phase 1-3: Basic Checks -```bash -# Biome comprehensive check (lint + format) -npm run check - -# TypeScript build -npm run build -``` - -### Phase 4-5: Tests and Final Confirmation -```bash -# Test execution -npm test - -# Coverage measurement (clear cache) -npm run test:coverage:fresh - -# Overall integrated check -npm run check:all -``` - -### Auxiliary Commands -```bash -# Check coverage report -open coverage/index.html - -# Vitest process cleanup (mandatory after tests) -npm run cleanup:processes - -# Safe test execution (with auto cleanup) -npm run test:safe - -# Auto fixes -npm run format # Format fixes -npm run lint:fix # Lint fixes -``` - -### Troubleshooting -- **Port in use error**: `npm run cleanup:processes` -- **Cache issues**: `npm run test:coverage:fresh` -- **Dependency errors**: Reinstall with `npm ci` -- **Vite preview not starting**: Check port 4173 availability - -## Situations Requiring Technical Decisions - -### Timing of Abstraction -- Extract patterns after writing concrete implementation 3 times -- Be conscious of YAGNI, implement only currently needed features -- Prioritize current simplicity over future extensibility - -### Performance vs Readability -- Prioritize readability unless clear bottleneck exists -- Measure before optimizing (don't guess, use React DevTools Profiler) -- Document reason with comments when optimizing - -### Granularity of Component/Type Definitions -- Overly detailed components/types reduce maintainability -- Design components that appropriately express UI patterns -- Use composition over inheritance - -## Continuous Improvement Mindset - -- **Humility**: Perfect code doesn't exist, welcome feedback -- **Courage**: Execute necessary refactoring boldly -- **Transparency**: Clearly document technical decision reasoning - -## Implementation Completeness Assurance - -### Required Procedure for Impact Analysis - -**Completion Criteria**: Complete all 3 stages - -#### 1. Discovery -```bash -Grep -n "ComponentName\|hookName" -o content -Grep -n "importedFunction" -o content -Grep -n "propsType\|StateType" -o content -``` - -#### 2. Understanding -**Mandatory**: Read all discovered files and include necessary parts in context: -- Caller's purpose and context -- Component hierarchy -- Data flow: Props → State → Event handlers → Callbacks - -#### 3. Identification -Structured impact report (mandatory): -``` -## Impact Analysis -### Direct Impact: ComponentA, ComponentB (with reasons) -### Indirect Impact: FeatureX, PageY (with integration paths) -### Processing Flow: Props → Render → Events → Callbacks -``` - -**Important**: Do not stop at search; execute all 3 stages - -### Unused Code Deletion Rule - -When unused code is detected → Will it be used? -- Yes → Implement immediately (no deferral allowed) -- No → Delete immediately (remains in Git history) - -Target: Components, hooks, utilities, documentation, configuration files - -### Existing Code Deletion Decision Flow - -``` -In use? No → Delete immediately (remains in Git history) - Yes → Working? No → Delete + Reimplement - Yes → Fix -``` diff --git a/docs/rules-en/frontend/typescript-testing.md b/docs/rules-en/frontend/typescript-testing.md index 2e89637..ca588f7 100644 --- a/docs/rules-en/frontend/typescript-testing.md +++ b/docs/rules-en/frontend/typescript-testing.md @@ -1,4 +1,4 @@ -# TypeScript Testing Rules (Frontend) +# TypeScript Testing Rules ## Test Framework - **Vitest**: This project uses Vitest @@ -47,79 +47,6 @@ - Success criteria: No change in displayed content, rendering time within 5 seconds - Designed for automatic execution in CI/CD pipelines -## Red-Green-Refactor Process (Test-First Development) - -**Recommended Principle**: Always start code changes with tests - -**Background**: -- Ensure behavior before changes, prevent regression -- Clarify expected behavior before implementation -- Ensure safety during refactoring - -**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 - -**NG Cases (Test-first not required)**: -- Pure configuration file changes (vite.config.ts, tailwind.config.js, etc.) -- Documentation-only updates (README, comments, etc.) -- Emergency production incident response (post-incident tests mandatory) - -## Test Design Principles - -### Test Case Structure -- Tests consist of three stages: "Arrange," "Act," "Assert" -- Clear naming that shows purpose of each test -- One test case verifies only one behavior - -### Test Data Management -- Manage test data in dedicated directories or co-located with tests -- Define test-specific environment variable values -- Always mock sensitive information -- Keep test data minimal, using only data directly related to test case verification purposes - -### Mock and Stub Usage Policy - -✅ **Recommended: Mock external dependencies in unit tests** -- Merit: Ensures test independence and reproducibility -- Practice: Mock API calls with MSW, mock external libraries - -❌ **Avoid: Actual API connections in unit tests** -- Reason: Slows test speed and causes environment-dependent problems - -### Test Failure Response Decision Criteria - -**Fix tests**: Wrong expected values, references to non-existent features, dependence on implementation details, implementation only for tests -**Fix implementation**: Valid specifications, business logic, important edge cases -**When in doubt**: Confirm with user - -## Test Helper Utilization Rules - -### Basic Principles -Use test helpers to reduce duplication and improve maintainability. - -### Decision Criteria -| Mock Characteristics | Response Policy | -|---------------------|-----------------| -| **Simple and stable** | Consolidate in common helpers | -| **Complex or frequently changing** | Individual implementation | -| **Duplicated in 3+ places** | Consider consolidation | -| **Test-specific logic** | Individual implementation | - -### Test Helper Usage Examples -```typescript -// ✅ Builder pattern for test data -const testUser = createTestUser({ name: 'Test User', email: 'test@example.com' }) - -// ✅ Custom render function with providers -function renderWithProviders(ui: React.ReactElement) { - return render({ui}) -} - -// ❌ Individual implementation of duplicate complex mocks -``` - ## Test Implementation Conventions ### Directory Structure (Co-location Principle) @@ -153,20 +80,6 @@ src/ - Reason: Creates test gaps and incomplete quality checks - Solution: Completely delete unnecessary tests -## Test Granularity Principles - -### Core Principle: User-Observable Behavior Only -**MUST Test**: Rendered output, user interactions, accessibility, error states -**MUST NOT Test**: Component internal state, implementation details, CSS class names - -```typescript -// ✅ Test user-observable behavior -expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument() - -// ❌ Test implementation details -expect(component.state.count).toBe(0) -``` - ## Mock Type Safety Enforcement ### MSW (Mock Service Worker) Setup @@ -193,10 +106,6 @@ const mockRouter = { } as unknown as Router // Complex router type structure ``` -## Continuity Test Scope - -Limited to verifying existing feature impact when adding new features. Long-term operations and performance testing are infrastructure responsibilities, not test scope. - ## Basic React Testing Library Example ```typescript diff --git a/docs/rules-en/frontend/typescript.md b/docs/rules-en/frontend/typescript.md index 407d172..eb16adf 100644 --- a/docs/rules-en/frontend/typescript.md +++ b/docs/rules-en/frontend/typescript.md @@ -1,51 +1,26 @@ -# TypeScript Development Rules (Frontend) +# TypeScript Development Rules -## Basic Principles +## Frontend-Specific Anti-patterns -✅ **Aggressive Refactoring** - Prevent technical debt and maintain health -❌ **Unused "Just in Case" Code** - Violates YAGNI principle (Kent Beck) +In addition to universal anti-patterns in coding-standards.md, watch for these Frontend-specific issues: -## Comment Writing Rules -- **Function Description Focus**: Describe what the code "does" -- **No Historical Information**: Do not record development history -- **Timeless**: Write only content that remains valid whenever read -- **Conciseness**: Keep explanations to necessary minimum +- **Prop drilling through 3+ levels** - Should use Context API or state management +- **Massive components (300+ lines)** - Split into smaller components -## Type Safety +## Type Safety in Frontend Implementation -**Absolute Rule**: any type is completely prohibited. It disables type checking and becomes a source of runtime errors. - -**any Type Alternatives (Priority Order)** -1. **unknown Type + Type Guards**: Use for validating external input (API responses, localStorage, URL parameters) -2. **Generics**: When type flexibility is needed -3. **Union Types・Intersection Types**: Combinations of multiple types -4. **Type Assertions (Last Resort)**: Only when type is certain - -**Type Guard Implementation Pattern** -```typescript -function isUser(value: unknown): value is User { - return typeof value === 'object' && value !== null && 'id' in value && 'name' in value -} -``` - -**Modern Type Features** -- **satisfies Operator**: `const config = { apiUrl: '/api' } satisfies Config` - Preserves inference -- **const Assertion**: `const ROUTES = { HOME: '/' } as const satisfies Routes` - Immutable and type-safe -- **Branded Types**: `type UserId = string & { __brand: 'UserId' }` - Distinguish meaning -- **Template Literal Types**: `type EventName = \`on\${Capitalize}\`` - Express string patterns with types +**Type Safety in Data Flow** +- **Frontend → Backend**: Props/State (Type Guaranteed) → API Request (Serialization) +- **Backend → Frontend**: API Response (`unknown`) → Type Guard → State (Type Guaranteed) -**Type Safety in Frontend Implementation** +**Frontend-Specific Type Scenarios**: - **React Props/State**: TypeScript manages types, unknown unnecessary - **External API Responses**: Always receive as `unknown`, validate with type guards - **localStorage/sessionStorage**: Treat as `unknown`, validate - **URL Parameters**: Treat as `unknown`, validate - **Form Input (Controlled Components)**: Type-safe with React synthetic events -**Type Safety in Data Flow** -- **Frontend → Backend**: Props/State (Type Guaranteed) → API Request (Serialization) -- **Backend → Frontend**: API Response (`unknown`) → Type Guard → State (Type Guaranteed) - -**Type Complexity Management** +**Type Complexity Management (Frontend)** - **Props Design**: - Props count: 3-7 props ideal (consider component splitting if exceeds 10) - Optional Props: 50% or less (consider default values or Context if excessive) @@ -148,17 +123,6 @@ Never include sensitive information (password, token, apiKey, secret, creditCard - Use try-catch with all async/await in event handlers - Always log and re-throw errors or display error state -## Refactoring Techniques - -**Basic Policy** -- 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 → Gradual Changes → Behavior Verification → Final Validation - -**Priority**: Duplicate Code Removal > Large Function Division > Complex Conditional Branch Simplification > Type Safety Improvement - ## Performance Optimization - Component Memoization: Use React.memo for expensive components diff --git a/docs/rules-en/rules-index.yaml b/docs/rules-en/rules-index.yaml index b1540b2..f0fdbae 100644 --- a/docs/rules-en/rules-index.yaml +++ b/docs/rules-en/rules-index.yaml @@ -2,11 +2,43 @@ # Manages overview, tags, typical usage scenarios, and size for each rule rules: + coding-standards: + file: "coding-standards.md" + tags: [universal, anti-patterns, refactoring, type-safety, testing, code-deletion, rule-of-three, fail-fast, impact-analysis] + typical-use: "Universal coding principles applicable across all domains, foundational standards for all developers" + size: large + key-references: + - "Rule of Three - Martin Fowler" + - "Single Responsibility Principle - Clean Code" + - "DRY Principle - The Pragmatic Programmer" + - "YAGNI Principle - Kent Beck" + - "5 Whys - Toyota Production System" + - "Red-Green-Refactor - Kent Beck" + - "AAA Pattern - Arrange-Act-Assert" + sections: + - "Technical Anti-patterns (Red Flag Patterns)" + - "Basic Principles" + - "Comment Writing Rules" + - "Fallback Design Principles" + - "Rule of Three - Criteria for Code Duplication" + - "Common Failure Patterns and Avoidance Methods" + - "Debugging Techniques" + - "Type Safety Fundamentals" + - "Refactoring Techniques" + - "Situations Requiring Technical Decisions" + - "Continuous Improvement Mindset" + - "Implementation Completeness Assurance" + - "Red-Green-Refactor Process (Test-First Development)" + - "Test Design Principles" + - "Test Helper Utilization Rules" + - "Test Granularity Principles" + - "Continuity Test Scope" + typescript: file: "typescript.md" - 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 + tags: [implementation, type-safety, async, refactoring, coding-style, functional-programming, dependency-injection, branded-types, backend] + typical-use: "Backend TypeScript code creation, modification, refactoring, modern type features utilization" + size: small key-references: - "YAGNI Principle - Kent Beck" - "Clean Code - Robert C. Martin" @@ -18,19 +50,16 @@ rules: - "Dependency Injection - Martin Fowler" - "Avoiding fallback in distributed systems - AWS Builders' Library" sections: - - "Basic Principles" - - "Comment Writing Rules" - - "Type Safety" + - "Type Safety in Backend Implementation" - "Coding Conventions" - "Error Handling" - - "Refactoring Techniques" - "Performance Optimization" typescript-testing: file: "typescript-testing.md" - tags: [quality, testing, tdd, coverage, vitest, implementation, debugging, refactoring] - typical-use: "Test creation, quality checks, development steps for code/bug fixes, refactoring, and new feature implementation" - size: medium + tags: [quality, testing, tdd, coverage, vitest, implementation, debugging, refactoring, backend] + typical-use: "Backend test creation, quality checks, development steps for code/bug fixes, refactoring, and new feature implementation" + size: small key-references: - "Test-Driven Development - Kent Beck" - "Rule of Three - Martin Fowler" @@ -39,42 +68,14 @@ rules: sections: - "Test Framework" - "Basic Testing Policy" - - "Red-Green-Refactor Process (Test-First Development)" - - "Test Design Principles" - - "Test Helper Utilization Rules" - "Test Implementation Conventions" - - "Test Granularity Principles" - "Mock Type Safety Enforcement" - - "Continuity Test Scope" - "Basic Vitest Example" - ai-development-guide: - file: "ai-development-guide.md" - tags: [anti-patterns, technical-judgment, debugging, quality-commands, rule-of-three, implementation, type-safety, refactoring, code-reading, best-practices, impact-analysis, unused-code, code-deletion] - typical-use: "Technical decision criteria, anti-pattern detection, debugging techniques, quality check commands, implementation best practices, impact analysis, unused code deletion" - size: medium - key-references: - - "Rule of Three - Martin Fowler" - - "5 Whys - Toyota Production System" - - "DRY Principle - The Pragmatic Programmer" - - "Single Responsibility Principle (SRP) - Clean Code" - - "YAGNI Principle - Extreme Programming" - - "Avoiding fallback in distributed systems - AWS Builders' Library" - sections: - - "Technical Anti-patterns (Red Flag Patterns)" - - "Fallback Design Principles" - - "Rule of Three - Criteria for Code Duplication" - - "Common Failure Patterns and Avoidance Methods" - - "Debugging Techniques" - - "Quality Check Command Reference" - - "Situations Requiring Technical Decisions" - - "Continuous Improvement Mindset" - - "Implementation Completeness Assurance" - technical-spec: file: "technical-spec.md" - tags: [architecture, design, documentation, environment, data-flow, implementation] - typical-use: "Technical design, environment configuration, documentation creation process, implementation policy decisions" + tags: [architecture, design, documentation, environment, data-flow, implementation, quality-commands, testing, build] + typical-use: "Technical design, environment configuration, documentation creation process, implementation policy decisions, quality check commands, build and test execution" size: medium key-references: - "ADR Format - Michael Nygard" @@ -141,7 +142,7 @@ rules: file: "frontend/typescript.md" tags: [frontend, react, implementation, type-safety, function-components, props-driven, async, refactoring, coding-style] typical-use: "React component creation, Props type definitions, frontend TypeScript development" - size: medium + size: small key-references: - "React Function Components - React Official" - "Props-driven Design - React Best Practices" @@ -149,19 +150,17 @@ rules: - "Clean Code - Robert C. Martin" - "TypeScript satisfies Operator - Microsoft" sections: - - "Basic Principles" - - "Comment Writing Rules" - - "Type Safety" + - "Frontend-Specific Anti-patterns" + - "Type Safety in Frontend Implementation" - "Coding Conventions" - "Error Handling" - - "Refactoring Techniques" - "Performance Optimization" frontend-typescript-testing: file: "frontend/typescript-testing.md" tags: [frontend, react, quality, testing, tdd, coverage, vitest, react-testing-library, msw, implementation] typical-use: "React component testing, React Testing Library tests, MSW API mocking, frontend test creation" - size: medium + size: small key-references: - "React Testing Library - Kent C. Dodds" - "MSW (Mock Service Worker) - MSW Team" @@ -171,13 +170,8 @@ rules: sections: - "Test Framework" - "Basic Testing Policy" - - "Red-Green-Refactor Process (Test-First Development)" - - "Test Design Principles" - - "Test Helper Utilization Rules" - "Test Implementation Conventions" - - "Test Granularity Principles" - "Mock Type Safety Enforcement" - - "Continuity Test Scope" - "Basic React Testing Library Example" frontend-technical-spec: @@ -197,27 +191,4 @@ rules: - "Build and Testing" - "Quality Check Requirements" - "Coverage Requirements" - - "Non-functional Requirements" - - frontend-ai-development-guide: - file: "frontend/ai-development-guide.md" - tags: [frontend, react, anti-patterns, technical-judgment, debugging, quality-commands, rule-of-three, implementation, lighthouse, bundle-size] - typical-use: "Frontend technical decision criteria, React anti-pattern detection, Lighthouse quality checks, bundle size optimization, frontend debugging" - size: medium - key-references: - - "Rule of Three - Martin Fowler" - - "React Component Best Practices - React Team" - - "Lighthouse Performance Guide - Google" - - "5 Whys - Toyota Production System" - - "Single Responsibility Principle (SRP) - Clean Code" - sections: - - "Technical Anti-patterns (Red Flag Patterns)" - - "Fallback Design Principles" - - "Rule of Three - Criteria for Code Duplication" - - "Common Failure Patterns and Avoidance Methods" - - "Debugging Techniques" - - "Quality Check Command Reference" - - "Situations Requiring Technical Decisions" - - "Continuous Improvement Mindset" - - "Implementation Completeness Assurance" - - "Unused Code Deletion Rule" \ No newline at end of file + - "Non-functional Requirements" \ No newline at end of file diff --git a/docs/rules-en/technical-spec.md b/docs/rules-en/technical-spec.md index 75da25d..bfa64b6 100644 --- a/docs/rules-en/technical-spec.md +++ b/docs/rules-en/technical-spec.md @@ -31,6 +31,66 @@ Maintain consistent data flow throughout the application: ## Build and Testing -Define build commands and test execution methods for each project. +### Build Commands +```bash +# TypeScript build +npm run build -Quality checks are mandatory upon implementation completion. \ No newline at end of file +# Type check (no emit) +npm run type-check +``` + +### Testing Commands +```bash +# Run tests +npm test + +# Run tests with coverage +npm run test:coverage + +# Run tests with coverage (fresh cache) +npm run test:coverage:fresh + +# Safe test execution (with auto cleanup) +npm run test:safe + +# Cleanup Vitest processes +npm run cleanup:processes +``` + +### Quality Check Requirements + +Quality checks are mandatory upon implementation completion: + +**Phase 1-3: Basic Checks** +```bash +npm run check # Biome (lint + format) +npm run check:unused # Detect unused exports +npm run build # TypeScript build +``` + +**Phase 4-6: Tests and Final Confirmation** +```bash +npm test # Test execution +npm run test:coverage:fresh # Coverage measurement +npm run check:all # Overall integrated check +``` + +### Auxiliary Commands +```bash +# Check coverage report +open coverage/index.html + +# Auto fixes +npm run format # Format fixes +npm run lint:fix # Lint fixes +``` + +### Troubleshooting +- **Port in use error**: `npm run cleanup:processes` +- **Cache issues**: `npm run test:coverage:fresh` +- **Dependency errors**: Reinstall with `npm ci` + +### Coverage Requirements +- **Mandatory**: Unit test coverage must be 70% or higher +- **Metrics**: Statements, Branches, Functions, Lines \ No newline at end of file diff --git a/docs/rules-en/typescript-testing.md b/docs/rules-en/typescript-testing.md index 230280a..76ec726 100644 --- a/docs/rules-en/typescript-testing.md +++ b/docs/rules-en/typescript-testing.md @@ -1,6 +1,7 @@ # TypeScript Testing Rules ## Test Framework + - **Vitest**: This project uses Vitest - Test imports: `import { describe, it, expect, beforeEach, vi } from 'vitest'` - Mock creation: Use `vi.mock()` @@ -35,77 +36,6 @@ - Success criteria: No change in response content, processing time within 5 seconds - Designed for automatic execution in CI/CD pipelines -## Red-Green-Refactor Process (Test-First Development) - -**Recommended Principle**: Always start code changes with tests - -**Background**: -- Ensure behavior before changes, prevent regression -- Clarify expected behavior before implementation -- Ensure safety during refactoring - -**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 - -**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) - -## Test Design Principles - -### Test Case Structure -- Tests consist of three stages: "Arrange," "Act," "Assert" -- Clear naming that shows purpose of each test -- One test case verifies only one behavior - -### Test Data Management -- Manage test data in dedicated directories -- Define test-specific environment variable values -- Always mock sensitive information -- Keep test data minimal, using only data directly related to test case verification purposes - -### Mock and Stub Usage Policy - -✅ **Recommended: Mock external dependencies in unit tests** -- Merit: Ensures test independence and reproducibility -- Practice: Mock DB, API, file system, and other external dependencies - -❌ **Avoid: Actual external connections in unit tests** -- Reason: Slows test speed and causes environment-dependent problems - -### Test Failure Response Decision Criteria - -**Fix tests**: Wrong expected values, references to non-existent features, dependence on implementation details, implementation only for tests -**Fix implementation**: Valid specifications, business logic, important edge cases -**When in doubt**: Confirm with user - -## Test Helper Utilization Rules - -### Basic Principles -Use test helpers to reduce duplication and improve maintainability. - -### Decision Criteria -| Mock Characteristics | Response Policy | -|---------------------|-----------------| -| **Simple and stable** | Consolidate in common helpers | -| **Complex or frequently changing** | Individual implementation | -| **Duplicated in 3+ places** | Consider consolidation | -| **Test-specific logic** | Individual implementation | - -### Test Helper Usage Examples -```typescript -// ✅ Builder pattern -const testData = new TestDataBuilder().withDefaults().withName('Test User').build() - -// ✅ Custom assertions -function assertValidUser(user: unknown): asserts user is User {} - -// ❌ Individual implementation of duplicate complex mocks -``` - ## Test Implementation Conventions ### Directory Structure @@ -125,7 +55,6 @@ src/ - Test suites: Names describing target features or situations - Test cases: Names describing expected behavior - ### Test Code Quality Rules ✅ **Recommended: Keep all tests always active** @@ -136,20 +65,6 @@ src/ - Reason: Creates test gaps and incomplete quality checks - Solution: Completely delete unnecessary tests -## Test Granularity Principles - -### Core Principle: Observable Behavior Only -**MUST Test**: Public APIs, return values, exceptions, external calls, persisted state -**MUST NOT Test**: Private methods, internal state, algorithm implementation details - -```typescript -// ✅ Test observable behavior -expect(calculatePrice(100, 0.1)).toBe(110) - -// ❌ Test implementation details -expect((calculator as any).taxRate).toBe(0.1) -``` - ## Mock Type Safety Enforcement ### Minimal Type Definition Requirements @@ -164,10 +79,6 @@ const sdkMock = { } as unknown as ExternalSDK // Complex external SDK type structure ``` -## Continuity Test Scope - -Limited to verifying existing feature impact when adding new features. Long-term operations and load testing are infrastructure responsibilities, not test scope. - ## Basic Vitest Example ```typescript @@ -185,4 +96,4 @@ describe('ComponentName', () => { expect(result).toBe('expected') }) }) -``` \ No newline at end of file +``` diff --git a/docs/rules-en/typescript.md b/docs/rules-en/typescript.md index 1c70329..81530b5 100644 --- a/docs/rules-en/typescript.md +++ b/docs/rules-en/typescript.md @@ -1,61 +1,22 @@ # TypeScript Development Rules -## Basic Principles - -✅ **Aggressive Refactoring** - Prevent technical debt and maintain health -❌ **Unused "Just in Case" Code** - Violates YAGNI principle (Kent Beck) - -## Comment Writing Rules -- **Function Description Focus**: Describe what the code "does" -- **No Historical Information**: Do not record development history -- **Timeless**: Write only content that remains valid whenever read -- **Conciseness**: Keep explanations to necessary minimum - -## Type Safety - -**Absolute Rule**: any type is completely prohibited. It disables type checking and becomes a source of runtime errors. - -**any Type Alternatives (Priority Order)** -1. **unknown Type + Type Guards**: Use for validating external input -2. **Generics**: When type flexibility is needed -3. **Union Types・Intersection Types**: Combinations of multiple types -4. **Type Assertions (Last Resort)**: Only when type is certain - -**Type Guard Implementation Pattern** -```typescript -function isUser(value: unknown): value is User { - return typeof value === 'object' && value !== null && 'id' in value && 'name' in value -} -``` - -**Modern Type Features** -- **satisfies Operator**: `const config = { port: 3000 } satisfies Config` - Preserves inference -- **const Assertion**: `const ROUTES = { HOME: '/' } as const satisfies Routes` - Immutable and type-safe -- **Branded Types**: `type UserId = string & { __brand: 'UserId' }` - Distinguish meaning -- **Template Literal Types**: `type Endpoint = \`\${HttpMethod} \${Route}\`` - Express string patterns with types - -**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 -- Legacy Integration: Stepwise assertion like `window as unknown as LegacyWindow` -- Test Code: Always define types for mocks, utilize `Partial` and `vi.fn<[Args], Return>()` +## Type Safety in Backend Implementation **Type Safety in Data Flow** Input Layer (`unknown`) → Type Guard → Business Layer (Type Guaranteed) → Output Layer (Serialization) -**Type Complexity Management** -- Field Count: Up to 20 (split by responsibility if exceeded, external API types are exceptions) -- Optional Ratio: Up to 30% (separate required/optional if exceeded) -- Nesting Depth: Up to 3 levels (flatten if exceeded) -- Type Assertions: Review design if used 3+ times -- **External API Types**: Relax constraints and define according to reality (convert appropriately internally) +**Backend-Specific Type Scenarios**: +- **API Communication**: Always receive responses as `unknown`, validate with type guards +- **Form Input**: External input as `unknown`, type determined after validation +- **Legacy Integration**: Stepwise assertion like `window as unknown as LegacyWindow` +- **Test Code**: Always define types for mocks, utilize `Partial` and `vi.fn<[Args], Return>()` ## Coding Conventions **Class Usage Criteria** - **Recommended: Implementation with Functions and Interfaces** - Rationale: Improves testability and flexibility of function composition -- **Classes Allowed**: +- **Classes Allowed**: - Framework requirements (NestJS Controller/Service, TypeORM Entity, etc.) - Custom error class definitions - When state and business logic are tightly coupled (e.g., ShoppingCart, Session, StateMachine) @@ -136,7 +97,7 @@ export class AppError extends Error { // Purpose-specific: ValidationError(400), BusinessRuleError(400), DatabaseError(500), ExternalServiceError(502) ``` -**Layer-Specific Error Handling** +**Layer-Specific Error Handling (Backend)** - API Layer: Convert to HTTP response, log output excluding sensitive information - Service Layer: Detect business rule violations, propagate AppError as-is - Repository Layer: Convert technical errors to domain errors @@ -149,18 +110,7 @@ Never include sensitive information (password, token, apiKey, secret, creditCard - Use try-catch with all async/await - Always log and re-throw errors -## Refactoring Techniques - -**Basic Policy** -- 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 → Gradual Changes → Behavior Verification → Final Validation - -**Priority**: Duplicate Code Removal > Large Function Division > Complex Conditional Branch Simplification > Type Safety Improvement - ## Performance Optimization - Streaming Processing: Process large datasets with streams -- Memory Leak Prevention: Explicitly release unnecessary objects \ No newline at end of file +- Memory Leak Prevention: Explicitly release unnecessary objects diff --git a/docs/rules-ja/ai-development-guide.md b/docs/rules-ja/coding-standards.md similarity index 59% rename from docs/rules-ja/ai-development-guide.md rename to docs/rules-ja/coding-standards.md index 1286635..19ad3b8 100644 --- a/docs/rules-ja/ai-development-guide.md +++ b/docs/rules-ja/coding-standards.md @@ -1,4 +1,4 @@ -# AI開発者ガイド - 技術的判断基準とアンチパターン集 +# 普遍的コーディング規約 ## 技術的アンチパターン(赤信号パターン) @@ -20,6 +20,17 @@ - **対処療法的修正** - 根本原因を解決しない表面的な修正 - **無計画な大規模変更** - 段階的アプローチの欠如 +## 基本原則 + +✅ **積極的なリファクタリング** - 技術的負債を防ぎ、健全性を維持 +❌ **使われない「念のため」のコード** - YAGNI原則(Kent Beck)に反する + +## コメント記述ルール +- **機能説明重視**: コードが「何をするか」を記述 +- **履歴情報禁止**: 開発履歴は記載しない +- **タイムレス**: いつ読んでも有効な内容のみ記述 +- **簡潔性**: 必要最小限の説明にとどめる + ## フォールバック処理に関する設計原則 ### 基本原則:Fail-Fast @@ -143,52 +154,46 @@ console.log('DEBUG:', { }) ``` -## 品質チェックコマンドリファレンス +## 型安全性の基礎 -### Phase 1-3: 基本チェック -```bash -# Biome総合チェック(lint + format) -npm run check +**絶対ルール**: `any`型は完全禁止。型チェックが無効化され、実行時エラーの温床となる。 -# 未使用エクスポートの検出 -npm run check:unused +**any型の代替手段(優先順位順)** +1. **unknown型 + 型ガード**: 外部入力の検証に使用 +2. **ジェネリクス**: 型の柔軟性が必要な場合 +3. **ユニオン型・インターセクション型**: 複数の型の組み合わせ +4. **型アサーション(最終手段)**: 型が確実な場合のみ -# TypeScriptビルド -npm run build +**型ガードの実装パターン** +```typescript +function isUser(value: unknown): value is User { + return typeof value === 'object' && value !== null && 'id' in value && 'name' in value +} ``` -### Phase 4-6: テストと最終確認 -```bash -# テスト実行 -npm test - -# カバレッジ測定(キャッシュクリア) -npm run test:coverage:fresh - -# 全体統合チェック -npm run check:all -``` +**モダンな型機能の活用** +- **satisfies演算子**: `const config = { port: 3000 } satisfies Config` - 型推論維持 +- **const assertion**: `const ROUTES = { HOME: '/' } as const satisfies Routes` - 不変かつ型安全 +- **ブランド型**: `type UserId = string & { __brand: 'UserId' }` - 意味を区別 +- **テンプレートリテラル型**: `type Endpoint = \`\${HttpMethod} \${Route}\`` - 文字列パターンを型で表現 -### 補助コマンド -```bash -# カバレッジレポート確認 -open coverage/index.html +**型の複雑性管理** +- フィールド数: 20個まで(超えたら責務で分割、外部API型は例外) +- オプショナル率: 30%まで(超えたら必須/任意で分離) +- ネスト深さ: 3階層まで(超えたらフラット化) +- 型アサーション: 3回以上使用したら設計見直し +- **外部API型の扱い**: 制約を緩和し、実態に合わせて定義(内部では適切に変換) -# Vitestプロセスのクリーンアップ(テスト後必須) -npm run cleanup:processes +## リファクタリング手法 -# 安全なテスト実行(自動クリーンアップ付き) -npm run test:safe +**基本方針** +- 小さなステップ: 段階的改善により、常に動作する状態を維持 +- 安全な変更: 一度に変更する範囲を最小限に抑制 +- 動作保証: 既存の動作を変えないことを確認しながら進める -# 自動修正 -npm run format # フォーマット修正 -npm run lint:fix # Lint修正 -``` +**実施手順**: 現状把握 → 段階的変更 → 動作確認 → 最終検証 -### トラブルシューティング -- **ポート使用中エラー**: `npm run cleanup:processes` -- **キャッシュ問題**: `npm run test:coverage:fresh` -- **依存関係エラー**: `npm ci`で再インストール +**優先順位**: 重複コード削除 > 長大な関数分割 > 複雑な条件分岐簡素化 > 型安全性向上 ## 技術的判断が必要な場面 @@ -257,4 +262,82 @@ Grep -n "targetData\|SetData\|UpdateData" -o content 使用中? No → 即削除(Git履歴に残る) Yes → 動作? No → 削除+再実装 Yes → 修正 -``` \ No newline at end of file +``` + +## Red-Green-Refactorプロセス(テストファースト開発) + +**推奨原則**: コード変更は必ずテストから始める + +**背景**: +- 変更前の動作を保証し、リグレッションを防止 +- 期待する動作を明確化してから実装 +- リファクタリング時の安全性を確保 + +**開発ステップ**: +1. **Red**: 期待する動作のテストを書く(失敗する) +2. **Green**: 最小限の実装でテストを通す +3. **Refactor**: テストが通る状態を維持しながらコード改善 + +**NGケース(テストファースト不要)**: +- 純粋な設定ファイル変更(.env、config等) +- ドキュメントのみの更新(README、コメント等) +- 緊急本番障害対応(ただし事後テスト必須) + +## テスト設計原則 + +### テストケースの構造 +- テストは「準備(Arrange)」「実行(Act)」「検証(Assert)」の3段階で構成 +- 各テストの目的が明確に分かる命名 +- 1つのテストケースでは1つの振る舞いのみを検証 + +### テストデータ管理 +- テストデータは専用ディレクトリで管理 +- 環境変数はテスト用の値を定義 +- 機密情報は必ずモック化 +- テストデータは最小限に保ち、テストケースの検証目的に直接関連するデータのみ使用 + +### モックとスタブの使用方針 + +✅ **推奨: 単体テストでの外部依存モック化** +- メリット: テストの独立性と再現性を確保 +- 実践: DB、API、ファイルシステム等の外部依存をモック化 + +❌ **避けるべき: 単体テストでの実際の外部接続** +- 理由: テスト速度が遅くなり、環境依存の問題が発生するため + +### テスト失敗時の対応判断基準 + +**テストを修正**: 間違った期待値、存在しない機能参照、実装詳細への依存、テストのためだけの実装 +**実装を修正**: 妥当な仕様、ビジネスロジック、重要なエッジケース +**判断に迷ったら**: ユーザーに確認 + +## テストヘルパーの活用ルール + +### 基本原則 +テストヘルパーは、テストコードの重複を減らし、保守性を高めるために活用します。 + +### 判断基準 +| モックの特性 | 対応方針 | +|-------------|---------| +| **単純で安定** | 共通ヘルパーに集約 | +| **複雑または変更頻度高** | 個別実装 | +| **3箇所以上で重複** | 共通化を検討 | +| **テスト固有ロジック** | 個別実装 | + +## テストの粒度原則 + +### 原則:観測可能な振る舞いのみ +**テスト対象**:公開API、戻り値、例外、外部呼び出し、永続化された状態 +**テスト対象外**:privateメソッド、内部状態、アルゴリズム詳細 + +```typescript +// ✅ 振る舞いをテスト +expect(calculatePrice(100, 0.1)).toBe(110) + +// ❌ 実装詳細をテスト +expect((calculator as any).taxRate).toBe(0.1) +``` + +## 継続性テストの範囲 + +新機能追加時の既存機能への影響確認に限定。長時間運用・負荷テストはインフラ層の責務のため対象外。 \ No newline at end of file diff --git a/docs/rules-ja/frontend/ai-development-guide.md b/docs/rules-ja/frontend/ai-development-guide.md deleted file mode 100644 index 969ba9e..0000000 --- a/docs/rules-ja/frontend/ai-development-guide.md +++ /dev/null @@ -1,261 +0,0 @@ -# AI開発者ガイド - 技術的判断基準とアンチパターン集(フロントエンド) - -## 技術的アンチパターン(赤信号パターン) - -以下のパターンを検出したら即座に停止し、設計を見直すこと: - -### コード品質のアンチパターン -1. **同じようなコードを3回以上書いた** - Rule of Threeに違反 -2. **単一コンポーネントに複数の責務が混在** - 単一責任原則(SRP)違反 -3. **同じ内容を複数コンポーネントで定義** - DRY原則違反 -4. **依存関係を確認せずに変更** - 予期しない影響の可能性 -5. **コメントアウトでコード無効化** - バージョン管理を活用すべき -6. **エラーの握りつぶし** - 問題の隠蔽は技術的負債 -7. **型アサーション(as)の多用** - 型安全性の放棄 -8. **3階層以上のProp drilling** - Context APIまたは状態管理を使用すべき -9. **大規模コンポーネント(300行以上)** - より小さいコンポーネントに分割 - -### 設計のアンチパターン -- **「一旦動くように」という思考** - 技術的負債の蓄積 -- **継ぎ足し実装** - 既存コンポーネントへの無計画な追加 -- **不確実技術の楽観的実装** - 未知要素を「たぶん動く」前提で設計 -- **対処療法的修正** - 根本原因を解決しない表面的な修正 -- **無計画な大規模変更** - 段階的アプローチの欠如 - -## フォールバック処理に関する設計原則 - -### 基本原則:Fail-Fast -分散システムにおいて、フォールバック処理よりもプライマリコードの信頼性向上を優先する設計思想。 - -### フォールバック実装の判断基準 -- **原則禁止**: エラー時の無条件フォールバックは実装しない -- **例外的許可**: Design Docで明示的に定義された場合のみ実装 -- **レイヤー責務**: - - コンポーネント層: Error Boundaryでエラーハンドリング - - フック層: ビジネス要件に基づく判断を実装 - -### フォールバック過多の検出 -- 同一機能で3つ目のcatch文を書く時点で設計見直しを必須とする -- フォールバックを実装する前にDesign Docでの定義を確認 -- エラーは適切にログ出力し、失敗を明確にする - -## Rule of Three - コード重複の判断基準 - -Martin Fowler「Refactoring」に基づく重複コードの扱い方: - -| 重複回数 | 対応 | 理由 | -|---------|------|------| -| 1回目 | インライン実装 | 将来の変化が予測できない | -| 2回目 | 将来の統合を意識 | パターンが見え始める | -| 3回目 | 共通化実施 | パターンが確立された | - -### 共通化の判断基準 - -**共通化すべきケース** -- ビジネスロジックの重複 -- 複雑な処理アルゴリズム -- コンポーネントパターン(フォームフィールド、カード等) -- カスタムフック -- バリデーションルール - -**共通化を避けるべきケース** -- 偶然の一致(たまたま同じコード) -- 将来異なる方向に進化する可能性 -- 共通化により可読性が著しく低下 -- テストコード内の簡単なヘルパー - -### 実装例 -```typescript -// ❌ 1回目の重複で即共通化 -function UserEmailInput() { /* ... */ } -function ContactEmailInput() { /* ... */ } - -// ✅ 3回目で共通化 -function EmailInput({ context }: { context: 'user' | 'contact' | 'admin' }) { /* ... */ } -``` - -## よくある失敗パターンと回避方法 - -### パターン1: エラー修正の連鎖 -**症状**: エラーを修正すると新しいエラーが発生 -**原因**: 根本原因を理解せずに表面的な修正 -**回避方法**: 5 Whysで根本原因を特定してから修正 - -### パターン2: 型安全性の放棄 -**症状**: any型やasの多用 -**原因**: 型エラーを回避したい衝動 -**回避方法**: unknown型と型ガードで安全に処理 - -### パターン3: テスト不足での実装 -**症状**: 実装後にバグ多発 -**原因**: Red-Green-Refactorプロセスの無視 -**回避方法**: 必ず失敗するテストから開始 - -### パターン4: 技術的不確実性の無視 -**症状**: 新技術導入時の想定外エラー多発 -**原因**: 事前調査なしで「公式ドキュメント通りなら動くはず」 -**回避方法**: -- タスクファイル冒頭に確実性評価を記載 - ``` - 確実性: low(理由: 本番実績が限定的な実験的機能) - 探索的実装: true - フォールバック: 確立されたパターンを使用 - ``` -- 確実性lowの場合、最初に最小限の動作確認コードを作成 - -### パターン5: 既存コード調査不足 -**症状**: 重複実装、アーキテクチャ不整合、結合時の障害 -**原因**: 実装前の既存コード理解不足 -**回避方法**: -- 実装前に類似機能の存在を必ず検索(同じドメイン、責務、コンポーネントパターンをキーワードに) -- 類似機能を発見 → その実装を使用する(新規実装は行わない) -- 類似機能が技術的負債 → ADRで改善提案を作成してから実装 -- 類似機能が存在しない → 既存の設計思想に沿って新規実装 -- すべての判断と根拠をDesign Docの「既存コードベース分析」セクションに記録 - -## デバッグ手法 - -### 1. エラー分析手順 -1. エラーメッセージ(最初の行)を正確に読む -2. スタックトレースの最初と最後に注目 -3. 自分のコードが現れる最初の行を特定 -4. React DevToolsでコンポーネント階層を確認 - -### 2. 5 Whys - 根本原因分析 -``` -症状: コンポーネントがレンダリングされない -Why1: Propsがundefined → Why2: 親コンポーネントがPropsを渡していない -Why3: 親が古いProp名を使用 → Why4: コンポーネントインターフェースが更新された -Why5: リファクタリング後に親の更新漏れ -根本原因: リファクタリングが不完全、呼び出し側の更新漏れ -``` - -### 3. 最小再現コード -問題を切り分けるため、最小限のコードで再現を試みる: -- 関連のないコンポーネントを削除 -- API呼び出しをモックで置き換え -- 問題が再現する最小構成を作成 -- React DevToolsでコンポーネントツリーを検査 - -### 4. デバッグログ出力 -```typescript -console.log('DEBUG:', { - context: 'user-form-submission', - props: { email, name }, - state: currentState, - timestamp: new Date().toISOString() -}) -``` - -## 品質チェックコマンドリファレンス - -### Phase 1-3: 基本チェック -```bash -# Biome総合チェック(lint + format) -npm run check - -# TypeScriptビルド -npm run build -``` - -### Phase 4-5: テストと最終確認 -```bash -# テスト実行 -npm test - -# カバレッジ測定(キャッシュクリア) -npm run test:coverage:fresh - -# 全体統合チェック -npm run check:all -``` - -### 補助コマンド -```bash -# カバレッジレポート確認 -open coverage/index.html - -# Vitestプロセスのクリーンアップ(テスト後必須) -npm run cleanup:processes - -# 安全なテスト実行(自動クリーンアップ付き) -npm run test:safe - -# 自動修正 -npm run format # フォーマット修正 -npm run lint:fix # Lint修正 -``` - -### トラブルシューティング -- **ポート使用中エラー**: `npm run cleanup:processes` -- **キャッシュ問題**: `npm run test:coverage:fresh` -- **依存関係エラー**: `npm ci`で再インストール - -## 技術的判断が必要な場面 - -### 抽象化のタイミング -- 具体的な実装を3回書いてからパターンを抽出 -- YAGNIを意識し、現在必要な機能のみ実装 -- 将来の拡張性より現在のシンプルさを優先 - -### パフォーマンス vs 可読性 -- 明確なボトルネックがない限り可読性を優先 -- 計測してから最適化(推測するな、React DevTools Profilerを使え) -- 最適化する場合はコメントで理由を明記 - -### コンポーネント/型定義の粒度 -- 過度に細かいコンポーネント/型は保守性を低下させる -- UIパターンを適切に表現するコンポーネントを設計 -- 継承よりコンポジションを使用 - -## 継続的改善のマインドセット - -- **謙虚**: 完璧なコードは存在しない、フィードバック歓迎 -- **勇気**: 必要なリファクタリングは大胆に実行 -- **透明性**: 技術的な判断理由を明確に記録 - -## 実装作業の完全性担保 - -### 影響範囲調査の必須手順 - -**完了定義**: 以下3段階すべての完了 - -#### 1. 検索(Discovery) -```bash -Grep -n "ComponentName\|hookName" -o content -Grep -n "importedFunction" -o content -Grep -n "propsType\|StateType" -o content -``` - -#### 2. 読解(Understanding) -**必須**: 発見した全ファイルを読み込み、作業に必要な部分をコンテキストに含める: -- 呼び出し元の目的と文脈 -- コンポーネント階層 -- データフロー: Props → State → イベントハンドラ → コールバック - -#### 3. 特定(Identification) -影響範囲の構造化報告(必須): -``` -## 影響範囲分析 -### 直接影響: ComponentA、ComponentB(理由明記) -### 間接影響: FeatureX、PageY(連携経路明記) -### 処理フロー: Props → Render → Events → Callbacks -``` - -**重要**: 検索のみで完了とせず、3段階すべてを実行すること - -### 未使用コード削除ルール - -未使用コード検出時 → 使用予定? -- Yes → 即実装(保留禁止) -- No → 即削除(Git履歴に残る) - -対象: コンポーネント、フック、ユーティリティ、ドキュメント、設定ファイル - -### 既存コード削除判断フロー - -``` -使用中? No → 即削除(Git履歴に残る) - Yes → 動作? No → 削除+再実装 - Yes → 修正 -``` diff --git a/docs/rules-ja/frontend/typescript-testing.md b/docs/rules-ja/frontend/typescript-testing.md index bcc133f..7ce54b9 100644 --- a/docs/rules-ja/frontend/typescript-testing.md +++ b/docs/rules-ja/frontend/typescript-testing.md @@ -47,79 +47,6 @@ - 判定基準: 表示内容の変化なし、レンダリング時間5秒以内 - CI/CDでの自動実行を前提とした設計 -## Red-Green-Refactorプロセス(テストファースト開発) - -**推奨原則**: コード変更は必ずテストから始める - -**背景**: -- 変更前の動作を保証し、リグレッションを防止 -- 期待する動作を明確化してから実装 -- リファクタリング時の安全性を確保 - -**開発ステップ**: -1. **Red**: 期待する動作のテストを書く(失敗する) -2. **Green**: 最小限の実装でテストを通す -3. **Refactor**: テストが通る状態を維持しながらコード改善 - -**NGケース(テストファースト不要)**: -- 純粋な設定ファイル変更(vite.config.ts、tailwind.config.js等) -- ドキュメントのみの更新(README、コメント等) -- 緊急本番障害対応(ただし事後テスト必須) - -## テストの設計原則 - -### テストケースの構造 -- テストは「準備(Arrange)」「実行(Act)」「検証(Assert)」の3段階で構成 -- 各テストの目的が明確に分かる命名 -- 1つのテストケースでは1つの振る舞いのみを検証 - -### テストデータ管理 -- テストデータは専用ディレクトリで管理、またはテストと同じ場所に配置 -- テスト用の環境変数値を定義 -- 機密情報は必ずモック化 -- テストデータは最小限に保ち、テストケースの検証目的に直接関連するデータのみ使用 - -### モックとスタブの使用方針 - -✅ **推奨: 単体テストでの外部依存モック化** -- メリット: テストの独立性と再現性を確保 -- 実践: MSWでAPI呼び出しをモック、外部ライブラリをモック化 - -❌ **避けるべき: 単体テストでの実際のAPI接続** -- 理由: テスト速度が遅くなり、環境依存の問題が発生するため - -### テスト失敗時の対応判断基準 - -**テストを修正**: 間違った期待値、存在しない機能参照、実装詳細への依存、テストのためだけの実装 -**実装を修正**: 妥当な仕様、ビジネスロジック、重要なエッジケース -**判断に迷ったら**: ユーザーに確認 - -## テストヘルパーの活用ルール - -### 基本原則 -テストヘルパーは、テストコードの重複を減らし、保守性を高めるために活用します。 - -### 判断基準 -| モックの特性 | 対応方針 | -|-------------|---------| -| **単純で安定** | 共通ヘルパーに集約 | -| **複雑または変更頻度高** | 個別実装 | -| **3箇所以上で重複** | 共通化を検討 | -| **テスト固有ロジック** | 個別実装 | - -### テストヘルパー活用例 -```typescript -// ✅ テストデータのビルダーパターン -const testUser = createTestUser({ name: 'Test User', email: 'test@example.com' }) - -// ✅ Providerを含むカスタムレンダー関数 -function renderWithProviders(ui: React.ReactElement) { - return render({ui}) -} - -// ❌ 重複する複雑なモックの個別実装 -``` - ## テストの実装規約 ### ディレクトリ構造(Co-location原則) @@ -153,20 +80,6 @@ src/ - 理由: テストの穴が生まれ、品質チェックが不完全になる - 対処: 不要なテストは完全に削除する -## テストの粒度原則 - -### 基本原則:ユーザーから観測可能な振る舞いのみ -**テスト対象**: レンダリング結果、ユーザーインタラクション、アクセシビリティ、エラー状態 -**テスト対象外**: コンポーネント内部状態、実装詳細、CSSクラス名 - -```typescript -// ✅ ユーザーから観測可能な振る舞いをテスト -expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument() - -// ❌ 実装詳細をテスト -expect(component.state.count).toBe(0) -``` - ## モックの型安全性の徹底 ### MSW(Mock Service Worker)セットアップ @@ -193,10 +106,6 @@ const mockRouter = { } as unknown as Router // 複雑なRouter型構造のため ``` -## 継続性テストの範囲 - -新機能追加時の既存機能への影響確認に限定。長時間運用・負荷テストはインフラ層の責務のため対象外。 - ## React Testing Libraryの基本例 ```typescript diff --git a/docs/rules-ja/frontend/typescript.md b/docs/rules-ja/frontend/typescript.md index 89db5b0..c68b636 100644 --- a/docs/rules-ja/frontend/typescript.md +++ b/docs/rules-ja/frontend/typescript.md @@ -1,51 +1,26 @@ -# TypeScript開発ルール(フロントエンド) +# TypeScript開発ルール -## 基本原則 +## フロントエンド固有のアンチパターン -✅ **積極的なリファクタリング** - 技術的負債を防ぎ、健全性を維持 -❌ **「念のため」の未使用コード** - YAGNI原則違反(Kent Beck) +coding-standards.mdの普遍的アンチパターンに加え、以下のフロントエンド固有の問題に注意: -## コメント記述ルール -- **機能説明に集中**: コードが「何をするか」を説明 -- **履歴情報なし**: 開発経緯は記録しない -- **時間に依存しない**: いつ読んでも有効な内容のみ記載 -- **簡潔性**: 必要最小限の説明に留める +- **3階層以上のProp drilling** - Context APIまたは状態管理を使用すべき +- **巨大なコンポーネント(300行以上)** - 小さなコンポーネントに分割 -## 型安全性 +## Frontend実装における型安全性 -**絶対ルール**: any型は完全禁止。型チェックを無効化し、実行時エラーの元凶となる。 - -**any型の代替策(優先順位順)** -1. **unknown型 + 型ガード**: 外部入力の検証に使用(APIレスポンス、localStorage、URLパラメータ) -2. **ジェネリクス**: 型の柔軟性が必要な場合 -3. **Union Types・Intersection Types**: 複数の型の組み合わせ -4. **型アサーション(最終手段)**: 型が確実な場合のみ - -**型ガード実装パターン** -```typescript -function isUser(value: unknown): value is User { - return typeof value === 'object' && value !== null && 'id' in value && 'name' in value -} -``` - -**モダンな型機能** -- **satisfies演算子**: `const config = { apiUrl: '/api' } satisfies Config` - 推論を保持 -- **const assertion**: `const ROUTES = { HOME: '/' } as const satisfies Routes` - 不変かつ型安全 -- **Branded Types**: `type UserId = string & { __brand: 'UserId' }` - 意味を区別 -- **Template Literal Types**: `type EventName = \`on\${Capitalize}\`` - 文字列パターンを型で表現 +**データフローにおける型安全性** +- **Frontend → Backend**: Props/State(型保証済み) → APIリクエスト(シリアライゼーション) +- **Backend → Frontend**: APIレスポンス(`unknown`) → 型ガード → State(型保証済み) -**フロントエンド実装における型安全性** +**Frontend固有の型シナリオ**: - **React Props/State**: TypeScriptが型管理、unknown不要 - **外部APIレスポンス**: 常に`unknown`として受け取り、型ガードで検証 - **localStorage/sessionStorage**: `unknown`として扱い、検証 - **URLパラメータ**: `unknown`として扱い、検証 - **Form入力(Controlled Components)**: React合成イベントで型安全 -**データフローにおける型安全性** -- **Frontend → Backend**: Props/State(型保証済み) → APIリクエスト(シリアライゼーション) -- **Backend → Frontend**: APIレスポンス(`unknown`) → 型ガード → State(型保証済み) - -**型の複雑性管理** +**型の複雑性管理(Frontend)** - **Props設計**: - Props数: 3-7個が理想(10個超えたらコンポーネント分割検討) - Optional Props: 50%以下(多すぎる場合はデフォルト値やContext使用検討) @@ -148,17 +123,6 @@ export class AppError extends Error { - イベントハンドラ内の全async/awaitでtry-catch使用 - エラーは常にログ記録し、再スローまたはerror stateで表示 -## リファクタリング手法 - -**基本方針** -- 小さなステップ: 段階的改善により常に動作する状態を維持 -- 安全な変更: 一度に変更する範囲を最小化 -- 動作保証: 既存の動作が変わらないことを確認しながら進める - -**実施手順**: 現状把握 → 段階的変更 → 動作確認 → 最終検証 - -**優先順位**: 重複コード削除 > 大きな関数の分割 > 複雑な条件分岐の簡略化 > 型安全性向上 - ## パフォーマンス最適化 - コンポーネントメモ化: 高コストコンポーネントにReact.memo使用 diff --git a/docs/rules-ja/rules-index.yaml b/docs/rules-ja/rules-index.yaml index fdf59ea..d15c082 100644 --- a/docs/rules-ja/rules-index.yaml +++ b/docs/rules-ja/rules-index.yaml @@ -2,79 +2,71 @@ # 各ルールの概要、タグ、典型的な使用場面、サイズを管理 rules: - typescript: - file: "typescript.md" - tags: [implementation, type-safety, async, refactoring, coding-style, functional-programming, dependency-injection, branded-types] - typical-use: "TypeScriptコードの作成・修正・リファクタリング、モダンな型機能活用" - size: medium + coding-standards: + file: "coding-standards.md" + tags: [anti-patterns, technical-judgment, debugging, rule-of-three, implementation, type-safety, refactoring, code-reading, best-practices, impact-analysis, unused-code, code-deletion, testing, tdd] + typical-use: "全ドメイン共通の技術的判断基準、アンチパターン検出、デバッグ手法、実装時のベストプラクティス、影響範囲調査、未使用コード削除、テスト設計原則" + size: large key-references: - - "YAGNI原則 - Kent Beck" - - "Clean Code - Robert C. Martin" + - "Rule of Three - Martin Fowler" + - "5 Whys - トヨタ生産方式" - "DRY原則 - The Pragmatic Programmer" - - "Refactoring - Martin Fowler" - - "TypeScript 4.9 satisfies演算子 - Microsoft" - - "Branded Types - TypeScript Community" - - "Effect-TS / fp-ts - 関数型プログラミング" - - "Dependency Injection - Martin Fowler" + - "単一責任原則(SRP) - Clean Code" + - "YAGNI原則 - Extreme Programming" - "Avoiding fallback in distributed systems - AWS Builders' Library" + - "Test-Driven Development - Kent Beck" + - "Red-Green-Refactor - Kent Beck" + - "AAAパターン - Arrange-Act-Assert" sections: + - "技術的アンチパターン(赤信号パターン)" - "基本原則" - "コメント記述ルール" - - "型安全性" + - "フォールバック処理に関する設計原則" + - "Rule of Three - コード重複の判断基準" + - "よくある失敗パターンと回避方法" + - "デバッグ手法" + - "型安全性の基礎" + - "リファクタリング手法" + - "技術的判断が必要な場面" + - "継続的改善のマインドセット" + - "実装作業の完全性担保" + - "Red-Green-Refactorプロセス(テストファースト開発)" + - "テスト設計原則" + - "テストヘルパーの活用ルール" + - "テストの粒度原則" + - "継続性テストの範囲" + + typescript: + file: "typescript.md" + tags: [implementation, type-safety, async, coding-style, functional-programming, dependency-injection, backend] + typical-use: "バックエンドTypeScriptコードの作成・修正、クラス使用判断、DI実装" + size: small + key-references: + - "Dependency Injection - Martin Fowler" + sections: + - "Backend実装における型安全性" - "コーディング規約" - "エラーハンドリング" - - "リファクタリング手法" - "パフォーマンス最適化" typescript-testing: file: "typescript-testing.md" - tags: [quality, testing, tdd, coverage, vitest, implementation, debugging, refactoring] - typical-use: "テスト作成、品質チェック、コード修正・バグ修正・リファクタリング・新機能実装時の開発ステップ" - size: medium + tags: [quality, testing, coverage, vitest, backend, implementation] + typical-use: "バックエンドテスト作成、Vitest設定、70%カバレッジ要件" + size: small key-references: - - "Test-Driven Development - Kent Beck" - - "Rule of Three - Martin Fowler" - - "Red-Green-Refactor - Kent Beck" - - "AAAパターン - Arrange-Act-Assert" + - "Vitest公式ドキュメント" sections: - "テストフレームワーク" - "テストの基本方針" - - "Red-Green-Refactorプロセス(テストファースト開発)" - - "テストの設計原則" - - "テストヘルパーの活用ルール" - "テストの実装規約" - - "テストの粒度" - "モックの型安全性" - - "継続性テストの範囲" - "Vitestの基本例" - ai-development-guide: - file: "ai-development-guide.md" - tags: [anti-patterns, technical-judgment, debugging, quality-commands, rule-of-three, implementation, type-safety, refactoring, code-reading, best-practices, impact-analysis, unused-code, code-deletion] - typical-use: "技術的判断基準、アンチパターン検出、デバッグ手法、品質チェックコマンド、実装時のベストプラクティス、影響範囲調査、未使用コード削除" - size: medium - key-references: - - "Rule of Three - Martin Fowler" - - "5 Whys - トヨタ生産方式" - - "DRY原則 - The Pragmatic Programmer" - - "単一責任原則(SRP) - Clean Code" - - "YAGNI原則 - Extreme Programming" - - "Avoiding fallback in distributed systems - AWS Builders' Library" - sections: - - "技術的アンチパターン(赤信号パターン)" - - "フォールバック処理に関する設計原則" - - "Rule of Three - コード重複の判断基準" - - "よくある失敗パターンと回避方法" - - "デバッグ手法" - - "品質チェックコマンドリファレンス" - - "技術的判断が必要な場面" - - "継続的改善のマインドセット" - - "実装作業の完全性担保" - technical-spec: file: "technical-spec.md" - tags: [architecture, design, documentation, environment, data-flow, implementation] - typical-use: "技術設計、環境設定、ドキュメント作成プロセス、実装方針決定" + tags: [architecture, design, documentation, environment, data-flow, implementation, quality-commands, testing, build] + typical-use: "技術設計、環境設定、ドキュメント作成プロセス、実装方針決定、品質チェックコマンド、ビルドとテスト実行" size: medium key-references: - "ADRフォーマット - Michael Nygard" @@ -138,78 +130,35 @@ rules: frontend-typescript: file: "frontend/typescript.md" - tags: [frontend, react, implementation, type-safety, async, refactoring, coding-style, props-driven, hooks, component-design, vite, error-boundary] - typical-use: "React/Viteでのフロントエンド開発、コンポーネント設計、TypeScript実装、モダンな型機能活用" - size: medium + tags: [frontend, react, implementation, type-safety, props-driven, hooks, component-design, vite, error-boundary] + typical-use: "React/Viteでのフロントエンド開発、コンポーネント設計、Props設計、環境変数管理" + size: small 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" - "React公式ドキュメント - Function Components" - "Props-driven開発 - React Patterns" sections: - - "基本原則" - - "コメント記述ルール" - - "型安全性" + - "フロントエンド固有のアンチパターン" + - "Frontend実装における型安全性" - "コーディング規約" - "エラーハンドリング" - - "リファクタリング手法" - "パフォーマンス最適化" frontend-typescript-testing: file: "frontend/typescript-testing.md" - tags: [frontend, react, quality, testing, tdd, coverage, vitest, react-testing-library, msw, component-testing, implementation, debugging, refactoring, user-observable-behavior] - typical-use: "Reactコンポーネントのテスト作成、品質チェック、コード修正・バグ修正・リファクタリング・新機能実装時の開発ステップ" - size: medium + tags: [frontend, react, quality, testing, coverage, vitest, react-testing-library, msw, component-testing, implementation] + typical-use: "Reactコンポーネントのテスト作成、React Testing Library、MSW、60%カバレッジ要件、Co-location" + size: small key-references: - - "Test-Driven Development - Kent Beck" - - "Rule of Three - Martin Fowler" - - "Red-Green-Refactor - Kent Beck" - - "AAAパターン - Arrange-Act-Assert" - "React Testing Library - Kent C. Dodds" - "MSW (Mock Service Worker) - API Mocking" - "ADR-0002 Co-location原則" - - "Testing Implementation Details - Kent C. Dodds" sections: - "テストフレームワーク" - "テストの基本方針" - - "Red-Green-Refactorプロセス(テストファースト開発)" - - "テストの設計原則" - - "テストヘルパーの活用ルール" - "テストの実装規約" - - "テストの粒度原則" - "モックの型安全性の徹底" - - "継続性テストの範囲" - "React Testing Libraryの基本例" - frontend-ai-development-guide: - file: "frontend/ai-development-guide.md" - tags: [frontend, react, anti-patterns, technical-judgment, debugging, quality-commands, rule-of-three, implementation, type-safety, refactoring, code-reading, best-practices, impact-analysis, unused-code, code-deletion, prop-drilling, component-hierarchy, lighthouse, bundle-size] - typical-use: "React開発での技術的判断基準、アンチパターン検出、デバッグ手法、品質チェックコマンド、実装時のベストプラクティス、影響範囲調査、未使用コード削除、フロントエンド固有の品質指標" - size: medium - key-references: - - "Rule of Three - Martin Fowler" - - "5 Whys - トヨタ生産方式" - - "DRY原則 - The Pragmatic Programmer" - - "単一責任原則(SRP) - Clean Code" - - "YAGNI原則 - Extreme Programming" - - "Avoiding fallback in distributed systems - AWS Builders' Library" - - "React DevTools - Meta" - - "Lighthouse - Google" - sections: - - "技術的アンチパターン(赤信号パターン)" - - "フォールバック処理に関する設計原則" - - "Rule of Three - コード重複の判断基準" - - "よくある失敗パターンと回避方法" - - "デバッグ手法" - - "品質チェックコマンドリファレンス" - - "技術的判断が必要な場面" - - "継続的改善のマインドセット" - - "実装作業の完全性担保" - frontend-technical-spec: file: "frontend/technical-spec.md" tags: [frontend, react, architecture, design, documentation, environment, data-flow, implementation, vite, security, client-side, state-management, context-api, hooks, lighthouse, bundle-size, non-functional-requirements] diff --git a/docs/rules-ja/technical-spec.md b/docs/rules-ja/technical-spec.md index 8663e5c..f1b0a9f 100644 --- a/docs/rules-ja/technical-spec.md +++ b/docs/rules-ja/technical-spec.md @@ -42,6 +42,66 @@ TypeScriptをベースとしたアプリケーション実装。アーキテク ## ビルドとテスト -プロジェクトごとにビルドコマンドとテスト実行方法を定義。 +### ビルドコマンド +```bash +# TypeScriptビルド +npm run build -品質チェックは実装完了時に必須。 \ No newline at end of file +# 型チェック(emit なし) +npm run type-check +``` + +### テストコマンド +```bash +# テスト実行 +npm test + +# カバレッジ測定 +npm run test:coverage + +# カバレッジ測定(キャッシュクリア) +npm run test:coverage:fresh + +# 安全なテスト実行(自動クリーンアップ付き) +npm run test:safe + +# Vitestプロセスのクリーンアップ +npm run cleanup:processes +``` + +### 品質チェック要件 + +品質チェックは実装完了時に必須: + +**Phase 1-3: 基本チェック** +```bash +npm run check # Biome(lint + format) +npm run check:unused # 未使用エクスポートの検出 +npm run build # TypeScriptビルド +``` + +**Phase 4-6: テストと最終確認** +```bash +npm test # テスト実行 +npm run test:coverage:fresh # カバレッジ測定 +npm run check:all # 全体統合チェック +``` + +### 補助コマンド +```bash +# カバレッジレポート確認 +open coverage/index.html + +# 自動修正 +npm run format # フォーマット修正 +npm run lint:fix # Lint修正 +``` + +### トラブルシューティング +- **ポート使用中エラー**: `npm run cleanup:processes` +- **キャッシュ問題**: `npm run test:coverage:fresh` +- **依存関係エラー**: `npm ci`で再インストール + +### カバレッジ要件 +- **必須**: ユニットテストカバレッジは70%以上 +- **メトリクス**: Statements、Branches、Functions、Lines \ No newline at end of file diff --git a/docs/rules-ja/typescript-testing.md b/docs/rules-ja/typescript-testing.md index c9e60fd..540e217 100644 --- a/docs/rules-ja/typescript-testing.md +++ b/docs/rules-ja/typescript-testing.md @@ -35,77 +35,6 @@ - 判定基準: レスポンス内容の変化なし、処理時間5秒以内 - CI/CDでの自動実行を前提とした設計 -## Red-Green-Refactorプロセス(テストファースト開発) - -**推奨原則**: コード変更は必ずテストから始める - -**背景**: -- 変更前の動作を保証し、リグレッションを防止 -- 期待する動作を明確化してから実装 -- リファクタリング時の安全性を確保 - -**開発ステップ**: -1. **Red**: 期待する動作のテストを書く(失敗する) -2. **Green**: 最小限の実装でテストを通す -3. **Refactor**: テストが通る状態を維持しながらコード改善 - -**NGケース(テストファースト不要)**: -- 純粋な設定ファイル変更(.env、config等) -- ドキュメントのみの更新(README、コメント等) -- 緊急本番障害対応(ただし事後テスト必須) - -## テストの設計原則 - -### テストケースの構造 -- テストは「準備(Arrange)」「実行(Act)」「検証(Assert)」の3段階で構成 -- 各テストの目的が明確に分かる命名 -- 1つのテストケースでは1つの振る舞いのみを検証 - -### テストデータ管理 -- テストデータは専用ディレクトリで管理 -- 環境変数はテスト用の値を定義 -- 機密情報は必ずモック化 -- テストデータは最小限に保ち、テストケースの検証目的に直接関連するデータのみ使用 - -### モックとスタブの使用方針 - -✅ **推奨: 単体テストでの外部依存モック化** -- メリット: テストの独立性と再現性を確保 -- 実践: DB、API、ファイルシステム等の外部依存をモック化 - -❌ **避けるべき: 単体テストでの実際の外部接続** -- 理由: テスト速度が遅くなり、環境依存の問題が発生するため - -### テスト失敗時の対応判断基準 - -**テストを修正**: 間違った期待値、存在しない機能参照、実装詳細への依存、テストのためだけの実装 -**実装を修正**: 妥当な仕様、ビジネスロジック、重要なエッジケース -**判断に迷ったら**: ユーザーに確認 - -## テストヘルパーの活用ルール - -### 基本原則 -テストヘルパーは、テストコードの重複を減らし、保守性を高めるために活用します。 - -### 判断基準 -| モックの特性 | 対応方針 | -|-------------|---------| -| **単純で安定** | 共通ヘルパーに集約 | -| **複雑または変更頻度高** | 個別実装 | -| **3箇所以上で重複** | 共通化を検討 | -| **テスト固有ロジック** | 個別実装 | - -### テストヘルパー活用例 -```typescript -// ✅ ビルダーパターン -const testData = new TestDataBuilder().withDefaults().withName('Test User').build() - -// ✅ カスタムアサーション -function assertValidUser(user: unknown): asserts user is User {} - -// ❌ 重複する複雑なモックの個別実装 -``` - ## テストの実装規約 ### ディレクトリ構造 @@ -136,20 +65,6 @@ src/ - 理由: テストの穴が生まれ、品質チェックが不完全になる - 対処: 不要なテストは完全に削除する -## テストの粒度 - -### 原則:観測可能な振る舞いのみ -**テスト対象**:公開API、戻り値、例外、外部呼び出し、永続化された状態 -**テスト対象外**:privateメソッド、内部状態、アルゴリズム詳細 - -```typescript -// ✅ 振る舞いをテスト -expect(calculatePrice(100, 0.1)).toBe(110) - -// ❌ 実装詳細をテスト -expect((calculator as any).taxRate).toBe(0.1) -``` - ## モックの型安全性 ### 必要最小限の型定義 @@ -164,10 +79,6 @@ const sdkMock = { } as unknown as ExternalSDK // 外部SDKの複雑な型のため ``` -## 継続性テストの範囲 - -新機能追加時の既存機能への影響確認に限定。長時間運用・負荷テストはインフラ層の責務のため対象外。 - ## Vitestの基本例 ```typescript diff --git a/docs/rules-ja/typescript.md b/docs/rules-ja/typescript.md index 2b04cd0..83d5f5f 100644 --- a/docs/rules-ja/typescript.md +++ b/docs/rules-ja/typescript.md @@ -1,54 +1,15 @@ # TypeScript 開発ルール -## 基本原則 - -✅ **積極的なリファクタリング** - 技術的負債を防ぎ、健全性を維持 -❌ **使われない「念のため」のコード** - YAGNI原則(Kent Beck)に反する - -## コメント記述ルール -- **機能説明重視**: コードが「何をするか」を記述 -- **履歴情報禁止**: 開発履歴は記載しない -- **タイムレス**: いつ読んでも有効な内容のみ記述 -- **簡潔性**: 必要最小限の説明にとどめる - -## 型安全性 - -**絶対ルール**: any型は完全禁止。型チェックが無効化され、実行時エラーの温床となる。 - -**any型の代替手段(優先順位順)** -1. **unknown型 + 型ガード**: 外部入力の検証に使用 -2. **ジェネリクス**: 型の柔軟性が必要な場合 -3. **ユニオン型・インターセクション型**: 複数の型の組み合わせ -4. **型アサーション(最終手段)**: 型が確実な場合のみ - -**型ガードの実装パターン** -```typescript -function isUser(value: unknown): value is User { - return typeof value === 'object' && value !== null && 'id' in value && 'name' in value -} -``` - -**モダンな型機能の活用** -- **satisfies演算子**: `const config = { port: 3000 } satisfies Config` - 型推論維持 -- **const assertion**: `const ROUTES = { HOME: '/' } as const satisfies Routes` - 不変かつ型安全 -- **ブランド型**: `type UserId = string & { __brand: 'UserId' }` - 意味を区別 -- **テンプレートリテラル型**: `type Endpoint = \`\${HttpMethod} \${Route}\`` - 文字列パターンを型で表現 - -**実装での型安全性** -- API通信: レスポンスは必ず`unknown`で受け、型ガードで検証 -- フォーム入力: 外部入力は`unknown`、バリデーション後に型確定 -- レガシー統合: `window as unknown as LegacyWindow`のように段階的アサーション -- テストコード: モックも必ず型定義、`Partial`や`vi.fn<[Args], Return>()`活用 +## Backend実装における型安全性 **データフローでの型安全性** 入力層(`unknown`) → 型ガード → ビジネス層(型保証) → 出力層(シリアライズ) -**型の複雑性管理** -- フィールド数: 20個まで(超えたら責務で分割、外部API型は例外) -- オプショナル率: 30%まで(超えたら必須/任意で分離) -- ネスト深さ: 3階層まで(超えたらフラット化) -- 型アサーション: 3回以上使用したら設計見直し -- **外部API型の扱い**: 制約を緩和し、実態に合わせて定義(内部では適切に変換) +**Backend固有の型シナリオ**: +- **API通信**: レスポンスは必ず`unknown`で受け、型ガードで検証 +- **フォーム入力**: 外部入力は`unknown`、バリデーション後に型確定 +- **レガシー統合**: `window as unknown as LegacyWindow`のように段階的アサーション +- **テストコード**: モックも必ず型定義、`Partial`や`vi.fn<[Args], Return>()`活用 ## コーディング規約 @@ -149,17 +110,6 @@ export class AppError extends Error { - すべてのasync/awaitでtry-catch使用 - エラーは必ずログと再スロー -## リファクタリング手法 - -**基本方針** -- 小さなステップ: 段階的改善により、常に動作する状態を維持 -- 安全な変更: 一度に変更する範囲を最小限に抑制 -- 動作保証: 既存の動作を変えないことを確認しながら進める - -**実施手順**: 現状把握 → 段階的変更 → 動作確認 → 最終検証 - -**優先順位**: 重複コード削除 > 長大な関数分割 > 複雑な条件分岐簡素化 > 型安全性向上 - ## パフォーマンス最適化 - ストリーミング処理: 大きなデータセットはストリームで処理