Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 17 additions & 103 deletions .agents/skills/ai-development-guide/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: ai-development-guide
description: "Anti-pattern detection, debugging techniques, quality check workflow, and implementation completeness assurance. Use when: fixing bugs, reviewing code quality, refactoring, making technical decisions, or performing quality assurance."
description: "Anti-pattern detection, root-cause discipline, quality check workflow, and implementation completeness assurance. Use when: fixing bugs, reviewing code quality, refactoring, making technical decisions, or performing quality assurance."
---

# AI Developer Guide - Technical Decision Criteria and Anti-pattern Collection
Expand All @@ -24,7 +24,7 @@ Explore broadly, then converge on the lowest-lifecycle-cost solution that delive
### Code Quality Anti-patterns
1. **Writing similar code 3 or more times** - Violates Rule of Three
2. **Multiple responsibilities mixed in a single file** - Violates Single Responsibility Principle (SRP)
3. **Defining same content in multiple files** - Violates DRY principle
3. **Maintaining the same runtime rule or data in multiple implementation sources when one source can safely serve all consumers** - Creates synchronization risk
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
Expand Down Expand Up @@ -76,19 +76,6 @@ Make errors explicit with full context. Prioritize primary code reliability over

**ENFORCEMENT**: Fallbacks without Design Doc approval are PROHIBITED

### Implementation Pattern

```
AVOID: Silent fallback that hides errors
<handle error>:
return DEFAULT_VALUE // Error hidden, debugging impossible

PREFERRED: Explicit failure with context
<handle error>:
log_error('Operation failed', context, error)
<propagate error> // Re-throw, return Error type, return error tuple
```

## Rule of Three - Criteria for Code Duplication

How to handle duplicate code based on Martin Fowler's "Refactoring":
Expand All @@ -113,78 +100,15 @@ How to handle duplicate code based on Martin Fowler's "Refactoring":
- Significant readability decrease from commonalization
- Simple helpers in test code

## 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: Circumventing Correctness Guarantees
**Symptom**: Bypassing safety mechanisms (type systems, validation, contracts)
**Cause**: Impulse to avoid correctness errors
**Avoidance**: Use language-appropriate safety mechanisms

### 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 things work without prior investigation
**Avoidance**:
- Record certainty evaluation at the beginning of task files
- For low certainty cases, create minimal verification code first

### Pattern 5: Insufficient Existing Code Investigation
**Symptom**: Duplicate implementations, architecture inconsistency, integration failures, adopting outdated patterns
**Cause**: Insufficient understanding of existing code before implementation; referencing only nearby files without checking representativeness
**Avoidance**:
- Before implementation, always search for similar functionality
- Similar functionality found: Use that implementation (do not create new)
## Pattern 5: Existing Code Investigation [MANDATORY]

Before implementation:
- Search for similar functionality
- Similar functionality found: Verify that it satisfies the current requirement and is representative of the repository; reuse or extend it when both checks pass
- Similar functionality is technical debt: Repair it when it blocks the current outcome, was caused by the current change, or lies in confirmed scope; otherwise report it separately. When the repair requires an architectural decision, record the decision in an ADR
- No similar functionality: Implement following existing design philosophy
- No suitable similar functionality: Implement using representative repository patterns
- When adopting a pattern or dependency from nearby code, verify it is representative across the repository before adopting it

## 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

### 2. 5 Whys - Root Cause Analysis
```
Example:
Symptom: Build error
Why1: Contract definitions don't match
Why2: Interface was updated
Why3: Dependency change
Why4: Package update impact
Why5: Major version upgrade with breaking changes
Root cause: Inappropriate version specification in dependency manifest
```

### 3. Minimal Reproduction Code
To isolate problems, attempt reproduction with minimal code:
- Remove unrelated parts
- Replace external dependencies with mocks
- Create minimal configuration that reproduces problem

### 4. Debug Log Output (temporary)
Add structured debug logs to isolate the issue, then remove them before commit.

```
Pattern: Structured logging with context
{
context: 'operation-name',
input: { relevant, input, data },
state: currentState,
timestamp: current_time_ISO8601
}
```

## Quality Assurance Mechanism Awareness

Before executing quality checks, discover applicable quality tools and constraints by inspecting the affected files' types, project manifests, CI pipelines, and configuration:
Expand Down Expand Up @@ -225,21 +149,6 @@ All checks MUST pass before proceeding:

**ENFORCEMENT**: Cannot proceed with ANY quality check failures — fix ALL errors before marking task complete

## Situations Requiring Technical Decisions

### Timing of Abstraction
- Extract patterns after writing concrete implementation 3 times (Rule of Three)

### Performance vs Readability
- Prioritize readability unless clear bottleneck exists
- **Measure first** — profile before optimizing (no guessing)
- Document reason with comments when optimizing

### Granularity of Contracts and Interfaces
- Overly detailed contracts reduce maintainability
- Design interfaces that appropriately express domain
- Use abstraction mechanisms to reduce duplication

## Implementation Completeness Assurance

### Impact Analysis: Mandatory 3-Stage Process [MANDATORY]
Expand Down Expand Up @@ -286,15 +195,20 @@ Complete these stages sequentially before any implementation:
### Unused Code Deletion

When unused code is detected:
- Will it be used in this work? Yes: Implement now | No: Delete now (Git preserves)
- Within confirmed scope or dependencies required for the current outcome: Will it be used in this work? Yes: Implement now | No: Delete now (Git preserves)
- Outside that boundary: Report it separately for a scope decision
- Applies to: Code, tests, docs, configs, assets

### Existing Code Modification

```
In use? No -> Delete
Yes -> Working? No -> Delete + Reimplement
Yes -> Fix/Extend
Within confirmed scope or required dependency?
No -> Report separately
Yes -> In use?
No -> Delete
Yes -> Working?
No -> Delete + Reimplement
Yes -> Fix/Extend
```

**Principle**: Prefer clean implementation over patching broken code
50 changes: 0 additions & 50 deletions .agents/skills/ai-development-guide/references/frontend.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,6 @@ In addition to the general anti-patterns in SKILL.md, detect these frontend-spec
- Custom hooks with shared logic
- Validation rules for form inputs

**Implementation Example**:
```typescript
// Bad: Immediate commonalization on 1st duplication
function UserEmailInput() { /* ... */ }
function ContactEmailInput() { /* ... */ }

// Good: Commonalize on 3rd occurrence
function EmailInput({ context }: { context: 'user' | 'contact' | 'admin' }) { /* ... */ }
```

## Frontend Fallback Design

### Layer Responsibilities (React-specific)
Expand All @@ -38,41 +28,6 @@ function EmailInput({ context }: { context: 'user' | 'contact' | 'admin' }) { /*
- Verify Design Doc definition before implementing fallbacks
- Log errors explicitly and make failures visible

## Frontend Debugging Techniques

### Error Analysis (React-specific)
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**

### 5 Whys Example (Frontend)
```
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
```

### Minimal Reproduction (React-specific)
- Remove unrelated components
- Replace API calls with mocks
- Create minimal configuration that reproduces the problem
- Use React DevTools to inspect component tree

### Debug Log Pattern (Frontend)
```typescript
console.log('DEBUG:', {
context: 'user-form-submission',
props: { email, name },
state: currentState,
timestamp: new Date().toISOString()
})
```

## Frontend Quality Check Workflow

Read `package.json` scripts and run them with the project's package manager from the `packageManager` field. Map the phases below using the script names declared in `package.json`.
Expand All @@ -84,11 +39,6 @@ Read `package.json` scripts and run them with the project's package manager from
4. **Test** - unit and integration tests
5. **Coverage** - coverage run when configured or when the task added or changed behavior

### Troubleshooting
- **Port already in use**: stop the stale dev, preview, or test process holding the port
- **Stale cache**: re-run with the project's fresh or clean-cache option
- **Dependency errors**: clean reinstall dependencies

## Frontend Technical Decisions

### Component/Type Granularity
Expand Down
4 changes: 2 additions & 2 deletions .agents/skills/coding-rules/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ For language-specific rules, also read:

1. **Maintainability over Speed**: Prioritize long-term code health
2. **Simplicity First**: YAGNI principle — simplest solution that meets requirements
3. **Design Convergence**: Deliver the current required outcome with the least new design surface. Use "Design Surface Terms" below for classification and implementation-approach for design selection.
3. **Design Convergence**: Deliver the current required outcome with the least new design surface. Add surface only to satisfy a current requirement, verified constraint, observed problem, or evidence-backed material risk; among sufficient options, choose the lowest-lifecycle-cost option.
4. **Explicit over Implicit**: Clear intentions through code structure and naming
5. **Delete over Comment**: Remove unused code instead of commenting it out

Expand All @@ -27,7 +27,7 @@ Use these definitions when classifying Design Convergence additions or code-revi
- **Maintenance-surface-bearing elements**: persistent state; public-contract or cross-boundary fields/props; behavioral modes, flags, or variants; reusable abstractions; extracted services; shared utilities; component splits.
- **Non-surface elements**: private local variables, internal helper functions with no external observers, test fixtures or mocks, temporary migration scaffolding removed before completion, and private implementation details confined to one function or file.
- **Classification precedence**: When an element matches both surface-bearing and non-surface conditions, classify it as surface-bearing.
- **Selection rule**: Follow implementation-approach Design Convergence for design selection. These terms classify design surface; they do not define a second selection process.
- **Selection rule**: Add a surface-bearing element only when it is required by a current requirement, verified constraint, observed problem, or evidence-backed material risk. Prefer fewer new elements only when the remaining candidates are otherwise sufficient and equivalent.
- **Relation to YAGNI**: YAGNI decides present vs. future need over time; Design Convergence minimizes surface area for the current accepted scope.

## Code Quality [MANDATORY]
Expand Down
85 changes: 4 additions & 81 deletions .agents/skills/coding-rules/references/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,6 @@
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<string>}\`` - Express string patterns with types

**Type Safety in Frontend Implementation**
- **React Props/State**: TypeScript manages types, unknown unnecessary
- **External API Responses**: Always receive as `unknown`, validate with type guards
Expand All @@ -57,8 +44,8 @@ function isUser(value: unknown): value is User {
## Coding Conventions

**Component Design Criteria**
- **Function Components (Mandatory)**: Official React recommendation, optimizable by modern tooling
- **Classes Prohibited**: Class components completely deprecated (Exception: Error Boundary)
- **Function Components (Mandatory)**: Use function components for new and modified React components
- **Class Component Exception**: Retain or introduce a class component only when an existing or required Error Boundary needs it
- **Custom Hooks**: Standard pattern for logic reuse and dependency injection
- **Component Hierarchy**: Follow the project's existing component architecture. Use Atoms > Molecules > Organisms > Templates > Pages only when the project adopts Atomic Design.
- **Co-location**: Place tests, styles, and related files alongside components
Expand All @@ -79,21 +66,8 @@ function isUser(value: unknown): value is User {
- **Unidirectional Flow**: Data flows top-down via props
- **Immutable Updates**: Use immutable patterns for state updates

```typescript
// Good: Immutable state update
setUsers(prev => [...prev, newUser])

// Bad: Mutable state update
users.push(newUser)
setUsers(users)
```

**Function Design**
- **0-2 parameters maximum**: Use object for 3+ parameters
```typescript
// Object parameter
function createUser({ name, email, role }: CreateUserParams) {}
```

**Props Design (Props-driven Approach)**
- Props are the interface: Define all necessary information as props
Expand All @@ -103,33 +77,15 @@ setUsers(users)
**Environment Variables**
- **Use the build tool's env accessor**: read client-side env through the bundler's exposed accessor, such as Vite `import.meta.env` or Next.js/CRA prefixed `process.env`.
- **Only prefixed vars reach the client**: build tools expose only vars carrying their public prefix. Match the project's bundler, such as Vite `VITE_`, Next.js `NEXT_PUBLIC_`, or CRA `REACT_APP_`.
- Centrally manage environment variables through a typed configuration layer with defaults.

```typescript
// Client-exposed env must carry the bundler's public prefix, or it is undefined in the browser.
// Vite: import.meta.env.VITE_API_URL
// Next.js: process.env.NEXT_PUBLIC_API_URL
const config = {
apiUrl: import.meta.env.VITE_API_URL || 'http://localhost:3000',
appName: import.meta.env.VITE_APP_NAME || 'My App'
}
```
- Centrally manage environment variables through a typed configuration layer.
- Treat a missing required variable as a configuration error. Use a default only when requirements or a Design Doc explicitly define that fallback.

**Security (Client-side Constraints)**
- **CRITICAL**: All frontend code is public and visible in browser
- **Never store secrets client-side**: No API keys, tokens, or secrets in environment variables
- Do not include `.env` files in Git
- Do not include sensitive information in error messages

```typescript
// Bad: API key exposed in browser
// const apiKey = import.meta.env.VITE_API_KEY
// const response = await fetch(`https://api.example.com/data?key=${apiKey}`)

// Good: Backend manages secrets, frontend accesses via proxy
const response = await fetch('/api/data') // Backend handles API key authentication
```

**Dependency Injection**
- **Custom Hooks for dependency injection**: Ensure testability and modularity

Expand All @@ -155,39 +111,6 @@ const response = await fetch('/api/data') // Backend handles API key authenticat
**Absolute Rule**: Handle every error explicitly with log output, recovery logic, or escalation appropriate to the failure mode.

**Fail-Fast Principle**: Fail quickly on errors to prevent continued processing in invalid states
```typescript
// Bad: Unconditional fallback
catch (error) {
return defaultValue // Hides error
}

// Good: Explicit failure
catch (error) {
logger.error('Processing failed', error)
throw error // Handle with Error Boundary or higher layer
}
```

**Result Type Pattern**: Express errors with types for explicit handling
```typescript
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }

function parseUser(data: unknown): Result<User, ValidationError> {
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 {
constructor(message: string, public readonly code: string, public readonly statusCode = 500) {
super(message)
this.name = this.constructor.name
}
}
// Purpose-specific: ValidationError(400), ApiError(502), NotFoundError(404)
```

**Layer-Specific Error Handling (React)**
- Error Boundary: Catch React component errors, display fallback UI
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ For serialized boundaries -- a value encoded on one side and parsed on the other

## Verification Strategy

Define correctness and how to prove it at design time. L1/L2/L3 from implementation-approach define task-level verification depth.
Define correctness and how to prove it at design time. Use task-level verification depth matching the exercised boundary: L1 for unit or local in-process behavior, L2 for interaction across a named component, persistence, process, or contract boundary, and L3 for a complete user, browser, process, or service journey.
Use the minimal form only for low-risk changes (1-2 files, no external contract/integration/data-flow change) or self-evident internal refactors with identical observable inputs/outputs.

### Correctness Proof Method
Expand Down
Loading