+ );
+}
+```
+
+**Benefits:**
+- One feature failing doesn't crash the page
+- Errors are attributed to specific features
+- Users can continue using working features
+
+Reference: [React Error Boundaries](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
diff --git a/.agents/skills/feature-arch/references/fcomp-props-as-data-boundary.md b/.agents/skills/feature-arch/references/fcomp-props-as-data-boundary.md
new file mode 100644
index 0000000..5f38bc1
--- /dev/null
+++ b/.agents/skills/feature-arch/references/fcomp-props-as-data-boundary.md
@@ -0,0 +1,88 @@
+---
+title: Use Props as Feature Boundaries
+impact: MEDIUM-HIGH
+impactDescription: Creates clear interfaces between features; enables feature composition
+tags: comp, props, interface, boundary
+---
+
+## Use Props as Feature Boundaries
+
+When features interact, use props to define the interface. The receiving component should not know about the providing feature's internals. This creates a clear boundary that allows either side to change independently.
+
+**Incorrect (feature internals exposed):**
+
+```typescript
+// Checkout component knows about Cart's internal structure
+import { useCartStore } from '@/features/cart/stores/cartStore';
+
+function CheckoutSummary() {
+ // Directly accessing cart's internal state structure
+ const items = useCartStore(s => s.items);
+ const appliedCoupons = useCartStore(s => s.coupons);
+ const shippingMethod = useCartStore(s => s.shipping.method);
+
+ // If cart store changes structure, this breaks
+ return
...
;
+}
+```
+
+**Correct (props as boundary):**
+
+```typescript
+// Define explicit interface for what checkout needs
+interface CheckoutSummaryProps {
+ items: Array<{
+ id: string;
+ name: string;
+ price: number;
+ quantity: number;
+ }>;
+ subtotal: number;
+ discount: number;
+ shipping: number;
+ total: number;
+}
+
+function CheckoutSummary({ items, subtotal, discount, shipping, total }: CheckoutSummaryProps) {
+ // Component only knows about its props, not cart internals
+ return (
+
+ );
+}
+
+// src/app/pages/CheckoutPage.tsx
+import { CheckoutSummary } from '@/features/checkout';
+import { ProductCard } from '@/features/product';
+import { UserAddress } from '@/features/user';
+import { useCart } from '@/features/cart';
+
+export function CheckoutPage() {
+ const cart = useCart();
+ return (
+ }
+ addressSection={}
+ />
+ );
+}
+```
+
+**ESLint enforcement per feature:**
+
+```javascript
+// .eslintrc.js
+rules: {
+ 'import/no-restricted-paths': ['error', {
+ zones: [
+ { target: './src/features/checkout', from: './src/features/product' },
+ { target: './src/features/checkout', from: './src/features/cart' },
+ { target: './src/features/checkout', from: './src/features/user' },
+ // Add for each feature combination
+ ],
+ }],
+}
+```
+
+Reference: [Robin Wieruch - React Feature Architecture](https://www.robinwieruch.de/react-feature-architecture/)
diff --git a/.agents/skills/feature-arch/references/import-path-aliases.md b/.agents/skills/feature-arch/references/import-path-aliases.md
new file mode 100644
index 0000000..3711c99
--- /dev/null
+++ b/.agents/skills/feature-arch/references/import-path-aliases.md
@@ -0,0 +1,64 @@
+---
+title: Use Consistent Path Aliases
+impact: HIGH
+impactDescription: Eliminates ../../../ chains; makes imports self-documenting
+tags: import, aliases, paths, navigation
+---
+
+## Use Consistent Path Aliases
+
+Configure path aliases to avoid relative import chains. Aliases make imports self-documenting by showing feature ownership clearly and survive file relocations within the same feature.
+
+**Incorrect (deep relative paths):**
+
+```typescript
+// src/features/checkout/components/PaymentForm.tsx
+import { Button } from '../../../shared/components/Button';
+import { useAuth } from '../../../features/auth/hooks/useAuth'; // Also wrong: cross-feature
+import { formatCurrency } from '../../../shared/utils/formatCurrency';
+import { useCheckout } from '../hooks/useCheckout';
+```
+
+**Correct (path aliases):**
+
+```typescript
+// src/features/checkout/components/PaymentForm.tsx
+import { Button } from '@/shared/components/Button';
+import { formatCurrency } from '@/shared/utils/formatCurrency';
+import { useCheckout } from '../hooks/useCheckout'; // Same feature = relative OK
+```
+
+**tsconfig.json:**
+
+```json
+{
+ "compilerOptions": {
+ "paths": {
+ "@/*": ["./src/*"],
+ "@/shared/*": ["./src/shared/*"],
+ "@/features/*": ["./src/features/*"],
+ "@/app/*": ["./src/app/*"]
+ }
+ }
+}
+```
+
+**Guidelines:**
+- Use `@/` prefix for absolute imports from src
+- Use relative imports (`./`, `../`) within the same feature
+- Relative imports within a feature make the feature more portable
+
+**Vite configuration:**
+
+```typescript
+// vite.config.ts
+export default defineConfig({
+ resolve: {
+ alias: {
+ '@': path.resolve(__dirname, './src'),
+ },
+ },
+});
+```
+
+Reference: [Robin Wieruch - React Folder Structure](https://www.robinwieruch.de/react-folder-structure/)
diff --git a/.agents/skills/feature-arch/references/import-public-api.md b/.agents/skills/feature-arch/references/import-public-api.md
new file mode 100644
index 0000000..766d3e9
--- /dev/null
+++ b/.agents/skills/feature-arch/references/import-public-api.md
@@ -0,0 +1,67 @@
+---
+title: Export Through Public API Only
+impact: CRITICAL
+impactDescription: Prevents deep imports; enables internal refactoring without breaking consumers
+tags: import, public-api, encapsulation, index
+---
+
+## Export Through Public API Only
+
+Each feature should have a single entry point (index.ts) that exports its public API. External code should never import internal files directly. This allows internal restructuring without affecting consumers.
+
+**Incorrect (deep imports into feature internals):**
+
+```typescript
+// src/app/pages/UserPage.tsx
+import { UserProfile } from '@/features/user/components/UserProfile';
+import { useUser } from '@/features/user/hooks/useUser';
+import { formatUserName } from '@/features/user/utils/formatters';
+import { User } from '@/features/user/types/user';
+```
+
+**Correct (import from public API):**
+
+```typescript
+// src/features/user/index.ts (public API)
+export { UserProfile } from './components/UserProfile';
+export { UserSettings } from './components/UserSettings';
+export { useUser } from './hooks/useUser';
+export type { User, UserRole } from './types';
+// Note: formatUserName is NOT exported - it's internal
+
+// src/app/pages/UserPage.tsx
+import { UserProfile, useUser } from '@/features/user';
+import type { User } from '@/features/user';
+```
+
+**Internal file can import freely:**
+
+```typescript
+// src/features/user/components/UserProfile.tsx
+import { useUser } from '../hooks/useUser';
+import { formatUserName } from '../utils/formatters'; // Internal util
+import type { User } from '../types';
+```
+
+**ESLint enforcement:**
+
+```javascript
+// .eslintrc.js
+rules: {
+ 'no-restricted-imports': ['error', {
+ patterns: [
+ {
+ group: ['@/features/*/components/*', '@/features/*/hooks/*', '@/features/*/utils/*'],
+ message: 'Import from feature index.ts instead',
+ },
+ ],
+ }],
+}
+```
+
+**Benefits:**
+- Refactor internal structure without breaking external imports
+- Clear contract of what a feature provides
+- Smaller, focused public surface area
+
+Reference: [Feature-Sliced Design](https://feature-sliced.design/)
diff --git a/.agents/skills/feature-arch/references/import-type-only.md b/.agents/skills/feature-arch/references/import-type-only.md
new file mode 100644
index 0000000..2fed447
--- /dev/null
+++ b/.agents/skills/feature-arch/references/import-type-only.md
@@ -0,0 +1,81 @@
+---
+title: Use Type-Only Imports for Types
+impact: MEDIUM
+impactDescription: Enables cross-feature type sharing without runtime coupling
+tags: import, types, typescript, type-only
+---
+
+## Use Type-Only Imports for Types
+
+Use `import type` syntax when importing only TypeScript types. This ensures types are stripped at compile time and allows sharing types across features without creating runtime dependencies.
+
+**Incorrect (mixing type and value imports):**
+
+```typescript
+// src/features/checkout/components/CheckoutForm.tsx
+import { User, useUser } from '@/features/user'; // Creates runtime dependency for type
+
+export function CheckoutForm({ userId }: { userId: string }) {
+ // We only need the User type, not useUser
+ const [user, setUser] = useState(null);
+}
+```
+
+**Correct (separate type imports):**
+
+```typescript
+// src/features/checkout/components/CheckoutForm.tsx
+import type { User } from '@/features/user'; // Type-only, no runtime dependency
+
+export function CheckoutForm({ userId }: { userId: string }) {
+ const [user, setUser] = useState(null);
+}
+```
+
+**Shared types for cross-feature contracts:**
+
+```typescript
+// src/shared/types/entities.ts
+export interface User {
+ id: string;
+ email: string;
+ name: string;
+}
+
+export interface Product {
+ id: string;
+ name: string;
+ price: number;
+}
+
+// Features import shared types
+// src/features/checkout/types.ts
+import type { User, Product } from '@/shared/types/entities';
+
+export interface CheckoutItem {
+ product: Product;
+ quantity: number;
+}
+
+export interface CheckoutSession {
+ user: User;
+ items: CheckoutItem[];
+}
+```
+
+**Benefits:**
+- No runtime bundle impact for type-only imports
+- Clear distinction between runtime and compile-time dependencies
+- Enables type sharing without architectural coupling
+
+**TypeScript configuration:**
+
+```json
+{
+ "compilerOptions": {
+ "verbatimModuleSyntax": true // Enforces type-only imports
+ }
+}
+```
+
+Reference: [TypeScript Handbook - Type-Only Imports](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export)
diff --git a/.agents/skills/feature-arch/references/import-unidirectional-flow.md b/.agents/skills/feature-arch/references/import-unidirectional-flow.md
new file mode 100644
index 0000000..e3fb5ef
--- /dev/null
+++ b/.agents/skills/feature-arch/references/import-unidirectional-flow.md
@@ -0,0 +1,82 @@
+---
+title: Enforce Unidirectional Import Flow
+impact: CRITICAL
+impactDescription: Prevents circular dependencies; enables deterministic build order
+tags: import, unidirectional, dependencies, architecture
+---
+
+## Enforce Unidirectional Import Flow
+
+Imports must flow in one direction: `shared → features → app`. Features can import from shared, and app can import from both, but never the reverse. This prevents circular dependencies that cause build failures and makes the dependency graph predictable.
+
+**Incorrect (bidirectional imports):**
+
+```typescript
+// src/shared/utils/analytics.ts
+import { useAuth } from '@/features/auth/hooks/useAuth'; // WRONG: shared → features
+
+export function trackEvent(event: string) {
+ const { user } = useAuth();
+ // ...
+}
+```
+
+```typescript
+// src/features/user/components/UserProfile.tsx
+import { AppLayout } from '@/app/layouts/AppLayout'; // WRONG: features → app
+
+export function UserProfile() {
+ return ...;
+}
+```
+
+**Correct (unidirectional flow):**
+
+```typescript
+// Dependency flow: shared → features → app
+
+// src/shared/utils/analytics.ts
+export function trackEvent(event: string, userId?: string) {
+ // No feature imports - userId passed as parameter
+}
+
+// src/features/user/components/UserProfile.tsx
+import { formatDate } from '@/shared/utils/formatDate'; // OK: shared used by feature
+import { trackEvent } from '@/shared/utils/analytics';
+
+export function UserProfile({ user }) {
+ useEffect(() => {
+ trackEvent('profile_view', user.id);
+ }, []);
+ return
...
;
+}
+
+// src/app/pages/UserPage.tsx
+import { UserProfile } from '@/features/user'; // OK: app uses features
+import { AppLayout } from '@/app/layouts/AppLayout';
+
+export function UserPage() {
+ return (
+
+
+
+ );
+}
+```
+
+**ESLint enforcement:**
+
+```javascript
+// .eslintrc.js
+rules: {
+ 'import/no-restricted-paths': ['error', {
+ zones: [
+ { target: './src/shared', from: './src/features' },
+ { target: './src/shared', from: './src/app' },
+ { target: './src/features', from: './src/app' },
+ ],
+ }],
+}
+```
+
+Reference: [Bulletproof React - Project Structure](https://github.com/alan2207/bulletproof-react/blob/master/docs/project-structure.md)
diff --git a/.agents/skills/feature-arch/references/name-descriptive-exports.md b/.agents/skills/feature-arch/references/name-descriptive-exports.md
new file mode 100644
index 0000000..11e0aea
--- /dev/null
+++ b/.agents/skills/feature-arch/references/name-descriptive-exports.md
@@ -0,0 +1,65 @@
+---
+title: Use Descriptive Export Names
+impact: LOW
+impactDescription: Enables IDE autocomplete; makes imports self-documenting
+tags: name, exports, descriptive, clarity
+---
+
+## Use Descriptive Export Names
+
+Export names should be descriptive and unique across the codebase. Generic names like `Card`, `List`, or `Button` cause confusion when multiple features export similar components.
+
+**Incorrect (generic export names):**
+
+```typescript
+// src/features/user/components/Card.tsx
+export function Card({ user }) { ... } // Which card?
+
+// src/features/product/components/Card.tsx
+export function Card({ product }) { ... } // Collision!
+
+// Import confusion
+import { Card } from '@/features/user'; // UserCard? ProductCard?
+import { Card as ProductCard } from '@/features/product'; // Requires alias
+```
+
+**Correct (descriptive export names):**
+
+```typescript
+// src/features/user/components/UserCard.tsx
+export function UserCard({ user }: { user: User }) { ... }
+
+// src/features/product/components/ProductCard.tsx
+export function ProductCard({ product }: { product: Product }) { ... }
+
+// Clear imports
+import { UserCard } from '@/features/user';
+import { ProductCard } from '@/features/product';
+```
+
+**Naming patterns:**
+
+| Type | Pattern | Example |
+|------|---------|---------|
+| Feature component | `{Feature}{Component}` | `UserProfile`, `CartSummary` |
+| Feature hook | `use{Feature}{Action}` | `useUserAuth`, `useCartItems` |
+| Feature API | `{action}{Feature}` | `getUser`, `updateCart` |
+| Feature store | `use{Feature}Store` | `useCartStore`, `useUserStore` |
+
+**Exception for shared components:**
+
+```typescript
+// Shared components can use generic names - they're not feature-specific
+// src/shared/components/Button.tsx
+export function Button({ children, ...props }) { ... }
+
+// src/shared/components/Card.tsx
+export function Card({ children, ...props }) { ... }
+```
+
+**Benefits:**
+- IDE autocomplete shows meaningful options
+- Imports are self-documenting
+- No aliasing required
+
+Reference: [React Naming Conventions](https://react.dev/learn/thinking-in-react)
diff --git a/.agents/skills/feature-arch/references/name-feature-naming.md b/.agents/skills/feature-arch/references/name-feature-naming.md
new file mode 100644
index 0000000..dfcb6ce
--- /dev/null
+++ b/.agents/skills/feature-arch/references/name-feature-naming.md
@@ -0,0 +1,60 @@
+---
+title: Use Domain-Driven Feature Names
+impact: LOW
+impactDescription: Improves discoverability; aligns code with business terminology
+tags: name, features, domain, naming
+---
+
+## Use Domain-Driven Feature Names
+
+Name features after business domains, not technical implementations. This makes the codebase navigable for non-developers and ensures feature boundaries align with business boundaries.
+
+**Incorrect (technical naming):**
+
+```text
+src/features/
+├── data-grid/ # What data? What domain?
+├── form-handler/ # What form? What entity?
+├── api-client/ # Generic technical concern
+├── modal-manager/ # UI pattern, not domain
+└── list-view/ # Generic view pattern
+```
+
+**Correct (domain naming):**
+
+```text
+src/features/
+├── user/ # User management domain
+├── product/ # Product catalog domain
+├── cart/ # Shopping cart domain
+├── checkout/ # Checkout/payment domain
+├── order/ # Order management domain
+├── notification/ # Notification domain
+└── search/ # Search domain
+```
+
+**Naming guidelines:**
+
+| Domain | Good Name | Bad Name |
+|--------|-----------|----------|
+| User management | `user`, `account` | `profile-component` |
+| Product catalog | `product`, `catalog` | `item-list` |
+| Shopping | `cart`, `checkout` | `purchase-flow` |
+| Authentication | `auth` | `login-system` |
+
+**Sub-features:**
+
+```text
+src/features/
+├── user/
+│ ├── ... # Core user feature
+├── user-preferences/ # Distinct sub-domain
+└── user-notifications/ # Another sub-domain
+```
+
+**Ask these questions:**
+- Would a product manager understand this name?
+- Does this map to a business capability?
+- Would this name make sense in a requirements document?
+
+Reference: [Bounded Context - Martin Fowler](https://martinfowler.com/bliki/BoundedContext.html)
diff --git a/.agents/skills/feature-arch/references/name-file-conventions.md b/.agents/skills/feature-arch/references/name-file-conventions.md
new file mode 100644
index 0000000..9325e0b
--- /dev/null
+++ b/.agents/skills/feature-arch/references/name-file-conventions.md
@@ -0,0 +1,79 @@
+---
+title: Use Consistent File Naming Conventions
+impact: LOW
+impactDescription: Enables pattern-based tooling; reduces cognitive load
+tags: name, files, conventions, consistency
+---
+
+## Use Consistent File Naming Conventions
+
+Establish and follow consistent file naming patterns. This enables automated tooling, makes files predictable, and reduces decision fatigue.
+
+**Incorrect (inconsistent naming):**
+
+```
+src/features/user/
+├── components/
+│ ├── UserProfile.tsx # PascalCase
+│ ├── user-avatar.tsx # kebab-case
+│ ├── userBadge.tsx # camelCase
+│ └── User_Settings.tsx # Snake_Case
+├── hooks/
+│ ├── useUser.ts # camelCase
+│ └── use-auth.ts # kebab-case
+└── api/
+ ├── getUser.ts # camelCase
+ └── user-api.ts # kebab-case
+```
+
+**Correct (consistent conventions):**
+
+```
+src/features/user/
+├── components/
+│ ├── UserProfile.tsx # PascalCase for components
+│ ├── UserAvatar.tsx
+│ ├── UserBadge.tsx
+│ └── UserSettings.tsx
+├── hooks/
+│ ├── useUser.ts # camelCase with use prefix
+│ └── useUserAuth.ts
+├── api/
+│ ├── get-user.ts # kebab-case for non-components
+│ ├── update-user.ts
+│ └── delete-user.ts
+├── stores/
+│ └── user-store.ts # kebab-case
+├── types/
+│ └── index.ts
+└── utils/
+ └── format-user-name.ts # kebab-case
+```
+
+**Recommended conventions:**
+
+| File Type | Convention | Example |
+|-----------|------------|---------|
+| React components | PascalCase | `UserProfile.tsx` |
+| Hooks | camelCase with use prefix | `useUser.ts` |
+| API functions | kebab-case | `get-user.ts` |
+| Stores | kebab-case | `user-store.ts` |
+| Utilities | kebab-case | `format-date.ts` |
+| Types | index.ts or kebab-case | `types/index.ts` |
+| Tests | match source + .test | `UserProfile.test.tsx` |
+
+**ESLint enforcement:**
+
+```javascript
+// .eslintrc.js
+rules: {
+ 'unicorn/filename-case': ['error', {
+ cases: {
+ pascalCase: true, // For .tsx files
+ kebabCase: true, // For .ts files
+ },
+ }],
+}
+```
+
+Reference: [Airbnb React Style Guide](https://github.com/airbnb/javascript/tree/master/react)
diff --git a/.agents/skills/feature-arch/references/struct-app-layer.md b/.agents/skills/feature-arch/references/struct-app-layer.md
new file mode 100644
index 0000000..564304e
--- /dev/null
+++ b/.agents/skills/feature-arch/references/struct-app-layer.md
@@ -0,0 +1,73 @@
+---
+title: Separate App Layer from Features
+impact: HIGH
+impactDescription: Isolates global concerns; enables feature modules to remain pure
+tags: struct, app-layer, providers, routing
+---
+
+## Separate App Layer from Features
+
+The app layer handles global concerns: routing, providers, initialization, and global layouts. Features should not contain routing logic or provider setup. This separation allows features to be portable and testable in isolation.
+
+**Incorrect (routing and providers mixed with features):**
+
+```
+src/features/user/
+├── components/
+│ └── UserProfile.tsx
+├── UserRoutes.tsx # Routing logic in feature
+└── UserProvider.tsx # Provider in feature
+```
+
+```typescript
+// src/features/user/UserRoutes.tsx
+import { Routes, Route } from 'react-router-dom';
+
+export function UserRoutes() {
+ return (
+
+ } />
+ } />
+
+ );
+}
+```
+
+**Correct (app layer owns routing and providers):**
+
+```
+src/
+├── app/
+│ ├── providers/
+│ │ ├── AuthProvider.tsx
+│ │ ├── QueryProvider.tsx
+│ │ └── index.tsx
+│ ├── routes/
+│ │ ├── index.tsx
+│ │ └── protected-routes.tsx
+│ └── App.tsx
+└── features/
+ └── user/
+ ├── components/
+ │ ├── UserProfile.tsx
+ │ └── UserSettings.tsx
+ └── index.ts
+```
+
+```typescript
+// src/app/routes/index.tsx
+import { UserProfile, UserSettings } from '@/features/user';
+
+export const routes = [
+ { path: '/profile', element: },
+ { path: '/settings', element: },
+];
+```
+
+**App layer responsibilities:**
+- Route definitions and navigation
+- Provider composition (Auth, Query, Theme)
+- Global error boundaries
+- Application initialization
+
+Reference: [Feature-Sliced Design](https://feature-sliced.design/)
diff --git a/.agents/skills/feature-arch/references/struct-feature-folders.md b/.agents/skills/feature-arch/references/struct-feature-folders.md
new file mode 100644
index 0000000..8740ce2
--- /dev/null
+++ b/.agents/skills/feature-arch/references/struct-feature-folders.md
@@ -0,0 +1,70 @@
+---
+title: Organize by Feature, Not Technical Type
+impact: CRITICAL
+impactDescription: Eliminates cross-file navigation; reduces onboarding time by 50%+
+tags: struct, organization, feature-folders, scalability
+---
+
+## Organize by Feature, Not Technical Type
+
+Technical grouping (components/, hooks/, utils/) forces developers to navigate multiple directories for single features. Feature-based organization colocates all related code, making features self-documenting and independently deployable.
+
+**Incorrect (technical grouping):**
+
+```
+src/
+├── components/
+│ ├── PostCard.tsx
+│ ├── CommentList.tsx
+│ └── UserAvatar.tsx
+├── hooks/
+│ ├── usePost.ts
+│ ├── useComments.ts
+│ └── useUser.ts
+├── api/
+│ ├── posts.ts
+│ ├── comments.ts
+│ └── users.ts
+└── utils/
+ ├── postHelpers.ts
+ └── commentHelpers.ts
+```
+
+**Correct (feature-based grouping):**
+
+```
+src/
+├── features/
+│ ├── post/
+│ │ ├── components/
+│ │ │ └── PostCard.tsx
+│ │ ├── hooks/
+│ │ │ └── usePost.ts
+│ │ ├── api/
+│ │ │ └── get-post.ts
+│ │ └── utils/
+│ │ └── postHelpers.ts
+│ ├── comment/
+│ │ ├── components/
+│ │ │ └── CommentList.tsx
+│ │ ├── hooks/
+│ │ │ └── useComments.ts
+│ │ └── api/
+│ │ └── get-comments.ts
+│ └── user/
+│ ├── components/
+│ │ └── UserAvatar.tsx
+│ └── hooks/
+│ └── useUser.ts
+└── shared/
+ └── components/
+ └── Button.tsx
+```
+
+**Benefits:**
+- Adding a feature = adding one folder
+- Removing a feature = removing one folder
+- Feature ownership is immediately clear
+- Teams can work on different features without conflicts
+
+Reference: [Robin Wieruch - React Feature Architecture](https://www.robinwieruch.de/react-feature-architecture/)
diff --git a/.agents/skills/feature-arch/references/struct-feature-self-contained.md b/.agents/skills/feature-arch/references/struct-feature-self-contained.md
new file mode 100644
index 0000000..1a377b9
--- /dev/null
+++ b/.agents/skills/feature-arch/references/struct-feature-self-contained.md
@@ -0,0 +1,62 @@
+---
+title: Make Features Self-Contained
+impact: CRITICAL
+impactDescription: Enables independent deployment and parallel team development
+tags: struct, isolation, self-contained, modularity
+---
+
+## Make Features Self-Contained
+
+Each feature folder should contain everything needed to implement that feature. When a feature requires code from multiple places, it becomes entangled with other features and cannot evolve independently.
+
+**Incorrect (scattered feature code):**
+
+```typescript
+// src/components/checkout/CheckoutForm.tsx
+import { useCart } from '../../hooks/useCart';
+import { validateCard } from '../../utils/validation';
+import { CartSummary } from '../cart/CartSummary';
+import { paymentApi } from '../../api/payment';
+
+export function CheckoutForm() {
+ const cart = useCart();
+ // Feature depends on 4 different locations
+}
+```
+
+**Correct (self-contained feature):**
+
+```typescript
+// src/features/checkout/components/CheckoutForm.tsx
+import { useCart } from '../hooks/useCart';
+import { validateCard } from '../utils/validation';
+import { CartSummary } from '../components/CartSummary';
+import { submitPayment } from '../api/submit-payment';
+
+export function CheckoutForm() {
+ const cart = useCart();
+ // All imports are within the feature
+}
+```
+
+**Feature folder structure:**
+
+```
+features/checkout/
+├── api/
+│ └── submit-payment.ts
+├── components/
+│ ├── CheckoutForm.tsx
+│ └── CartSummary.tsx
+├── hooks/
+│ └── useCart.ts
+├── utils/
+│ └── validation.ts
+└── index.ts
+```
+
+**When NOT to use this pattern:**
+- Truly generic utilities (date formatting, string helpers) belong in `shared/`
+- UI primitives (Button, Input) belong in `shared/components/`
+
+Reference: [Bulletproof React - Project Structure](https://github.com/alan2207/bulletproof-react/blob/master/docs/project-structure.md)
diff --git a/.agents/skills/feature-arch/references/struct-flat-hierarchy.md b/.agents/skills/feature-arch/references/struct-flat-hierarchy.md
new file mode 100644
index 0000000..4a21b00
--- /dev/null
+++ b/.agents/skills/feature-arch/references/struct-flat-hierarchy.md
@@ -0,0 +1,58 @@
+---
+title: Keep Directory Hierarchy Flat
+impact: CRITICAL
+impactDescription: Reduces cognitive load; prevents 5+ level deep import paths
+tags: struct, nesting, hierarchy, navigation
+---
+
+## Keep Directory Hierarchy Flat
+
+Deep nesting creates long import paths, makes file relocation difficult, and obscures the overall structure. Limit nesting to 2-3 levels within features.
+
+**Incorrect (deep nesting):**
+
+```
+src/features/checkout/
+├── components/
+│ ├── form/
+│ │ ├── fields/
+│ │ │ ├── payment/
+│ │ │ │ └── CardInput.tsx
+│ │ │ └── shipping/
+│ │ │ └── AddressInput.tsx
+│ │ └── FormWrapper.tsx
+│ └── summary/
+│ └── OrderSummary.tsx
+```
+
+```typescript
+// Import path is 6 levels deep
+import { CardInput } from '../../../components/form/fields/payment/CardInput';
+```
+
+**Correct (flat hierarchy):**
+
+```
+src/features/checkout/
+├── components/
+│ ├── CardInput.tsx
+│ ├── AddressInput.tsx
+│ ├── FormWrapper.tsx
+│ └── OrderSummary.tsx
+```
+
+```typescript
+// Import path is 2 levels
+import { CardInput } from '../components/CardInput';
+```
+
+**When deeper nesting is acceptable:**
+- Feature has 20+ components (consider splitting into sub-features)
+- Clear categorical distinction (e.g., `forms/` vs `displays/`)
+
+**Guidelines:**
+- Maximum 3 levels within a feature folder
+- If you need deeper nesting, the feature is likely too large
+- Prefer flat with clear naming over deep with vague naming
+
+Reference: [Robin Wieruch - React Folder Structure](https://www.robinwieruch.de/react-folder-structure/)
diff --git a/.agents/skills/feature-arch/references/struct-optional-segments.md b/.agents/skills/feature-arch/references/struct-optional-segments.md
new file mode 100644
index 0000000..419ed23
--- /dev/null
+++ b/.agents/skills/feature-arch/references/struct-optional-segments.md
@@ -0,0 +1,72 @@
+---
+title: Include Only Necessary Segments
+impact: HIGH
+impactDescription: Prevents empty folder clutter; keeps features minimal and focused
+tags: struct, segments, minimal, pragmatic
+---
+
+## Include Only Necessary Segments
+
+Not every feature needs every segment (components/, hooks/, api/, utils/, types/). Start with only what the feature requires and add segments as complexity grows. Empty folders add noise and suggest over-engineering.
+
+**Incorrect (every segment even when unused):**
+
+```
+src/features/notification/
+├── api/ # Empty - notifications are client-side only
+├── components/
+│ └── Toast.tsx
+├── hooks/
+│ └── useNotification.ts
+├── stores/ # Empty - using context instead
+├── types/
+│ └── index.ts # Just re-exports one interface
+└── utils/ # Empty
+```
+
+**Correct (only necessary segments):**
+
+```
+src/features/notification/
+├── components/
+│ └── Toast.tsx
+├── hooks/
+│ └── useNotification.ts
+└── types.ts # Single file, not a folder with one file
+```
+
+**Another example - simple feature:**
+
+```
+src/features/theme/
+├── ThemeProvider.tsx
+├── useTheme.ts
+└── index.ts
+```
+
+**Complex feature with all segments:**
+
+```
+src/features/checkout/
+├── api/
+│ ├── submit-order.ts
+│ └── validate-address.ts
+├── components/
+│ ├── CheckoutForm.tsx
+│ ├── PaymentSection.tsx
+│ └── ShippingSection.tsx
+├── hooks/
+│ ├── useCheckout.ts
+│ └── usePaymentMethods.ts
+├── stores/
+│ └── checkout-store.ts
+├── types/
+│ └── index.ts
+├── utils/
+│ └── validation.ts
+└── index.ts
+```
+
+**Guideline:** Add segments when you have 2+ files that would go there.
+
+Reference: [Bulletproof React - Project Structure](https://github.com/alan2207/bulletproof-react/blob/master/docs/project-structure.md)
diff --git a/.agents/skills/feature-arch/references/struct-shared-layer.md b/.agents/skills/feature-arch/references/struct-shared-layer.md
new file mode 100644
index 0000000..9702454
--- /dev/null
+++ b/.agents/skills/feature-arch/references/struct-shared-layer.md
@@ -0,0 +1,68 @@
+---
+title: Use Shared Layer for Truly Generic Code Only
+impact: CRITICAL
+impactDescription: Prevents shared/ from becoming a dumping ground; maintains feature boundaries
+tags: struct, shared, reusability, generic
+---
+
+## Use Shared Layer for Truly Generic Code Only
+
+The shared layer should contain only code with high reusability and minimal business logic. When business-specific code lands in shared/, it creates hidden dependencies and prevents features from being truly independent.
+
+**Incorrect (business logic in shared):**
+
+```
+src/shared/
+├── components/
+│ ├── Button.tsx # Generic - OK
+│ ├── ProductCard.tsx # Business-specific - WRONG
+│ └── UserBadge.tsx # Business-specific - WRONG
+├── hooks/
+│ ├── useDebounce.ts # Generic - OK
+│ └── useCheckout.ts # Business-specific - WRONG
+└── utils/
+ ├── formatDate.ts # Generic - OK
+ └── calculateTax.ts # Business-specific - WRONG
+```
+
+**Correct (shared is generic only):**
+
+```
+src/shared/
+├── components/
+│ ├── Button.tsx
+│ ├── Input.tsx
+│ ├── Modal.tsx
+│ └── Tooltip.tsx
+├── hooks/
+│ ├── useDebounce.ts
+│ ├── useLocalStorage.ts
+│ └── useMediaQuery.ts
+└── utils/
+ ├── formatDate.ts
+ ├── formatCurrency.ts
+ └── cn.ts
+```
+
+```
+src/features/product/
+├── components/
+│ └── ProductCard.tsx # Business component lives with feature
+└── ...
+
+src/features/checkout/
+├── hooks/
+│ └── useCheckout.ts # Business hook lives with feature
+├── utils/
+│ └── calculateTax.ts # Business util lives with feature
+└── ...
+```
+
+**Litmus test for shared/:**
+- Would this be useful in a completely different project?
+- Does it contain zero business domain knowledge?
+- Is it used by 3+ features?
+
+If any answer is "no", it belongs in a feature folder.
+
+Reference: [Feature-Sliced Design](https://feature-sliced.design/)
diff --git a/.agents/skills/feature-arch/references/test-colocate-with-feature.md b/.agents/skills/feature-arch/references/test-colocate-with-feature.md
new file mode 100644
index 0000000..20324b2
--- /dev/null
+++ b/.agents/skills/feature-arch/references/test-colocate-with-feature.md
@@ -0,0 +1,78 @@
+---
+title: Colocate Tests with Features
+impact: MEDIUM
+impactDescription: Makes test coverage visible; ensures tests move with features
+tags: test, colocation, organization, feature
+---
+
+## Colocate Tests with Features
+
+Tests should live in the same feature folder as the code they test. When tests are in a separate tests/ folder, they become disconnected from the code, leading to missing coverage and orphaned tests.
+
+**Incorrect (centralized test folder):**
+
+```
+src/
+├── features/
+│ ├── user/
+│ │ └── components/
+│ │ └── UserProfile.tsx
+│ └── cart/
+│ └── hooks/
+│ └── useCart.ts
+└── tests/ # Disconnected from features
+ ├── user/
+ │ └── UserProfile.test.tsx
+ └── cart/
+ └── useCart.test.ts
+```
+
+**Correct (colocated tests):**
+
+```
+src/features/
+├── user/
+│ ├── components/
+│ │ ├── UserProfile.tsx
+│ │ └── __tests__/
+│ │ └── UserProfile.test.tsx
+│ └── hooks/
+│ ├── useUser.ts
+│ └── __tests__/
+│ └── useUser.test.ts
+└── cart/
+ ├── hooks/
+ │ ├── useCart.ts
+ │ └── __tests__/
+ │ └── useCart.test.ts
+ └── api/
+ ├── get-cart.ts
+ └── __tests__/
+ └── get-cart.test.ts
+```
+
+**Alternative: Adjacent files:**
+
+```
+src/features/user/components/
+├── UserProfile.tsx
+└── UserProfile.test.tsx # Same folder, no __tests__ subfolder
+```
+
+**Benefits:**
+- Moving a feature moves its tests
+- Deleting a feature deletes its tests
+- Test coverage is visible in the feature folder
+- Easy to see what's tested at a glance
+
+**vitest.config.ts:**
+
+```typescript
+export default defineConfig({
+ test: {
+ include: ['src/**/*.test.{ts,tsx}'],
+ },
+});
+```
+
+Reference: [Bulletproof React - Project Structure](https://github.com/alan2207/bulletproof-react/blob/master/docs/project-structure.md)
diff --git a/.agents/skills/feature-arch/references/test-feature-isolation.md b/.agents/skills/feature-arch/references/test-feature-isolation.md
new file mode 100644
index 0000000..7915afb
--- /dev/null
+++ b/.agents/skills/feature-arch/references/test-feature-isolation.md
@@ -0,0 +1,88 @@
+---
+title: Test Features in Isolation
+impact: MEDIUM
+impactDescription: Enables faster tests; provides clear failure attribution
+tags: test, isolation, mocking, independence
+---
+
+## Test Features in Isolation
+
+Feature tests should mock cross-feature dependencies. When tests use real implementations of other features, they become slow, flaky, and failures are hard to attribute.
+
+**Incorrect (integrated feature tests):**
+
+```typescript
+// Testing checkout feature but using real cart and user features
+describe('CheckoutForm', () => {
+ it('submits order', async () => {
+ // Test depends on cart and user working correctly
+ render(
+
+
+
+
+
+
+
+ );
+
+ // If cart has a bug, checkout tests fail
+ // Slow because it's testing 3 features
+ });
+});
+```
+
+**Correct (isolated feature tests):**
+
+```typescript
+// src/features/checkout/components/__tests__/CheckoutForm.test.tsx
+describe('CheckoutForm', () => {
+ const mockItems = [
+ { id: '1', name: 'Product', price: 100, quantity: 2 },
+ ];
+
+ it('submits order with provided items', async () => {
+ const onSubmit = vi.fn();
+
+ render(
+
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: /submit/i }));
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ items: mockItems,
+ userId: 'user-123',
+ });
+ });
+
+ it('shows empty state when no items', () => {
+ render();
+
+ expect(screen.getByText(/cart is empty/i)).toBeInTheDocument();
+ });
+});
+```
+
+**Mock cross-feature hooks:**
+
+```typescript
+// Mock the cart feature's exported hook
+vi.mock('@/features/cart', () => ({
+ useCart: () => ({
+ items: [{ id: '1', name: 'Test', price: 50, quantity: 1 }],
+ total: 50,
+ }),
+}));
+```
+
+**Benefits:**
+- Fast tests (no unnecessary dependencies)
+- Clear failure attribution
+- Tests document the feature's interface
+
+Reference: [Testing Library - Guiding Principles](https://testing-library.com/docs/guiding-principles)
diff --git a/.agents/skills/feature-arch/references/test-integration-at-app-layer.md b/.agents/skills/feature-arch/references/test-integration-at-app-layer.md
new file mode 100644
index 0000000..4ed73d5
--- /dev/null
+++ b/.agents/skills/feature-arch/references/test-integration-at-app-layer.md
@@ -0,0 +1,87 @@
+---
+title: Write Integration Tests at App Layer
+impact: MEDIUM
+impactDescription: Verifies feature composition; catches integration bugs
+tags: test, integration, e2e, app-layer
+---
+
+## Write Integration Tests at App Layer
+
+While features should be tested in isolation, integration tests that verify features work together belong at the app layer. This matches the composition structure of the application.
+
+**Incorrect (integration tests inside features):**
+
+```typescript
+// src/features/checkout/__tests__/checkout-integration.test.tsx
+// WRONG: Integration test inside a feature folder
+import { CartProvider } from '@/features/cart';
+import { UserProvider } from '@/features/user';
+import { CheckoutForm } from '../components/CheckoutForm';
+
+describe('Checkout Integration', () => {
+ it('completes checkout with cart and user', async () => {
+ render(
+
+
+
+
+
+ );
+ // Feature test depends on other features
+ });
+});
+```
+
+**Correct (integration tests at app layer):**
+
+```typescript
+// src/app/__tests__/checkout-flow.test.tsx
+// Correct: Integration test at app layer where features are composed
+describe('Checkout Flow Integration', () => {
+ it('completes order from cart to confirmation', async () => {
+ render(
+
+
+
+ );
+
+ // Add product to cart (cart feature)
+ await userEvent.click(screen.getByRole('button', { name: /add to cart/i }));
+
+ // Navigate to checkout (routing)
+ await userEvent.click(screen.getByRole('link', { name: /checkout/i }));
+
+ // Fill checkout form (checkout feature)
+ await userEvent.type(screen.getByLabelText(/email/i), 'test@example.com');
+ await userEvent.click(screen.getByRole('button', { name: /place order/i }));
+
+ // Verify confirmation (order feature)
+ expect(await screen.findByText(/order confirmed/i)).toBeInTheDocument();
+ });
+});
+```
+
+**E2E tests for critical paths:**
+
+```typescript
+// e2e/checkout.spec.ts
+test('complete purchase flow', async ({ page }) => {
+ await page.goto('/products');
+ await page.click('[data-testid="add-to-cart"]');
+ await page.click('[data-testid="go-to-checkout"]');
+ await page.fill('[name="email"]', 'test@example.com');
+ await page.click('text=Place Order');
+ await expect(page.locator('text=Order Confirmed')).toBeVisible();
+});
+```
+
+**Test layer structure:**
+
+```
+tests/
+├── unit/ # Fast, isolated tests (run on every commit)
+├── integration/ # Feature composition tests (run on PR)
+└── e2e/ # Full user journeys (run before deploy)
+```
+
+Reference: [Testing Trophy - Kent C. Dodds](https://kentcdodds.com/blog/the-testing-trophy-and-testing-classifications)
diff --git a/.agents/skills/feature-arch/references/test-shared-utilities.md b/.agents/skills/feature-arch/references/test-shared-utilities.md
new file mode 100644
index 0000000..ea4d93d
--- /dev/null
+++ b/.agents/skills/feature-arch/references/test-shared-utilities.md
@@ -0,0 +1,94 @@
+---
+title: Create Feature-Specific Test Utilities
+impact: MEDIUM
+impactDescription: Reduces test boilerplate; ensures consistent test setup
+tags: test, utilities, helpers, fixtures
+---
+
+## Create Feature-Specific Test Utilities
+
+Each feature should have its own test utilities: factories, fixtures, and render wrappers. Shared test utilities become coupled to all features and are hard to maintain.
+
+**Incorrect (global test utilities):**
+
+```typescript
+// src/testing/utils.ts - One file for all features
+export function createMockUser() { ... }
+export function createMockProduct() { ... }
+export function createMockOrder() { ... }
+export function renderWithProviders(ui: ReactNode) {
+ return render(ui, {
+ wrapper: ({ children }) => (
+
+
+
+
+ {children}
+
+
+
+
+ ),
+ });
+}
+```
+
+**Correct (feature-specific utilities):**
+
+```typescript
+// src/features/user/testing/factories.ts
+export function createUser(overrides?: Partial): User {
+ return {
+ id: faker.string.uuid(),
+ email: faker.internet.email(),
+ name: faker.person.fullName(),
+ ...overrides,
+ };
+}
+
+// src/features/user/testing/render.tsx
+export function renderUserFeature(ui: ReactNode) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ return render(ui, {
+ wrapper: ({ children }) => (
+
+ {children}
+
+ ),
+ });
+}
+
+// src/features/user/testing/index.ts
+export { createUser } from './factories';
+export { renderUserFeature } from './render';
+
+// Usage in tests
+import { createUser, renderUserFeature } from '../testing';
+
+describe('UserProfile', () => {
+ it('displays user name', () => {
+ const user = createUser({ name: 'Jane Doe' });
+ renderUserFeature();
+ expect(screen.getByText('Jane Doe')).toBeInTheDocument();
+ });
+});
+```
+
+**Shared testing utilities (truly generic):**
+
+```typescript
+// src/shared/testing/query-client.ts
+export function createTestQueryClient() {
+ return new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+}
+```
+
+Reference: [Testing Library - Setup](https://testing-library.com/docs/react-testing-library/setup)
diff --git a/.agents/skills/msw/SKILL.md b/.agents/skills/msw/SKILL.md
new file mode 100644
index 0000000..9df0ca7
--- /dev/null
+++ b/.agents/skills/msw/SKILL.md
@@ -0,0 +1,121 @@
+---
+name: msw
+description: MSW 2 API mocking for tests.
+---
+
+# MSW Best Practices
+
+Comprehensive API mocking guide for MSW v2 applications (current: MSW 2.15), designed for AI agents and LLMs. Contains 48 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
+
+## When to Apply
+
+Reference these guidelines when:
+- Setting up MSW for testing or development
+- Writing or organizing request handlers
+- Configuring test environments with MSW
+- Mocking REST or GraphQL APIs
+- Debugging handler matching issues
+- Testing error states and edge cases
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Setup & Initialization | CRITICAL | `setup-` |
+| 2 | Handler Architecture | CRITICAL | `handler-` |
+| 3 | Test Integration | HIGH | `test-` |
+| 4 | Response Patterns | HIGH | `response-` |
+| 5 | Request Matching | MEDIUM-HIGH | `match-` |
+| 6 | GraphQL Mocking | MEDIUM | `graphql-` |
+| 7 | Advanced Patterns | MEDIUM | `advanced-` |
+| 8 | Debugging & Performance | LOW | `debug-` |
+
+## Quick Reference
+
+### 1. Setup & Initialization (CRITICAL)
+
+- `setup-server-node-entrypoint` - Use correct entrypoint for Node.js (msw/node)
+- `setup-lifecycle-hooks` - Configure server lifecycle in test setup
+- `setup-worker-script-commit` - Commit worker script to version control
+- `setup-node-version` - Require Node.js 18+ for MSW v2
+- `setup-unhandled-requests` - Configure unhandled request behavior
+- `setup-typescript-config` - Configure TypeScript for MSW v2
+
+### 2. Handler Architecture (CRITICAL)
+
+- `handler-happy-path-first` - Define happy path handlers as baseline
+- `handler-domain-grouping` - Group handlers by domain
+- `handler-absolute-urls` - Use absolute URLs in handlers
+- `handler-shared-resolvers` - Extract shared response logic into resolvers
+- `handler-v2-response-syntax` - Use MSW v2 response syntax
+- `handler-request-body-parsing` - Explicitly parse request bodies
+- `handler-resolver-argument` - Destructure resolver arguments correctly
+- `handler-reusability-environments` - Share handlers across environments
+
+### 3. Test Integration (HIGH)
+
+- `test-reset-handlers` - Reset handlers after each test
+- `test-avoid-request-assertions` - Avoid direct request assertions
+- `test-concurrent-boundary` - Use server.boundary() for concurrent tests
+- `test-fake-timers-config` - Configure fake timers to preserve queueMicrotask
+- `test-async-utilities` - Use async testing utilities for mock responses
+- `test-clear-request-cache` - Clear request library caches between tests
+- `test-jsdom-environment` - Use correct JSDOM environment for Jest
+
+### 4. Response Patterns (HIGH)
+
+- `response-http-response-helpers` - Use HttpResponse static methods
+- `response-delay-realistic` - Add delays only for timing behavior under test
+- `response-error-simulation` - Simulate error responses correctly
+- `response-one-time-handlers` - Use one-time handlers for sequential scenarios
+- `response-custom-headers` - Set response headers correctly
+- `response-streaming` - Mock streaming responses with ReadableStream
+
+### 5. Request Matching (MEDIUM-HIGH)
+
+- `match-url-patterns` - Use URL path parameters correctly
+- `match-query-params` - Access query parameters from request URL
+- `match-custom-predicate` - Use custom predicates for complex matching
+- `match-http-methods` - Match HTTP methods explicitly
+- `match-handler-order` - Order handlers from specific to general
+
+### 6. GraphQL Mocking (MEDIUM)
+
+- `graphql-operation-handlers` - Use operation name for GraphQL matching
+- `graphql-error-responses` - Return GraphQL errors in correct format
+- `graphql-batched-queries` - Handle batched GraphQL queries
+- `graphql-variables-access` - Access GraphQL variables correctly
+- `graphql-schema-first` - Resolve operations against a GraphQL schema
+
+### 7. Advanced Patterns (MEDIUM)
+
+- `advanced-bypass-requests` - Use bypass() for passthrough requests
+- `advanced-cookies-auth` - Handle cookies and authentication
+- `advanced-dynamic-scenarios` - Implement dynamic mock scenarios
+- `advanced-vitest-browser` - Configure MSW for Vitest browser mode
+- `advanced-file-uploads` - Mock file upload endpoints
+- `advanced-websocket-mocking` - Mock WebSocket connections with ws.link
+- `advanced-playwright-integration` - Use defineNetworkFixture from @msw/playwright
+
+### 8. Debugging & Performance (LOW)
+
+- `debug-lifecycle-events` - Use lifecycle events for debugging
+- `debug-verify-interception` - Verify request interception is working
+- `debug-common-issues` - Know common MSW issues and fixes
+- `debug-request-logging` - Log request details for debugging
+
+## How to Use
+
+Run in the project root first:
+
+```bash
+npx -y @pymodel/react-frontend-skills detect # installed vs. targeted versions
+npx -y @pymodel/react-frontend-skills scan --skill msw # deprecated APIs → rule IDs
+```
+
+Read `references/.md` for each rule above that matches the task and for each `scan` hit: why it matters, then incorrect vs. correct code.
+
+## Related Skills
+
+- For consuming mocked APIs, see `tanstack-query` skill
+- For test framework patterns, see `vitest`; for methodology, see `tdd`
diff --git a/.agents/skills/msw/references/advanced-bypass-requests.md b/.agents/skills/msw/references/advanced-bypass-requests.md
new file mode 100644
index 0000000..85c5dda
--- /dev/null
+++ b/.agents/skills/msw/references/advanced-bypass-requests.md
@@ -0,0 +1,81 @@
+---
+title: Use bypass() for Passthrough Requests
+impact: MEDIUM
+impactDescription: Enables mixing real and mocked APIs; supports hybrid testing
+tags: advanced, bypass, passthrough, real-api, proxy
+---
+
+## Use bypass() for Passthrough Requests
+
+Use `bypass()` to mark requests that should skip MSW interception and hit the real server. This enables hybrid scenarios where some APIs are mocked and others are real.
+
+**Incorrect (request creates infinite loop):**
+
+```typescript
+// Making a fetch inside a handler without bypass creates infinite recursion
+http.get('/api/user', async () => {
+ // This request is intercepted by this same handler!
+ const realResponse = await fetch('/api/user') // Infinite loop
+ return realResponse
+})
+```
+
+**Correct (bypass MSW interception):**
+
+```typescript
+import { http, HttpResponse, bypass } from 'msw'
+
+export const handlers = [
+ // Proxy to real API and modify response
+ http.get('/api/user', async ({ request }) => {
+ // bypass() marks the request to skip MSW
+ const realResponse = await fetch(bypass(request))
+ const realData = await realResponse.json()
+
+ // Augment real data with mock data
+ return HttpResponse.json({
+ ...realData,
+ mockField: 'added by MSW',
+ })
+ }),
+
+ // Conditional passthrough
+ http.get('/api/data', async ({ request }) => {
+ const url = new URL(request.url)
+
+ // Only mock in test environment
+ if (url.searchParams.get('mock') !== 'true') {
+ return fetch(bypass(request))
+ }
+
+ return HttpResponse.json({ mocked: true })
+ }),
+]
+```
+
+**Using passthrough() for unconditional passthrough:**
+
+```typescript
+import { http, passthrough } from 'msw'
+
+export const handlers = [
+ // Always pass through to real API
+ http.get('/api/analytics/*', () => {
+ return passthrough()
+ }),
+
+ // Pass through external APIs
+ http.all('https://external-service.com/*', () => {
+ return passthrough()
+ }),
+]
+```
+
+**Difference between bypass and passthrough:**
+- `bypass(request)`: Use inside a handler to make a real request
+- `passthrough()`: Return from handler to let the original request through
+
+**When NOT to use this pattern:**
+- Fully mocked environments should avoid real API calls
+
+Reference: [MSW bypass API](https://mswjs.io/docs/api/bypass)
diff --git a/.agents/skills/msw/references/advanced-cookies-auth.md b/.agents/skills/msw/references/advanced-cookies-auth.md
new file mode 100644
index 0000000..8ff09b5
--- /dev/null
+++ b/.agents/skills/msw/references/advanced-cookies-auth.md
@@ -0,0 +1,119 @@
+---
+title: Handle Cookies and Authentication
+impact: MEDIUM
+impactDescription: Enables session-based auth testing; validates auth flows
+tags: advanced, cookies, authentication, session, auth
+---
+
+## Handle Cookies and Authentication
+
+Access cookies from the `cookies` object in resolvers and set cookies via response headers. This enables testing of session-based authentication flows.
+
+**Incorrect (ignoring authentication state):**
+
+```typescript
+// Always returns user regardless of auth state
+http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+})
+```
+
+**Correct (cookie-based auth handling):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Login sets session cookie
+ http.post('/api/login', async ({ request }) => {
+ const { email, password } = await request.json()
+
+ if (email === 'john@example.com' && password === 'password') {
+ return HttpResponse.json(
+ { user: { id: '1', email } },
+ {
+ headers: {
+ 'Set-Cookie': 'session=abc123; Path=/; HttpOnly; SameSite=Strict',
+ },
+ }
+ )
+ }
+
+ return HttpResponse.json(
+ { error: 'Invalid credentials' },
+ { status: 401 }
+ )
+ }),
+
+ // Protected endpoint checks cookie
+ http.get('/api/user', ({ cookies }) => {
+ if (!cookies.session) {
+ return HttpResponse.json(
+ { error: 'Not authenticated' },
+ { status: 401 }
+ )
+ }
+
+ // In real app, validate session token
+ return HttpResponse.json({
+ id: '1',
+ name: 'John',
+ email: 'john@example.com',
+ })
+ }),
+
+ // Logout clears cookie
+ http.post('/api/logout', () => {
+ return new HttpResponse(null, {
+ status: 200,
+ headers: {
+ 'Set-Cookie': 'session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT',
+ },
+ })
+ }),
+]
+```
+
+**Bearer token authentication:**
+
+```typescript
+http.get('/api/protected', ({ request }) => {
+ const authHeader = request.headers.get('Authorization')
+
+ if (!authHeader?.startsWith('Bearer ')) {
+ return HttpResponse.json(
+ { error: 'Missing token' },
+ { status: 401 }
+ )
+ }
+
+ const token = authHeader.slice(7)
+
+ // Validate token (simplified)
+ if (token === 'valid-token') {
+ return HttpResponse.json({ data: 'protected content' })
+ }
+
+ return HttpResponse.json(
+ { error: 'Invalid token' },
+ { status: 403 }
+ )
+})
+```
+
+**Multiple cookies:**
+
+```typescript
+http.get('/api/preferences', ({ cookies }) => {
+ return HttpResponse.json({
+ theme: cookies.theme || 'light',
+ language: cookies.lang || 'en',
+ userId: cookies.session ? '1' : null,
+ })
+})
+```
+
+**When NOT to use this pattern:**
+- Public endpoints that don't require authentication
+
+Reference: [MSW Cookies](https://mswjs.io/docs/concepts/request-handler#cookies)
diff --git a/.agents/skills/msw/references/advanced-dynamic-scenarios.md b/.agents/skills/msw/references/advanced-dynamic-scenarios.md
new file mode 100644
index 0000000..ab894ed
--- /dev/null
+++ b/.agents/skills/msw/references/advanced-dynamic-scenarios.md
@@ -0,0 +1,114 @@
+---
+title: Implement Dynamic Mock Scenarios
+impact: MEDIUM
+impactDescription: Enables runtime mock state changes; supports complex test flows
+tags: advanced, dynamic, scenarios, state, runtime
+---
+
+## Implement Dynamic Mock Scenarios
+
+Use module-level state or scenario flags to switch between different mock behaviors at runtime. This enables testing different application states without restarting tests.
+
+**Incorrect (static handlers for all scenarios):**
+
+```typescript
+// Can't test different user states without test setup changes
+http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John', plan: 'free' })
+})
+```
+
+**Correct (dynamic scenario switching):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+// Scenario state
+type Scenario = 'default' | 'premium' | 'expired' | 'error'
+let currentScenario: Scenario = 'default'
+
+// Export function to change scenario
+export function setScenario(scenario: Scenario) {
+ currentScenario = scenario
+}
+
+export const handlers = [
+ http.get('/api/user', () => {
+ switch (currentScenario) {
+ case 'premium':
+ return HttpResponse.json({
+ name: 'John',
+ plan: 'premium',
+ features: ['feature1', 'feature2', 'feature3'],
+ })
+
+ case 'expired':
+ return HttpResponse.json({
+ name: 'John',
+ plan: 'expired',
+ features: [],
+ message: 'Please renew your subscription',
+ })
+
+ case 'error':
+ return HttpResponse.json(
+ { error: 'Service unavailable' },
+ { status: 503 }
+ )
+
+ default:
+ return HttpResponse.json({
+ name: 'John',
+ plan: 'free',
+ features: ['feature1'],
+ })
+ }
+ }),
+]
+```
+
+**Usage in tests:**
+
+```typescript
+import { setScenario } from '../mocks/handlers'
+
+describe('Subscription', () => {
+ afterEach(() => {
+ setScenario('default') // Reset after each test
+ })
+
+ it('shows premium features for premium users', async () => {
+ setScenario('premium')
+ render()
+ expect(await screen.findByText('Premium Features')).toBeInTheDocument()
+ })
+
+ it('shows renewal prompt for expired users', async () => {
+ setScenario('expired')
+ render()
+ expect(await screen.findByText('Please renew')).toBeInTheDocument()
+ })
+})
+```
+
+**URL-based scenarios (for development):**
+
+```typescript
+http.get('/api/user', ({ request }) => {
+ const url = new URL(request.url)
+ const scenario = url.searchParams.get('_scenario')
+
+ if (scenario === 'error') {
+ return new HttpResponse(null, { status: 500 })
+ }
+
+ return HttpResponse.json({ name: 'John' })
+})
+
+// In browser: /dashboard?_scenario=error
+```
+
+**When NOT to use this pattern:**
+- Simple tests with single states don't need scenario complexity
+
+Reference: [Dynamic Mock Scenarios](https://mswjs.io/docs/best-practices/dynamic-mock-scenarios)
diff --git a/.agents/skills/msw/references/advanced-file-uploads.md b/.agents/skills/msw/references/advanced-file-uploads.md
new file mode 100644
index 0000000..28191fe
--- /dev/null
+++ b/.agents/skills/msw/references/advanced-file-uploads.md
@@ -0,0 +1,109 @@
+---
+title: Mock File Upload Endpoints
+impact: MEDIUM
+impactDescription: Tests file upload forms and progress indicators
+tags: advanced, upload, file, formdata, multipart
+---
+
+## Mock File Upload Endpoints
+
+Parse `FormData` from requests to mock file upload endpoints. Access uploaded files and other form fields through the standard `FormData` API.
+
+**Incorrect (ignoring multipart data):**
+
+```typescript
+// Can't access uploaded file
+http.post('/api/upload', () => {
+ return HttpResponse.json({ success: true })
+})
+```
+
+**Correct (parsing FormData):**
+
+```typescript
+import { http, HttpResponse, delay } from 'msw'
+
+export const handlers = [
+ // Single file upload
+ http.post('/api/upload', async ({ request }) => {
+ const formData = await request.formData()
+ const file = formData.get('file') as File
+
+ if (!file) {
+ return HttpResponse.json(
+ { error: 'No file provided' },
+ { status: 400 }
+ )
+ }
+
+ // Simulate upload delay based on file size
+ await delay(Math.min(file.size / 1000, 2000))
+
+ return HttpResponse.json({
+ id: crypto.randomUUID(),
+ filename: file.name,
+ size: file.size,
+ mimeType: file.type,
+ url: `https://cdn.example.com/uploads/${file.name}`,
+ })
+ }),
+
+ // Multiple files
+ http.post('/api/upload-multiple', async ({ request }) => {
+ const formData = await request.formData()
+ const files = formData.getAll('files') as File[]
+
+ const results = files.map((file) => ({
+ id: crypto.randomUUID(),
+ filename: file.name,
+ size: file.size,
+ }))
+
+ return HttpResponse.json({ files: results })
+ }),
+
+ // File with additional form fields
+ http.post('/api/profile/avatar', async ({ request }) => {
+ const formData = await request.formData()
+ const avatar = formData.get('avatar') as File
+ const userId = formData.get('userId') as string
+
+ if (!avatar || !userId) {
+ return HttpResponse.json(
+ { error: 'Missing required fields' },
+ { status: 400 }
+ )
+ }
+
+ return HttpResponse.json({
+ userId,
+ avatarUrl: `https://cdn.example.com/avatars/${userId}/${avatar.name}`,
+ })
+ }),
+]
+```
+
+**Validating file types:**
+
+```typescript
+http.post('/api/upload/image', async ({ request }) => {
+ const formData = await request.formData()
+ const file = formData.get('image') as File
+
+ const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
+
+ if (!allowedTypes.includes(file.type)) {
+ return HttpResponse.json(
+ { error: 'Invalid file type. Allowed: JPEG, PNG, GIF' },
+ { status: 415 }
+ )
+ }
+
+ return HttpResponse.json({ success: true, url: '/uploaded.jpg' })
+})
+```
+
+**When NOT to use this pattern:**
+- JSON-only APIs don't need FormData parsing
+
+Reference: [MSW file uploads](https://mswjs.io/docs/http/mocking-responses/file-uploads)
diff --git a/.agents/skills/msw/references/advanced-playwright-integration.md b/.agents/skills/msw/references/advanced-playwright-integration.md
new file mode 100644
index 0000000..40a9eb1
--- /dev/null
+++ b/.agents/skills/msw/references/advanced-playwright-integration.md
@@ -0,0 +1,78 @@
+---
+title: Use defineNetworkFixture from @msw/playwright
+impact: MEDIUM
+impactDescription: controls MSW network from Playwright tests without cross-process worker hacks
+tags: msw, playwright, e2e, network, fixture
+---
+
+## Use defineNetworkFixture from @msw/playwright
+
+The official [`@msw/playwright`](https://github.com/mswjs/msw/tree/master/packages/playwright) binding lets Playwright tests use the familiar `setupWorker()` API (`use`, `resetHandlers`) directly from the Node.js test process. Without it, overriding handlers requires clunky `page.evaluate(() => window.msw.worker.use(...))` bridges because the worker lives in the browser process.
+
+**Incorrect (cross-process worker references):**
+
+```typescript
+test('shows dashboard', async ({ page }) => {
+ // Requires exposing msw on window and serializing overrides
+ // across the test<->browser process boundary
+ await page.evaluate(() => {
+ const { worker, http } = window.msw
+ worker.use(http.get('/user', () => new Response('{}')))
+ })
+ await page.goto('/dashboard')
+})
+```
+
+**Correct (network fixture in the setup file):**
+
+```typescript
+// playwright.setup.ts
+import { test as testBase } from '@playwright/test'
+import { type AnyHandler } from 'msw'
+import { defineNetworkFixture, type NetworkFixture } from '@msw/playwright'
+import { handlers } from '../mocks/handlers.js'
+
+interface Fixtures {
+ handlers: Array
+ network: NetworkFixture
+}
+
+export const test = testBase.extend({
+ // Initial list of the network handlers
+ handlers: [handlers, { option: true }],
+
+ network: [
+ async ({ context, handlers }, use) => {
+ const network = defineNetworkFixture({ context, handlers })
+ await network.enable()
+ await use(network)
+ await network.disable()
+ },
+ { auto: true },
+ ],
+})
+```
+
+**Correct (override handlers from the test itself):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+import { test } from './playwright.setup.js'
+
+test('displays the user dashboard', async ({ network, page }) => {
+ network.use(
+ http.get('/user', () =>
+ HttpResponse.json({ id: 'abc-123', firstName: 'John' }),
+ ),
+ )
+
+ await page.goto('/dashboard')
+})
+```
+
+**Notes:**
+
+- Install with `npm i msw @msw/playwright`; no worker script initialization is needed — the package provisions interception through Playwright's `page.route()` until cross-process interception ships.
+- `page.route()` limitations apply (e.g., no request bodies for some redirects); treat the transport as an implementation detail.
+- WebSocket links via `ws.link()` work, but relative WebSocket URLs resolve against the most recently created page in the context.
+- For Vitest browser mode, do not use this package — use the plain browser integration with a test-context fixture instead (see [advanced-vitest-browser](advanced-vitest-browser.md)).
diff --git a/.agents/skills/msw/references/advanced-vitest-browser.md b/.agents/skills/msw/references/advanced-vitest-browser.md
new file mode 100644
index 0000000..59442a0
--- /dev/null
+++ b/.agents/skills/msw/references/advanced-vitest-browser.md
@@ -0,0 +1,100 @@
+---
+title: Configure MSW for Vitest Browser Mode
+impact: MEDIUM
+impactDescription: Enables browser-environment testing with proper worker setup
+tags: advanced, vitest, browser, worker, testing
+---
+
+## Configure MSW for Vitest Browser Mode
+
+Extend Vitest's test context to include the MSW worker when testing in browser mode. This ensures proper worker lifecycle management per test.
+
+**Incorrect (global worker without test context):**
+
+```typescript
+// Worker state leaks between tests
+import { worker } from './mocks/browser'
+
+beforeAll(() => worker.start())
+afterAll(() => worker.stop())
+
+// Tests can't override handlers safely
+```
+
+**Correct (extended test context):**
+
+```typescript
+// test-extend.ts
+import { test as testBase } from 'vitest'
+import { worker } from './mocks/browser'
+
+export const test = testBase.extend({
+ worker: [
+ async ({}, use) => {
+ // Start worker before test
+ await worker.start({
+ onUnhandledRequest: 'error',
+ })
+
+ // Provide worker to test
+ await use(worker)
+
+ // Reset handlers after test
+ worker.resetHandlers()
+ },
+ {
+ auto: true, // Automatically available to all tests
+ },
+ ],
+})
+
+export { expect } from 'vitest'
+```
+
+```typescript
+// user.test.ts
+import { http, HttpResponse } from 'msw'
+import { test, expect } from './test-extend'
+import { Dashboard } from './components/Dashboard'
+
+test('displays user data', async ({ worker }) => {
+ // Worker is automatically started
+ render()
+ expect(await screen.findByText('John')).toBeInTheDocument()
+})
+
+test('handles error state', async ({ worker }) => {
+ // Override handlers for this test
+ worker.use(
+ http.get('/api/user', () => {
+ return new HttpResponse(null, { status: 500 })
+ })
+ )
+
+ render()
+ expect(await screen.findByText('Error loading')).toBeInTheDocument()
+})
+```
+
+**Vitest config for browser mode:**
+
+```typescript
+// vitest.config.ts
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ browser: {
+ enabled: true,
+ name: 'chromium',
+ provider: 'playwright',
+ },
+ setupFiles: ['./vitest.setup.ts'],
+ },
+})
+```
+
+**When NOT to use this pattern:**
+- Node.js tests should use `setupServer` instead
+
+Reference: [MSW Vitest Browser Mode](https://mswjs.io/docs/recipes/vitest-browser-mode)
diff --git a/.agents/skills/msw/references/advanced-websocket-mocking.md b/.agents/skills/msw/references/advanced-websocket-mocking.md
new file mode 100644
index 0000000..322fb66
--- /dev/null
+++ b/.agents/skills/msw/references/advanced-websocket-mocking.md
@@ -0,0 +1,87 @@
+---
+title: Mock WebSocket Connections with ws.link
+impact: MEDIUM
+impactDescription: tests realtime features (chat, live feeds) without a real server
+tags: msw, websocket, ws, realtime, socket.io
+---
+
+## Mock WebSocket Connections with ws.link
+
+MSW 2.x intercepts WebSocket connections with the `ws` namespace. `ws.link(url)` creates a WebSocket link handler; its `connection` event gives you the `client` and `server` connection objects to mock a realtime session.
+
+**Incorrect (mocking WebSocket with ad-hoc stubs):**
+
+```typescript
+// Replacing the global WebSocket with a hand-rolled fake
+class FakeWebSocket {
+ send = vi.fn()
+ close = vi.fn()
+ addEventListener = vi.fn()
+}
+vi.stubGlobal('WebSocket', FakeWebSocket)
+// Breaks on every real-world protocol nuance; skips MSW's
+// handler model entirely, so no shared mock scenarios
+```
+
+**Correct (use a WebSocket link handler):**
+
+```typescript
+import { ws } from 'msw'
+
+const chat = ws.link('wss://api.example.com/chat')
+
+export const handlers = [
+ chat.addEventListener('connection', ({ client, server }) => {
+ // Greet the connected client immediately
+ client.send(JSON.stringify({ type: 'welcome' }))
+
+ // Echo incoming client messages back
+ client.addEventListener('message', (event) => {
+ client.send(JSON.stringify({ type: 'ack', data: event.data }))
+ })
+ }),
+]
+```
+
+**Forward between client and actual server:**
+
+```typescript
+chat.addEventListener('connection', ({ client, server }) => {
+ server.connect()
+
+ // Pass client messages through to the real server
+ client.addEventListener('message', (event) => {
+ server.send(event.data)
+ })
+
+ // Observe server messages without changing them
+ server.addEventListener('message', (event) => {
+ client.send(event.data)
+ })
+})
+```
+
+**Mock Socket.IO with the official binding:**
+
+```typescript
+import { ws } from 'msw'
+import { toSocketIo } from '@mswjs/socket.io-binding'
+
+const chat = ws.link('wss://chat.example.com')
+
+export const handlers = [
+ chat.addEventListener('connection', (connection) => {
+ const io = toSocketIo(connection)
+
+ io.client.on('hello', (username) => {
+ io.client.emit('message', `hello, ${username}!`)
+ })
+ }),
+]
+```
+
+**Notes:**
+
+- The connection listener arguments include `client`, `server`, `params` (path parameters from the link URL), and connection `info`.
+- Call `server.connect()` only when you want to establish the actual underlying server connection; omit it for fully mocked sessions.
+- WebSocket links go in the same `handlers` array as `http`/`graphql` handlers and work in browser, Node.js, and React Native integrations.
diff --git a/.agents/skills/msw/references/debug-common-issues.md b/.agents/skills/msw/references/debug-common-issues.md
new file mode 100644
index 0000000..56c3a2a
--- /dev/null
+++ b/.agents/skills/msw/references/debug-common-issues.md
@@ -0,0 +1,79 @@
+---
+title: Know Common MSW Issues and Fixes
+impact: LOW
+impactDescription: Quick reference for frequent problems; reduces debugging time
+tags: debug, troubleshooting, issues, fixes, reference
+---
+
+## Know Common MSW Issues and Fixes
+
+Reference this checklist when MSW behaves unexpectedly. Most issues fall into a few common categories that have well-known solutions.
+
+**Incorrect (handler not matching due to relative URL):**
+
+```typescript
+// Node.js environment - handler never matches
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Relative URL doesn't match absolute request URLs
+ http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ }),
+]
+
+// When fetch('http://localhost:3000/api/user') is called,
+// the handler doesn't match because '/api/user' !== 'http://localhost:3000/api/user'
+```
+
+**Correct (handler matches with wildcard):**
+
+```typescript
+// Node.js environment - handler matches any origin
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Wildcard matches any origin prefix
+ http.get('*/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ }),
+]
+
+// Now fetch('http://localhost:3000/api/user') matches correctly
+```
+
+## Common Issues Quick Reference
+
+**Issue: "fetch is not defined"**
+- Fix: Upgrade Node.js to 18+ (native fetch support)
+
+**Issue: Body parsing hangs with fake timers**
+```typescript
+// Fix: Exclude queueMicrotask from fake timers
+vi.useFakeTimers({
+ toFake: ['setTimeout', 'setInterval', 'Date'],
+ // queueMicrotask NOT faked
+})
+```
+
+**Issue: Stale responses from cache**
+```typescript
+// Fix: Clear request library cache between tests
+afterEach(() => {
+ cache.clear() // SWR
+ queryClient.clear() // TanStack Query
+})
+```
+
+**Issue: MSW v1 code in v2 project**
+```typescript
+// v2 correct syntax:
+http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+})
+```
+
+**When NOT to use this pattern:**
+- Reference only; not all issues apply to every project
+
+Reference: [MSW Debugging Runbook](https://mswjs.io/docs/runbook/)
diff --git a/.agents/skills/msw/references/debug-lifecycle-events.md b/.agents/skills/msw/references/debug-lifecycle-events.md
new file mode 100644
index 0000000..cb4fdee
--- /dev/null
+++ b/.agents/skills/msw/references/debug-lifecycle-events.md
@@ -0,0 +1,88 @@
+---
+title: Use Lifecycle Events for Debugging
+impact: LOW
+impactDescription: Provides visibility into request interception; aids troubleshooting
+tags: debug, lifecycle, events, logging, observability
+---
+
+## Use Lifecycle Events for Debugging
+
+Subscribe to lifecycle events to observe request interception, matching, and responses. This is invaluable for debugging why handlers aren't matching or responses aren't arriving.
+
+**Incorrect (guessing why requests fail):**
+
+```typescript
+// No visibility into what MSW is doing
+const server = setupServer(...handlers)
+server.listen()
+
+// Tests fail mysteriously - is the handler matching? Is the response correct?
+```
+
+**Correct (lifecycle event logging):**
+
+```typescript
+import { setupServer } from 'msw/node'
+import { handlers } from './handlers'
+
+const server = setupServer(...handlers)
+
+// Log all intercepted requests
+server.events.on('request:start', ({ request }) => {
+ console.log('MSW intercepted:', request.method, request.url)
+})
+
+// Log when a handler matches
+server.events.on('request:match', ({ request }) => {
+ console.log('MSW matched:', request.method, request.url)
+})
+
+// Log completed responses
+server.events.on('request:end', ({ request, response }) => {
+ console.log(
+ 'MSW responded:',
+ request.method,
+ request.url,
+ '→',
+ response.status
+ )
+})
+
+// Log unhandled requests
+server.events.on('request:unhandled', ({ request }) => {
+ console.warn('MSW unhandled:', request.method, request.url)
+})
+```
+
+**Conditional logging:**
+
+```typescript
+// Only log in debug mode
+if (process.env.DEBUG_MSW) {
+ server.events.on('request:start', ({ request }) => {
+ console.log('[MSW]', request.method, request.url)
+ })
+}
+```
+
+**Event types:**
+- `request:start` - Request intercepted by MSW
+- `request:match` - Handler found for request
+- `request:unhandled` - No handler matched
+- `request:end` - Response sent (mocked or passthrough)
+- `response:mocked` - Mocked response sent
+- `response:bypass` - Request passed through to network
+
+**Cleanup:**
+
+```typescript
+// Remove event listeners when done
+const unsubscribe = server.events.on('request:start', handler)
+unsubscribe() // Remove listener
+```
+
+**When NOT to use this pattern:**
+- Production builds should not include debug logging
+- CI environments may want minimal logging for cleaner output
+
+Reference: [MSW Lifecycle Events](https://mswjs.io/docs/api/life-cycle-events)
diff --git a/.agents/skills/msw/references/debug-request-logging.md b/.agents/skills/msw/references/debug-request-logging.md
new file mode 100644
index 0000000..87f2a2a
--- /dev/null
+++ b/.agents/skills/msw/references/debug-request-logging.md
@@ -0,0 +1,113 @@
+---
+title: Log Request Details for Debugging
+impact: LOW
+impactDescription: Provides detailed request inspection; identifies payload issues
+tags: debug, logging, request, inspection, development
+---
+
+## Log Request Details for Debugging
+
+Create a debugging middleware handler to log full request details. This helps identify issues with request payloads, headers, and authentication.
+
+**Incorrect (no request visibility):**
+
+```typescript
+// Can't see what's being sent to handlers
+http.post('/api/user', async ({ request }) => {
+ const body = await request.json()
+ // body is unexpected - but why?
+ return HttpResponse.json({ error: 'Invalid data' }, { status: 400 })
+})
+```
+
+**Correct (detailed request logging):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+// Debug middleware - add as first handler
+const debugHandler = http.all('*', async ({ request }) => {
+ const url = new URL(request.url)
+ const clone = request.clone()
+
+ console.group(`[MSW] ${request.method} ${url.pathname}`)
+ console.log('Full URL:', request.url)
+ console.log('Headers:', Object.fromEntries(request.headers.entries()))
+
+ // Log body for non-GET requests
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
+ const contentType = request.headers.get('Content-Type')
+
+ if (contentType?.includes('application/json')) {
+ console.log('Body (JSON):', await clone.json())
+ } else if (contentType?.includes('multipart/form-data')) {
+ const formData = await clone.formData()
+ console.log('Body (FormData):', Object.fromEntries(formData.entries()))
+ } else {
+ console.log('Body (Text):', await clone.text())
+ }
+ }
+
+ console.groupEnd()
+
+ // Don't return - let next handler process the request
+})
+
+export const handlers = [
+ debugHandler, // Must be first
+ // ... other handlers
+]
+```
+
+**Conditional debug mode:**
+
+```typescript
+const DEBUG = process.env.DEBUG_MSW === 'true'
+
+export const handlers = [
+ ...(DEBUG ? [debugHandler] : []),
+ // ... other handlers
+]
+```
+
+**Response logging:**
+
+```typescript
+// Log responses using lifecycle events
+server.events.on('request:end', async ({ request, response }) => {
+ if (!response) return
+
+ const clone = response.clone()
+ const contentType = response.headers.get('Content-Type')
+
+ console.log(`[MSW Response] ${request.method} ${request.url}`)
+ console.log('Status:', response.status)
+
+ if (contentType?.includes('application/json')) {
+ console.log('Body:', await clone.json())
+ }
+})
+```
+
+**Development browser logging:**
+
+```typescript
+// mocks/browser.ts
+import { setupWorker } from 'msw/browser'
+import { handlers } from './handlers'
+
+export const worker = setupWorker(...handlers)
+
+// Enable detailed logging in development
+if (process.env.NODE_ENV === 'development') {
+ worker.start({
+ onUnhandledRequest: 'warn',
+ })
+}
+```
+
+**When NOT to use this pattern:**
+- Remove debug logging before committing/production
+- CI should use minimal logging for cleaner output
+
+Reference: [MSW Lifecycle Events](https://mswjs.io/docs/api/life-cycle-events)
diff --git a/.agents/skills/msw/references/debug-verify-interception.md b/.agents/skills/msw/references/debug-verify-interception.md
new file mode 100644
index 0000000..2b618c1
--- /dev/null
+++ b/.agents/skills/msw/references/debug-verify-interception.md
@@ -0,0 +1,95 @@
+---
+title: Verify Request Interception is Working
+impact: LOW
+impactDescription: Confirms MSW is active; identifies setup failures early
+tags: debug, verification, setup, troubleshooting, runbook
+---
+
+## Verify Request Interception is Working
+
+Add a verification step to confirm MSW is intercepting requests. This catches configuration issues before they cause mysterious test failures.
+
+**Incorrect (assuming MSW is working):**
+
+```typescript
+// No verification - tests fail with confusing errors
+beforeAll(() => server.listen())
+
+it('fetches user', async () => {
+ // If MSW isn't working, this hits real API or fails silently
+ const response = await fetch('/api/user')
+})
+```
+
+**Correct (verify interception):**
+
+```typescript
+import { setupServer } from 'msw/node'
+import { handlers } from './handlers'
+
+const server = setupServer(...handlers)
+
+beforeAll(() => {
+ server.listen()
+
+ // Verify MSW is intercepting
+ server.events.on('request:start', ({ request }) => {
+ console.log('✓ MSW intercepted:', request.method, request.url)
+ })
+})
+
+// Or create a verification test
+describe('MSW Setup', () => {
+ it('intercepts requests', async () => {
+ let intercepted = false
+
+ server.events.on('request:start', () => {
+ intercepted = true
+ })
+
+ await fetch('/api/health')
+
+ expect(intercepted).toBe(true)
+ })
+})
+```
+
+**Debugging checklist when handlers don't match:**
+
+```typescript
+// Step 1: Verify interception is happening
+server.events.on('request:start', ({ request }) => {
+ console.log('Intercepted URL:', request.url) // Check if URL is absolute
+ console.log('Intercepted method:', request.method)
+})
+
+// Step 2: Add console.log inside handler
+http.get('/api/user', () => {
+ console.log('Handler matched!') // If this doesn't log, handler isn't matching
+ return HttpResponse.json({ name: 'John' })
+})
+
+// Step 3: Check handler URL vs request URL
+// Common issues:
+// - Handler: '/api/user' but request goes to 'http://localhost:3000/api/user'
+// - Environment variable in URL is undefined
+// - Typo in URL path
+```
+
+**Browser verification:**
+
+```typescript
+// In browser console
+const { worker } = await import('./mocks/browser')
+await worker.start()
+
+// Check if worker script is accessible
+fetch('/mockServiceWorker.js')
+ .then((r) => r.ok ? 'Worker script found' : 'Worker script missing')
+ .then(console.log)
+```
+
+**When NOT to use this pattern:**
+- Stable test suites don't need verification in every run
+
+Reference: [MSW Debugging Runbook](https://mswjs.io/docs/runbook/)
diff --git a/.agents/skills/msw/references/graphql-batched-queries.md b/.agents/skills/msw/references/graphql-batched-queries.md
new file mode 100644
index 0000000..257d624
--- /dev/null
+++ b/.agents/skills/msw/references/graphql-batched-queries.md
@@ -0,0 +1,93 @@
+---
+title: Handle Batched GraphQL Queries
+impact: MEDIUM
+impactDescription: Supports Apollo batching; prevents unhandled batch requests
+tags: graphql, batching, apollo, performance, advanced
+---
+
+## Handle Batched GraphQL Queries
+
+Create a custom handler for batched GraphQL queries when using Apollo Client's batch link or similar. Batched requests send multiple operations in a single HTTP request.
+
+**Incorrect (individual handlers don't match batches):**
+
+```typescript
+// These won't match a batched request containing both queries
+graphql.query('GetUser', () => {
+ return HttpResponse.json({ data: { user: { name: 'John' } } })
+})
+
+graphql.query('GetPosts', () => {
+ return HttpResponse.json({ data: { posts: [] } })
+})
+
+// Batched request is unhandled!
+```
+
+**Correct (batch handler with individual resolution):**
+
+```typescript
+import { http, HttpResponse, getResponse, bypass } from 'msw'
+
+export function batchedGraphQLQuery(url: string, handlers: RequestHandler[]) {
+ return http.post(url, async ({ request }) => {
+ const requestClone = request.clone()
+ const payload = await request.json()
+
+ // Ignore non-batched requests
+ if (!Array.isArray(payload)) {
+ return
+ }
+
+ // Resolve each query in the batch
+ const responses = await Promise.all(
+ payload.map(async (operation) => {
+ const queryRequest = new Request(requestClone.url, {
+ method: 'POST',
+ headers: requestClone.headers,
+ body: JSON.stringify(operation),
+ })
+
+ const response = await getResponse(handlers, queryRequest)
+ return response || fetch(bypass(queryRequest))
+ })
+ )
+
+ // Combine responses into batch format
+ const results = await Promise.all(
+ responses.map((response) => response?.json())
+ )
+
+ return HttpResponse.json(results)
+ })
+}
+```
+
+```typescript
+// Usage
+import { graphql, HttpResponse } from 'msw'
+import { batchedGraphQLQuery } from './batchedGraphQLQuery'
+
+const graphqlHandlers = [
+ graphql.query('GetUser', () => {
+ return HttpResponse.json({
+ data: { user: { id: '1', name: 'John' } },
+ })
+ }),
+ graphql.query('GetPosts', () => {
+ return HttpResponse.json({
+ data: { posts: [{ id: '1', title: 'Post 1' }] },
+ })
+ }),
+]
+
+export const handlers = [
+ batchedGraphQLQuery('/graphql', graphqlHandlers),
+ ...graphqlHandlers, // Also handle non-batched requests
+]
+```
+
+**When NOT to use this pattern:**
+- Apps not using query batching don't need batch handlers
+
+Reference: [MSW GraphQL Query Batching](https://mswjs.io/docs/graphql/mocking-responses/query-batching)
diff --git a/.agents/skills/msw/references/graphql-error-responses.md b/.agents/skills/msw/references/graphql-error-responses.md
new file mode 100644
index 0000000..36f6bc2
--- /dev/null
+++ b/.agents/skills/msw/references/graphql-error-responses.md
@@ -0,0 +1,119 @@
+---
+title: Return GraphQL Errors in Correct Format
+impact: MEDIUM
+impactDescription: Ensures GraphQL clients parse errors correctly; tests error handling
+tags: graphql, errors, format, validation, response
+---
+
+## Return GraphQL Errors in Correct Format
+
+Return GraphQL errors in the standard `errors` array format. GraphQL errors are different from HTTP errors - they use status 200 with an `errors` field in the response body.
+
+**Incorrect (HTTP-style error response):**
+
+```typescript
+// GraphQL clients won't recognize this as a GraphQL error
+graphql.query('GetUser', () => {
+ return HttpResponse.json(
+ { error: 'User not found' },
+ { status: 404 }
+ )
+})
+```
+
+**Correct (GraphQL error format):**
+
+```typescript
+import { graphql, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Single error
+ graphql.query('GetUser', () => {
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message: 'User not found',
+ extensions: {
+ code: 'NOT_FOUND',
+ },
+ },
+ ],
+ })
+ }),
+
+ // Validation errors with paths
+ graphql.mutation('CreateUser', () => {
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message: 'Invalid email format',
+ path: ['createUser', 'email'],
+ extensions: {
+ code: 'VALIDATION_ERROR',
+ field: 'email',
+ },
+ },
+ {
+ message: 'Name is required',
+ path: ['createUser', 'name'],
+ extensions: {
+ code: 'VALIDATION_ERROR',
+ field: 'name',
+ },
+ },
+ ],
+ })
+ }),
+
+ // Partial success with errors
+ graphql.query('GetUsers', () => {
+ return HttpResponse.json({
+ data: {
+ users: [
+ { id: '1', name: 'John' },
+ null, // This user failed to load
+ { id: '3', name: 'Jane' },
+ ],
+ },
+ errors: [
+ {
+ message: 'Failed to load user',
+ path: ['users', 1],
+ extensions: { code: 'INTERNAL_ERROR' },
+ },
+ ],
+ })
+ }),
+
+ // Authentication error
+ graphql.query('GetPrivateData', () => {
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message: 'Not authenticated',
+ extensions: {
+ code: 'UNAUTHENTICATED',
+ },
+ },
+ ],
+ })
+ }),
+]
+```
+
+**Network-level errors (rare):**
+
+```typescript
+// For complete request failures, use HTTP error
+graphql.query('GetUser', () => {
+ return HttpResponse.error() // Network failure
+})
+```
+
+**When NOT to use this pattern:**
+- True network failures (DNS, connection) use `HttpResponse.error()`
+
+Reference: [GraphQL Spec - Errors](https://spec.graphql.org/October2021/#sec-Errors)
diff --git a/.agents/skills/msw/references/graphql-operation-handlers.md b/.agents/skills/msw/references/graphql-operation-handlers.md
new file mode 100644
index 0000000..398067e
--- /dev/null
+++ b/.agents/skills/msw/references/graphql-operation-handlers.md
@@ -0,0 +1,101 @@
+---
+title: Use Operation Name for GraphQL Matching
+impact: MEDIUM
+impactDescription: Enables precise operation targeting; prevents query/mutation conflicts
+tags: graphql, operation, query, mutation, matching
+---
+
+## Use Operation Name for GraphQL Matching
+
+Match GraphQL operations by their operation name, not by URL. All GraphQL requests typically go to the same endpoint (`/graphql`), so operation name is the discriminator.
+
+**Incorrect (URL-based matching for GraphQL):**
+
+```typescript
+// All GraphQL requests go to /graphql - this catches everything!
+http.post('/graphql', () => {
+ return HttpResponse.json({ data: { user: { name: 'John' } } })
+})
+```
+
+**Correct (operation-based matching):**
+
+```typescript
+import { graphql, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Match query by operation name
+ graphql.query('GetUser', () => {
+ return HttpResponse.json({
+ data: {
+ user: {
+ id: '1',
+ name: 'John',
+ email: 'john@example.com',
+ },
+ },
+ })
+ }),
+
+ // Match mutation by operation name
+ graphql.mutation('CreateUser', async ({ variables }) => {
+ return HttpResponse.json({
+ data: {
+ createUser: {
+ id: crypto.randomUUID(),
+ name: variables.name,
+ email: variables.email,
+ },
+ },
+ })
+ }),
+
+ // Separate handlers for different queries
+ graphql.query('GetUsers', () => {
+ return HttpResponse.json({
+ data: {
+ users: [
+ { id: '1', name: 'John' },
+ { id: '2', name: 'Jane' },
+ ],
+ },
+ })
+ }),
+]
+```
+
+**Access operation variables:**
+
+```typescript
+graphql.query('GetUser', ({ variables }) => {
+ // variables matches your GraphQL query variables
+ return HttpResponse.json({
+ data: {
+ user: {
+ id: variables.id,
+ name: 'John',
+ },
+ },
+ })
+})
+
+// Query from client:
+// query GetUser($id: ID!) { user(id: $id) { id name } }
+// variables: { id: "123" }
+```
+
+**Custom GraphQL endpoint:**
+
+```typescript
+// If your GraphQL endpoint isn't /graphql
+graphql.link('https://api.example.com/gql').query('GetUser', () => {
+ return HttpResponse.json({
+ data: { user: { name: 'John' } },
+ })
+})
+```
+
+**When NOT to use this pattern:**
+- REST APIs should use `http.*` handlers, not GraphQL handlers
+
+Reference: [MSW GraphQL API](https://mswjs.io/docs/api/graphql)
diff --git a/.agents/skills/msw/references/graphql-schema-first.md b/.agents/skills/msw/references/graphql-schema-first.md
new file mode 100644
index 0000000..2979951
--- /dev/null
+++ b/.agents/skills/msw/references/graphql-schema-first.md
@@ -0,0 +1,76 @@
+---
+title: Resolve Operations Against a GraphQL Schema
+impact: MEDIUM
+impactDescription: schema-accurate mocks without hand-writing response shapes
+tags: msw, graphql, schema, operation
+---
+
+## Resolve Operations Against a GraphQL Schema
+
+Instead of hand-writing every mocked GraphQL response, execute intercepted operations against a real schema with the `graphql` package inside a `graphql.operation()` catch-all handler. Responses stay schema-valid as operations evolve, and resolvers live in one place.
+
+**Incorrect (hand-maintained response shapes per operation):**
+
+```typescript
+// Every handler duplicates the response shape; a schema change
+// silently leaves stale mocks that no longer match production
+export const handlers = [
+ graphql.query('GetUser', () =>
+ HttpResponse.json({ data: { user: { id: '1', firstName: 'John' } } }),
+ ),
+ graphql.query('GetUserWithPosts', () =>
+ HttpResponse.json({
+ data: { user: { id: '1', firstName: 'John', posts: [] } },
+ }),
+ ),
+]
+```
+
+**Correct (schema-first resolution):**
+
+```typescript
+import { graphql, HttpResponse } from 'msw'
+import { graphql as executeGraphql, buildSchema } from 'graphql'
+
+const schema = buildSchema(`
+ type User {
+ id: ID!
+ firstName: String!
+ }
+
+ type Query {
+ user(id: ID!): User
+ }
+`)
+
+const data = {
+ users: [
+ { id: '1', name: 'John' },
+ { id: '2', name: 'Kate' },
+ ],
+}
+
+export const handlers = [
+ graphql.operation(async ({ query, variables }) => {
+ const { data, errors } = await executeGraphql({
+ schema,
+ source: query,
+ variableValues: variables,
+ rootValue: {
+ user(args) {
+ return data.users.find((user) => user.id === args.id)
+ },
+ },
+ })
+
+ return HttpResponse.json({ data, errors })
+ }),
+]
+```
+
+**Notes:**
+
+- `graphql.operation()` matches every operation; place more specific named-operation handlers above it when you need per-test overrides.
+- The `graphql` package (`buildSchema`, `graphql()`) is a peer dependency you install alongside MSW.
+- Because resolution runs against the schema, invalid client queries surface real GraphQL `errors` in the mocked response — useful for testing error UI.
+- Pair with [graphql-operation-handlers](graphql-operation-handlers.md) for targeted overrides and [graphql-error-responses](graphql-error-responses.md) for error-shape rules.
diff --git a/.agents/skills/msw/references/graphql-variables-access.md b/.agents/skills/msw/references/graphql-variables-access.md
new file mode 100644
index 0000000..9853b9b
--- /dev/null
+++ b/.agents/skills/msw/references/graphql-variables-access.md
@@ -0,0 +1,123 @@
+---
+title: Access GraphQL Variables Correctly
+impact: MEDIUM
+impactDescription: Enables dynamic mock responses based on query input
+tags: graphql, variables, dynamic, input, resolver
+---
+
+## Access GraphQL Variables Correctly
+
+Access GraphQL variables through the `variables` property in the resolver argument. Use them to return dynamic responses based on query input.
+
+**Incorrect (ignoring variables):**
+
+```typescript
+// Returns same user regardless of which ID is requested
+graphql.query('GetUser', () => {
+ return HttpResponse.json({
+ data: {
+ user: { id: '1', name: 'John' },
+ },
+ })
+})
+```
+
+**Correct (using variables for dynamic responses):**
+
+```typescript
+import { graphql, HttpResponse } from 'msw'
+
+// Mock data store
+const users = new Map([
+ ['1', { id: '1', name: 'John', email: 'john@example.com' }],
+ ['2', { id: '2', name: 'Jane', email: 'jane@example.com' }],
+])
+
+export const handlers = [
+ graphql.query('GetUser', ({ variables }) => {
+ const user = users.get(variables.id)
+
+ if (!user) {
+ return HttpResponse.json({
+ data: null,
+ errors: [{ message: 'User not found' }],
+ })
+ }
+
+ return HttpResponse.json({
+ data: { user },
+ })
+ }),
+
+ // Mutation with input variables
+ graphql.mutation('UpdateUser', ({ variables }) => {
+ const { id, input } = variables
+ const existingUser = users.get(id)
+
+ if (!existingUser) {
+ return HttpResponse.json({
+ data: null,
+ errors: [{ message: 'User not found' }],
+ })
+ }
+
+ const updatedUser = { ...existingUser, ...input }
+ users.set(id, updatedUser)
+
+ return HttpResponse.json({
+ data: { updateUser: updatedUser },
+ })
+ }),
+
+ // Pagination with variables
+ graphql.query('GetUsers', ({ variables }) => {
+ const { first = 10, after } = variables
+ const allUsers = Array.from(users.values())
+
+ let startIndex = 0
+ if (after) {
+ startIndex = allUsers.findIndex((u) => u.id === after) + 1
+ }
+
+ const pageUsers = allUsers.slice(startIndex, startIndex + first)
+ const hasNextPage = startIndex + first < allUsers.length
+
+ return HttpResponse.json({
+ data: {
+ users: {
+ edges: pageUsers.map((user) => ({
+ node: user,
+ cursor: user.id,
+ })),
+ pageInfo: {
+ hasNextPage,
+ endCursor: pageUsers[pageUsers.length - 1]?.id,
+ },
+ },
+ },
+ })
+ }),
+]
+```
+
+**Type-safe variables:**
+
+```typescript
+type GetUserVariables = {
+ id: string
+}
+
+graphql.query('GetUser', ({ variables }) => {
+ // variables.id is typed as string
+ return HttpResponse.json({
+ data: {
+ user: { id: variables.id, name: 'John' },
+ },
+ })
+})
+```
+
+**When NOT to use this pattern:**
+- Queries without variables don't need variable access
+
+Reference: [MSW GraphQL Intercepting Operations](https://mswjs.io/docs/graphql/intercepting-operations)
diff --git a/.agents/skills/msw/references/handler-absolute-urls.md b/.agents/skills/msw/references/handler-absolute-urls.md
new file mode 100644
index 0000000..5f6b8fd
--- /dev/null
+++ b/.agents/skills/msw/references/handler-absolute-urls.md
@@ -0,0 +1,70 @@
+---
+title: Use Absolute URLs in Handlers
+impact: CRITICAL
+impactDescription: Prevents URL mismatch failures; required for Node.js environments
+tags: handler, url, absolute, node, matching
+---
+
+## Use Absolute URLs in Handlers
+
+Use absolute URLs or URL patterns in request handlers. Node.js environments require absolute URLs for proper matching, and relative URLs cause silent handler failures.
+
+**Incorrect (relative URLs in Node.js context):**
+
+```typescript
+// mocks/handlers.ts
+export const handlers = [
+ // Relative URL - may not match in Node.js tests
+ http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ }),
+]
+
+// Test makes request to full URL
+await fetch('http://localhost:3000/api/user')
+// Handler doesn't match - request goes unhandled
+```
+
+**Correct (absolute URLs or wildcards):**
+
+```typescript
+// mocks/handlers.ts
+export const handlers = [
+ // Absolute URL - matches reliably
+ http.get('http://localhost:3000/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ }),
+]
+```
+
+**Better (wildcard for any origin):**
+
+```typescript
+// mocks/handlers.ts
+export const handlers = [
+ // Wildcard matches any origin - most flexible
+ http.get('*/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ }),
+
+ // Or use path patterns that MSW resolves against baseURL
+ http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ }),
+]
+```
+
+**Environment variable pitfall:**
+
+```typescript
+// AVOID: Environment variable not set in tests
+const API_URL = process.env.API_URL // undefined in tests!
+
+http.get(`${API_URL}/user`, () => { /* ... */ })
+// Results in: http.get('undefined/user', ...) - never matches
+```
+
+**When NOT to use this pattern:**
+- Browser environments with properly configured base URLs may use relative paths
+
+Reference: [MSW Debugging Runbook](https://mswjs.io/docs/runbook/)
diff --git a/.agents/skills/msw/references/handler-domain-grouping.md b/.agents/skills/msw/references/handler-domain-grouping.md
new file mode 100644
index 0000000..0302e5d
--- /dev/null
+++ b/.agents/skills/msw/references/handler-domain-grouping.md
@@ -0,0 +1,81 @@
+---
+title: Group Handlers by Domain
+impact: CRITICAL
+impactDescription: Reduces maintenance overhead; scales to large APIs without N×M complexity
+tags: handler, organization, domain, modules, scalability
+---
+
+## Group Handlers by Domain
+
+Split handlers into separate files organized by domain or feature area. This prevents a single handlers file from becoming unmanageable and enables selective handler composition for different test scenarios.
+
+**Incorrect (monolithic handler file):**
+
+```typescript
+// mocks/handlers.ts - 500+ lines, unmaintainable
+export const handlers = [
+ // User endpoints
+ http.get('/api/user', () => { /* ... */ }),
+ http.post('/api/user', () => { /* ... */ }),
+ http.delete('/api/user/:id', () => { /* ... */ }),
+ // Auth endpoints
+ http.post('/api/login', () => { /* ... */ }),
+ http.post('/api/logout', () => { /* ... */ }),
+ // Product endpoints
+ http.get('/api/products', () => { /* ... */ }),
+ // ... 50 more endpoints mixed together
+]
+```
+
+**Correct (domain-organized handlers):**
+
+```typescript
+// mocks/handlers/user.ts
+import { http, HttpResponse } from 'msw'
+
+export const userHandlers = [
+ http.get('/api/user', () => {
+ return HttpResponse.json({ id: '1', name: 'John' })
+ }),
+ http.post('/api/user', async ({ request }) => {
+ const user = await request.json()
+ return HttpResponse.json(user, { status: 201 })
+ }),
+ http.delete('/api/user/:id', ({ params }) => {
+ return new HttpResponse(null, { status: 204 })
+ }),
+]
+```
+
+```typescript
+// mocks/handlers/auth.ts
+import { http, HttpResponse } from 'msw'
+
+export const authHandlers = [
+ http.post('/api/login', async ({ request }) => {
+ const { email, password } = await request.json()
+ return HttpResponse.json({ token: 'jwt-token' })
+ }),
+ http.post('/api/logout', () => {
+ return new HttpResponse(null, { status: 200 })
+ }),
+]
+```
+
+```typescript
+// mocks/handlers/index.ts - compose all handlers
+import { userHandlers } from './user'
+import { authHandlers } from './auth'
+import { productHandlers } from './products'
+
+export const handlers = [
+ ...userHandlers,
+ ...authHandlers,
+ ...productHandlers,
+]
+```
+
+**When NOT to use this pattern:**
+- Small projects with fewer than 10 endpoints may use a single file
+
+Reference: [Structuring Handlers - Group by Domain](https://mswjs.io/docs/best-practices/structuring-handlers)
diff --git a/.agents/skills/msw/references/handler-happy-path-first.md b/.agents/skills/msw/references/handler-happy-path-first.md
new file mode 100644
index 0000000..f214391
--- /dev/null
+++ b/.agents/skills/msw/references/handler-happy-path-first.md
@@ -0,0 +1,60 @@
+---
+title: Define Happy Path Handlers as Baseline
+impact: CRITICAL
+impactDescription: Establishes reliable baseline; enables clean runtime overrides
+tags: handler, structure, happy-path, baseline, organization
+---
+
+## Define Happy Path Handlers as Baseline
+
+Define success-state handlers in a central `handlers.ts` file as your baseline. This establishes a reliable foundation that runtime overrides can modify for error scenarios, keeping test-specific edge cases separate from normal behavior.
+
+**Incorrect (mixing success and error states):**
+
+```typescript
+// mocks/handlers.ts - cluttered with all scenarios
+export const handlers = [
+ http.get('/user', () => HttpResponse.json({ name: 'John' })),
+ http.get('/user', () => new HttpResponse(null, { status: 401 })),
+ http.get('/user', () => new HttpResponse(null, { status: 500 })),
+ http.get('/user', () => HttpResponse.error()),
+ // Confusing: which handler runs? Last one wins but intent unclear
+]
+```
+
+**Correct (happy path baseline with runtime overrides):**
+
+```typescript
+// mocks/handlers.ts - clean success states only
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ http.get('/api/user', () => {
+ return HttpResponse.json({ id: '1', name: 'John Maverick' })
+ }),
+ http.post('/api/login', async ({ request }) => {
+ const { email } = await request.json()
+ return HttpResponse.json({ token: 'mock-jwt-token', email })
+ }),
+]
+```
+
+```typescript
+// user.test.ts - override for specific scenarios
+import { http, HttpResponse } from 'msw'
+import { server } from '../mocks/node'
+
+it('handles authentication error', () => {
+ server.use(
+ http.get('/api/user', () => {
+ return new HttpResponse(null, { status: 401 })
+ })
+ )
+ // Test error handling...
+})
+```
+
+**When NOT to use this pattern:**
+- Single-use test utilities that will never need runtime overrides
+
+Reference: [Structuring Handlers](https://mswjs.io/docs/best-practices/structuring-handlers)
diff --git a/.agents/skills/msw/references/handler-request-body-parsing.md b/.agents/skills/msw/references/handler-request-body-parsing.md
new file mode 100644
index 0000000..25f3235
--- /dev/null
+++ b/.agents/skills/msw/references/handler-request-body-parsing.md
@@ -0,0 +1,76 @@
+---
+title: Explicitly Parse Request Bodies
+impact: CRITICAL
+impactDescription: v2 no longer auto-parses bodies; missing parsing returns undefined
+tags: handler, request, body, parsing, json
+---
+
+## Explicitly Parse Request Bodies
+
+MSW v2 does not automatically parse request bodies based on Content-Type. You must explicitly call `.json()`, `.text()`, `.formData()`, or `.arrayBuffer()` on the request object.
+
+**Incorrect (assuming auto-parsed body):**
+
+```typescript
+// MSW v1 pattern - body was auto-parsed
+http.post('/api/user', ({ request }) => {
+ const body = request.body // a ReadableStream in v2, not parsed data
+ return HttpResponse.json({ id: '1', ...body })
+})
+```
+
+**Correct (explicit body parsing):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // JSON body
+ http.post('/api/user', async ({ request }) => {
+ const body = await request.json()
+ return HttpResponse.json({ id: '1', ...body }, { status: 201 })
+ }),
+
+ // Text body
+ http.post('/api/text', async ({ request }) => {
+ const text = await request.text()
+ return HttpResponse.text(`Received: ${text}`)
+ }),
+
+ // Form data
+ http.post('/api/upload', async ({ request }) => {
+ const formData = await request.formData()
+ const file = formData.get('file')
+ return HttpResponse.json({ filename: file?.name })
+ }),
+
+ // ArrayBuffer for binary
+ http.post('/api/binary', async ({ request }) => {
+ const buffer = await request.arrayBuffer()
+ return HttpResponse.json({ bytes: buffer.byteLength })
+ }),
+]
+```
+
+**Typed body parsing:**
+
+```typescript
+interface CreateUserRequest {
+ name: string
+ email: string
+}
+
+http.post('/api/user', async ({ request }) => {
+ const body = await request.json() as CreateUserRequest
+ return HttpResponse.json({
+ id: crypto.randomUUID(),
+ name: body.name,
+ email: body.email,
+ })
+})
+```
+
+**When NOT to use this pattern:**
+- GET requests typically don't have bodies and don't need parsing
+
+Reference: [MSW v2 Migration - Request Changes](https://mswjs.io/docs/migrations/1.x-to-2.x/)
diff --git a/.agents/skills/msw/references/handler-resolver-argument.md b/.agents/skills/msw/references/handler-resolver-argument.md
new file mode 100644
index 0000000..9794299
--- /dev/null
+++ b/.agents/skills/msw/references/handler-resolver-argument.md
@@ -0,0 +1,86 @@
+---
+title: Destructure Resolver Arguments Correctly
+impact: CRITICAL
+impactDescription: Wrong destructuring pattern causes undefined values; silent failures
+tags: handler, resolver, params, cookies, request, destructuring
+---
+
+## Destructure Resolver Arguments Correctly
+
+MSW v2 passes a single object argument to resolvers containing `request`, `params`, `cookies`, and other properties. Destructure from this object instead of using multiple arguments.
+
+**Incorrect (v1 multiple arguments pattern):**
+
+```typescript
+// MSW v1 pattern - does not work in v2
+http.get('/api/user/:id', (req, res, ctx) => {
+ const userId = req.params.id // undefined!
+ return res(ctx.json({ id: userId }))
+})
+```
+
+**Correct (v2 single object argument):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Destructure from single argument object
+ http.get('/api/user/:id', ({ request, params, cookies }) => {
+ return HttpResponse.json({
+ id: params.id,
+ sessionId: cookies.sessionId,
+ userAgent: request.headers.get('User-Agent'),
+ })
+ }),
+]
+```
+
+**Available resolver properties:**
+
+```typescript
+http.post('/api/data', async (info) => {
+ // Full request object
+ const { request } = info
+
+ // URL path parameters
+ const { params } = info // { id: '123' } for /api/data/:id
+
+ // Parsed cookies from Cookie header
+ const { cookies } = info // { session: 'abc', token: 'xyz' }
+
+ // Request URL as string (not URL object)
+ const url = new URL(request.url)
+
+ // Request method
+ const method = request.method
+
+ // Request headers
+ const authHeader = request.headers.get('Authorization')
+
+ // Request body (must await)
+ const body = await request.json()
+
+ return HttpResponse.json({ success: true })
+})
+```
+
+**Type-safe params:**
+
+```typescript
+// Define params type for better type safety
+type UserParams = {
+ id: string
+ orgId: string
+}
+
+http.get('/api/org/:orgId/user/:id', ({ params }) => {
+ // params.id and params.orgId are typed as string
+ return HttpResponse.json({ userId: params.id, orgId: params.orgId })
+})
+```
+
+**When NOT to use this pattern:**
+- This is the only pattern in MSW v2; no alternatives
+
+Reference: [MSW v2 Migration - Resolver Changes](https://mswjs.io/docs/migrations/1.x-to-2.x/)
diff --git a/.agents/skills/msw/references/handler-reusability-environments.md b/.agents/skills/msw/references/handler-reusability-environments.md
new file mode 100644
index 0000000..17db61e
--- /dev/null
+++ b/.agents/skills/msw/references/handler-reusability-environments.md
@@ -0,0 +1,80 @@
+---
+title: Share Handlers Across Environments
+impact: CRITICAL
+impactDescription: Single source of truth; eliminates mock drift between dev/test
+tags: handler, reuse, environment, browser, node, integration
+---
+
+## Share Handlers Across Environments
+
+Define handlers once and reuse them across browser (development) and Node.js (testing) environments. This ensures mock behavior is consistent and prevents drift between development and test mocks.
+
+**Incorrect (duplicate handlers per environment):**
+
+```typescript
+// mocks/browser-handlers.ts - browser development
+export const browserHandlers = [
+ http.get('/api/user', () => HttpResponse.json({ name: 'Dev User' })),
+]
+
+// mocks/test-handlers.ts - tests (different implementation!)
+export const testHandlers = [
+ http.get('/api/user', () => HttpResponse.json({ name: 'Test User' })),
+]
+// Mock behavior differs between environments - bugs hide until production
+```
+
+**Correct (shared handlers, environment-specific setup):**
+
+```typescript
+// mocks/handlers.ts - single source of truth
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ http.get('/api/user', () => {
+ return HttpResponse.json({ id: '1', name: 'John Maverick' })
+ }),
+ http.get('/api/posts', () => {
+ return HttpResponse.json([
+ { id: '1', title: 'First Post' },
+ { id: '2', title: 'Second Post' },
+ ])
+ }),
+]
+```
+
+```typescript
+// mocks/browser.ts - browser setup
+import { setupWorker } from 'msw/browser'
+import { handlers } from './handlers'
+
+export const worker = setupWorker(...handlers)
+```
+
+```typescript
+// mocks/node.ts - Node.js setup
+import { setupServer } from 'msw/node'
+import { handlers } from './handlers'
+
+export const server = setupServer(...handlers)
+```
+
+```typescript
+// src/index.tsx - conditional browser activation
+async function enableMocking() {
+ if (process.env.NODE_ENV !== 'development') {
+ return
+ }
+ const { worker } = await import('./mocks/browser')
+ return worker.start()
+}
+
+enableMocking().then(() => {
+ ReactDOM.createRoot(document.getElementById('root')!).render()
+})
+```
+
+**When NOT to use this pattern:**
+- Environment-specific handlers (e.g., browser-only features) can be added via separate arrays
+
+Reference: [MSW Comparison - Reusability](https://mswjs.io/docs/comparison)
diff --git a/.agents/skills/msw/references/handler-shared-resolvers.md b/.agents/skills/msw/references/handler-shared-resolvers.md
new file mode 100644
index 0000000..80bccb6
--- /dev/null
+++ b/.agents/skills/msw/references/handler-shared-resolvers.md
@@ -0,0 +1,99 @@
+---
+title: Extract Shared Response Logic into Resolvers
+impact: CRITICAL
+impactDescription: Eliminates duplication; ensures consistent mock responses across tests
+tags: handler, resolver, reuse, abstraction, dry
+---
+
+## Extract Shared Response Logic into Resolvers
+
+Extract repetitive response logic into reusable resolver functions. This ensures consistency across handlers and reduces maintenance when response shapes change.
+
+**Incorrect (duplicated response logic):**
+
+```typescript
+// mocks/handlers.ts
+export const handlers = [
+ http.get('/api/user/:id', ({ params }) => {
+ return HttpResponse.json({
+ id: params.id,
+ name: 'John',
+ email: 'john@example.com',
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ })
+ }),
+ http.get('/api/users', () => {
+ return HttpResponse.json([
+ {
+ id: '1',
+ name: 'John',
+ email: 'john@example.com',
+ createdAt: new Date().toISOString(), // Duplicated shape
+ updatedAt: new Date().toISOString(),
+ },
+ // ... more users with same structure
+ ])
+ }),
+]
+```
+
+**Correct (shared resolver factories):**
+
+```typescript
+// mocks/factories/user.ts
+import { faker } from '@faker-js/faker'
+
+export function createMockUser(overrides: Partial = {}): User {
+ return {
+ id: faker.string.uuid(),
+ name: faker.person.fullName(),
+ email: faker.internet.email(),
+ createdAt: faker.date.past().toISOString(),
+ updatedAt: faker.date.recent().toISOString(),
+ ...overrides,
+ }
+}
+```
+
+```typescript
+// mocks/handlers/user.ts
+import { http, HttpResponse } from 'msw'
+import { createMockUser } from '../factories/user'
+
+export const userHandlers = [
+ http.get('/api/user/:id', ({ params }) => {
+ return HttpResponse.json(createMockUser({ id: params.id as string }))
+ }),
+ http.get('/api/users', () => {
+ return HttpResponse.json([
+ createMockUser(),
+ createMockUser(),
+ createMockUser(),
+ ])
+ }),
+]
+```
+
+**Higher-order handler for cross-cutting concerns:**
+
+```typescript
+// mocks/utils/withAuth.ts
+import { HttpResponse } from 'msw'
+import type { HttpResponseResolver } from 'msw'
+
+export function withAuth(resolver: HttpResponseResolver): HttpResponseResolver {
+ return ({ request, ...rest }) => {
+ const authHeader = request.headers.get('Authorization')
+ if (!authHeader?.startsWith('Bearer ')) {
+ return new HttpResponse(null, { status: 401 })
+ }
+ return resolver({ request, ...rest })
+ }
+}
+```
+
+**When NOT to use this pattern:**
+- One-off handlers for specific test scenarios don't need abstraction
+
+Reference: [Structuring Handlers](https://mswjs.io/docs/best-practices/structuring-handlers)
diff --git a/.agents/skills/msw/references/handler-v2-response-syntax.md b/.agents/skills/msw/references/handler-v2-response-syntax.md
new file mode 100644
index 0000000..bc5d190
--- /dev/null
+++ b/.agents/skills/msw/references/handler-v2-response-syntax.md
@@ -0,0 +1,94 @@
+---
+title: Use MSW v2 Response Syntax
+impact: CRITICAL
+impactDescription: v1 syntax breaks in v2; causes complete handler failure
+tags: handler, response, v2, HttpResponse, migration
+---
+
+## Use MSW v2 Response Syntax
+
+MSW v2 replaces the composition-based `res(ctx.json())` syntax with native `Response` and `HttpResponse`. Using v1 syntax in v2 causes handlers to fail silently.
+
+**Incorrect (v1 composition syntax):**
+
+```typescript
+// MSW v1 syntax - does not work in v2
+import { rest } from 'msw'
+
+export const handlers = [
+ rest.get('/api/user', (req, res, ctx) => {
+ return res(
+ ctx.status(200),
+ ctx.json({ name: 'John' }),
+ ctx.delay(100)
+ )
+ }),
+]
+```
+
+**Correct (v2 HttpResponse syntax):**
+
+```typescript
+// MSW v2 syntax
+import { http, HttpResponse, delay } from 'msw'
+
+export const handlers = [
+ http.get('/api/user', async () => {
+ await delay(100)
+ return HttpResponse.json(
+ { name: 'John' },
+ { status: 200 }
+ )
+ }),
+]
+```
+
+**Common v2 response patterns:**
+
+```typescript
+import { http, HttpResponse, delay } from 'msw'
+
+export const handlers = [
+ // JSON response
+ http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ }),
+
+ // Text response
+ http.get('/api/text', () => {
+ return HttpResponse.text('Hello, World!')
+ }),
+
+ // XML response
+ http.get('/api/xml', () => {
+ return HttpResponse.xml('John')
+ }),
+
+ // Empty response with status
+ http.delete('/api/user/:id', () => {
+ return new HttpResponse(null, { status: 204 })
+ }),
+
+ // Custom headers
+ http.get('/api/data', () => {
+ return HttpResponse.json(
+ { data: 'value' },
+ {
+ headers: {
+ 'X-Custom-Header': 'custom-value',
+ },
+ }
+ )
+ }),
+
+ // Network error
+ http.get('/api/error', () => {
+ return HttpResponse.error()
+ }),
+]
+```
+
+**When NOT to use this pattern:**
+- Projects still on MSW v1 should use the v1 syntax until migration
+
+Reference: [MSW v2 Migration Guide](https://mswjs.io/docs/migrations/1.x-to-2.x/)
diff --git a/.agents/skills/msw/references/match-custom-predicate.md b/.agents/skills/msw/references/match-custom-predicate.md
new file mode 100644
index 0000000..f537d4c
--- /dev/null
+++ b/.agents/skills/msw/references/match-custom-predicate.md
@@ -0,0 +1,99 @@
+---
+title: Use Custom Predicates for Complex Matching
+impact: MEDIUM-HIGH
+impactDescription: Enables header-based, body-based, and conditional request matching
+tags: match, predicate, custom, conditional, advanced
+---
+
+## Use Custom Predicates for Complex Matching
+
+Use a predicate function instead of a URL string for complex matching logic. This enables matching based on headers, request body, cookies, or any combination of request properties.
+
+**Incorrect (multiple handlers for same URL):**
+
+```typescript
+// Awkward - two handlers for same URL with different behavior
+http.get('/api/data', () => {
+ return HttpResponse.json({ public: true })
+})
+
+// How to handle authenticated vs unauthenticated?
+```
+
+**Correct (predicate-based matching):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Match based on header presence
+ http.get('/api/data', ({ request }) => {
+ const authHeader = request.headers.get('Authorization')
+
+ if (authHeader?.startsWith('Bearer ')) {
+ return HttpResponse.json({ data: 'authenticated content' })
+ }
+
+ return HttpResponse.json(
+ { error: 'Unauthorized' },
+ { status: 401 }
+ )
+ }),
+]
+```
+
+**Predicate function syntax:**
+
+```typescript
+// Match by custom criteria
+http.all(
+ ({ request }) => {
+ // Return true to match this request
+ return request.url.includes('/api/') &&
+ request.headers.get('X-Custom-Header') === 'special'
+ },
+ () => {
+ return HttpResponse.json({ matched: true })
+ }
+)
+```
+
+**Match by request body content:**
+
+```typescript
+http.post(
+ '/api/action',
+ async ({ request }) => {
+ const body = await request.clone().json()
+
+ // Different response based on action type
+ if (body.action === 'create') {
+ return HttpResponse.json({ id: '1', created: true })
+ }
+ if (body.action === 'delete') {
+ return new HttpResponse(null, { status: 204 })
+ }
+
+ return HttpResponse.json(
+ { error: 'Unknown action' },
+ { status: 400 }
+ )
+ }
+)
+```
+
+**Match by cookie value:**
+
+```typescript
+http.get('/api/user', ({ cookies }) => {
+ if (cookies.role === 'admin') {
+ return HttpResponse.json({ permissions: ['read', 'write', 'delete'] })
+ }
+ return HttpResponse.json({ permissions: ['read'] })
+})
+```
+
+**When NOT to use this pattern:**
+- Simple URL-based matching is clearer when sufficient
+
+Reference: [MSW Custom Request Predicate](https://mswjs.io/docs/best-practices/custom-request-predicate)
diff --git a/.agents/skills/msw/references/match-handler-order.md b/.agents/skills/msw/references/match-handler-order.md
new file mode 100644
index 0000000..6f7b804
--- /dev/null
+++ b/.agents/skills/msw/references/match-handler-order.md
@@ -0,0 +1,93 @@
+---
+title: Order Handlers from Specific to General
+impact: MEDIUM-HIGH
+impactDescription: Prevents general handlers from shadowing specific ones
+tags: match, order, priority, specific, general
+---
+
+## Order Handlers from Specific to General
+
+Place more specific handlers before general ones in the handlers array. MSW matches handlers in order, and the first match wins. A wildcard handler placed first will shadow all subsequent handlers.
+
+**Incorrect (general handler shadows specific):**
+
+```typescript
+export const handlers = [
+ // Wildcard matches first - specific handlers never reached!
+ http.get('/api/*', () => {
+ return HttpResponse.json({ fallback: true })
+ }),
+
+ // Never matches because /api/* already caught it
+ http.get('/api/user/:id', ({ params }) => {
+ return HttpResponse.json({ id: params.id, name: 'John' })
+ }),
+]
+```
+
+**Correct (specific before general):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Most specific handlers first
+ http.get('/api/user/:id/settings', ({ params }) => {
+ return HttpResponse.json({ userId: params.id, theme: 'dark' })
+ }),
+
+ http.get('/api/user/:id', ({ params }) => {
+ return HttpResponse.json({ id: params.id, name: 'John' })
+ }),
+
+ http.get('/api/users', () => {
+ return HttpResponse.json([{ id: '1' }, { id: '2' }])
+ }),
+
+ // General fallback last
+ http.get('/api/*', () => {
+ return HttpResponse.json(
+ { error: 'Not found' },
+ { status: 404 }
+ )
+ }),
+]
+```
+
+**Middleware with passthrough:**
+
+```typescript
+export const handlers = [
+ // Middleware runs first but doesn't return - passes through
+ http.all('*', async () => {
+ await delay(50) // Add delay to all requests
+ // No return = continue to next handler
+ }),
+
+ // Specific handlers still match
+ http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ }),
+]
+```
+
+**Runtime handler precedence:**
+
+```typescript
+// Initial handlers
+const server = setupServer(
+ http.get('/api/user', () => HttpResponse.json({ name: 'John' }))
+)
+
+// Runtime handlers are PREPENDED (take precedence)
+server.use(
+ http.get('/api/user', () => HttpResponse.json({ name: 'Jane' }))
+)
+
+// Request to /api/user returns { name: 'Jane' }
+```
+
+**When NOT to use this pattern:**
+- Single handlers don't have ordering concerns
+
+Reference: [MSW Handler Precedence](https://mswjs.io/docs/concepts/request-handler)
diff --git a/.agents/skills/msw/references/match-http-methods.md b/.agents/skills/msw/references/match-http-methods.md
new file mode 100644
index 0000000..04d7f6d
--- /dev/null
+++ b/.agents/skills/msw/references/match-http-methods.md
@@ -0,0 +1,98 @@
+---
+title: Match HTTP Methods Explicitly
+impact: MEDIUM-HIGH
+impactDescription: Prevents cross-method interference; models REST APIs correctly
+tags: match, methods, http, get, post, put, delete
+---
+
+## Match HTTP Methods Explicitly
+
+Use method-specific handlers (`http.get`, `http.post`, etc.) instead of `http.all`. This prevents a GET handler from accidentally matching POST requests and ensures correct REST API simulation.
+
+**Incorrect (catching unintended methods):**
+
+```typescript
+// Matches ALL methods - GET, POST, PUT, DELETE, etc.
+http.all('/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+})
+
+// POST /api/user also returns user JSON instead of creating
+```
+
+**Correct (method-specific handlers):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // GET - retrieve resource
+ http.get('/api/user/:id', ({ params }) => {
+ return HttpResponse.json({ id: params.id, name: 'John' })
+ }),
+
+ // POST - create resource
+ http.post('/api/user', async ({ request }) => {
+ const body = await request.json()
+ return HttpResponse.json(
+ { id: crypto.randomUUID(), ...body },
+ { status: 201 }
+ )
+ }),
+
+ // PUT - replace resource
+ http.put('/api/user/:id', async ({ params, request }) => {
+ const body = await request.json()
+ return HttpResponse.json({ id: params.id, ...body })
+ }),
+
+ // PATCH - partial update
+ http.patch('/api/user/:id', async ({ params, request }) => {
+ const updates = await request.json()
+ return HttpResponse.json({ id: params.id, name: 'John', ...updates })
+ }),
+
+ // DELETE - remove resource
+ http.delete('/api/user/:id', () => {
+ return new HttpResponse(null, { status: 204 })
+ }),
+
+ // HEAD - metadata only
+ http.head('/api/user/:id', () => {
+ return new HttpResponse(null, {
+ headers: { 'X-User-Exists': 'true' },
+ })
+ }),
+
+ // OPTIONS - CORS preflight
+ http.options('/api/*', () => {
+ return new HttpResponse(null, {
+ headers: {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
+ },
+ })
+ }),
+]
+```
+
+**When to use http.all:**
+
+```typescript
+// Global middleware (logging, delay)
+http.all('*', async () => {
+ await delay(50)
+ // No return - continues to next handler
+})
+
+// Catch-all fallback for testing
+http.all('/api/*', () => {
+ console.warn('Unhandled API request')
+ return new HttpResponse(null, { status: 404 })
+})
+```
+
+**When NOT to use this pattern:**
+- Middleware handlers that should apply to all methods can use `http.all`
+
+Reference: [MSW HTTP Handlers](https://mswjs.io/docs/api/http)
diff --git a/.agents/skills/msw/references/match-query-params.md b/.agents/skills/msw/references/match-query-params.md
new file mode 100644
index 0000000..8e9bb12
--- /dev/null
+++ b/.agents/skills/msw/references/match-query-params.md
@@ -0,0 +1,89 @@
+---
+title: Access Query Parameters from Request URL
+impact: MEDIUM-HIGH
+impactDescription: Enables filtering, pagination, and search mocking
+tags: match, query, search-params, url, filtering
+---
+
+## Access Query Parameters from Request URL
+
+Parse query parameters from `request.url` using the `URL` constructor. MSW does not automatically parse query strings, so you must extract them manually.
+
+**Incorrect (assuming params includes query string):**
+
+```typescript
+http.get('/api/users', ({ params }) => {
+ // params does NOT contain query parameters!
+ const page = params.page // undefined
+ return HttpResponse.json([])
+})
+```
+
+**Correct (parse from request.url):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ http.get('/api/users', ({ request }) => {
+ const url = new URL(request.url)
+ const page = url.searchParams.get('page') || '1'
+ const limit = url.searchParams.get('limit') || '10'
+ const search = url.searchParams.get('search')
+
+ // Mock paginated response
+ const pageNum = parseInt(page, 10)
+ const limitNum = parseInt(limit, 10)
+
+ return HttpResponse.json({
+ data: mockUsers.slice((pageNum - 1) * limitNum, pageNum * limitNum),
+ meta: {
+ page: pageNum,
+ limit: limitNum,
+ total: mockUsers.length,
+ },
+ })
+ }),
+
+ // Filtering by query params
+ http.get('/api/products', ({ request }) => {
+ const url = new URL(request.url)
+ const category = url.searchParams.get('category')
+ const minPrice = url.searchParams.get('minPrice')
+ const maxPrice = url.searchParams.get('maxPrice')
+
+ let products = [...mockProducts]
+
+ if (category) {
+ products = products.filter((p) => p.category === category)
+ }
+ if (minPrice) {
+ products = products.filter((p) => p.price >= Number(minPrice))
+ }
+ if (maxPrice) {
+ products = products.filter((p) => p.price <= Number(maxPrice))
+ }
+
+ return HttpResponse.json(products)
+ }),
+]
+```
+
+**Multiple values for same parameter:**
+
+```typescript
+http.get('/api/items', ({ request }) => {
+ const url = new URL(request.url)
+ // /api/items?tag=red&tag=blue&tag=green
+ const tags = url.searchParams.getAll('tag') // ['red', 'blue', 'green']
+
+ return HttpResponse.json(
+ mockItems.filter((item) => tags.some((tag) => item.tags.includes(tag)))
+ )
+})
+```
+
+**When NOT to use this pattern:**
+- Endpoints that don't use query parameters
+
+Reference: [MSW query parameters](https://mswjs.io/docs/http/intercepting-requests/query-parameters)
diff --git a/.agents/skills/msw/references/match-url-patterns.md b/.agents/skills/msw/references/match-url-patterns.md
new file mode 100644
index 0000000..ef096cb
--- /dev/null
+++ b/.agents/skills/msw/references/match-url-patterns.md
@@ -0,0 +1,87 @@
+---
+title: Use URL Path Parameters Correctly
+impact: MEDIUM-HIGH
+impactDescription: Prevents silent handler mismatches; enables dynamic URL matching
+tags: match, url, params, path-parameters, dynamic
+---
+
+## Use URL Path Parameters Correctly
+
+Use `:paramName` syntax for dynamic path segments. Parameters are available in the resolver's `params` object. Incorrect patterns cause handlers to never match.
+
+**Incorrect (literal URL instead of pattern):**
+
+```typescript
+// Only matches exact string "/api/user/123"
+http.get('/api/user/123', () => {
+ return HttpResponse.json({ name: 'John' })
+})
+
+// Request to /api/user/456 is unhandled
+```
+
+**Correct (parameterized URL):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Matches /api/user/123, /api/user/abc, etc.
+ http.get('/api/user/:id', ({ params }) => {
+ return HttpResponse.json({ id: params.id, name: 'John' })
+ }),
+
+ // Multiple parameters
+ http.get('/api/org/:orgId/user/:userId', ({ params }) => {
+ return HttpResponse.json({
+ orgId: params.orgId,
+ userId: params.userId,
+ })
+ }),
+
+ // Optional parameters (use separate handlers)
+ http.get('/api/posts', () => {
+ return HttpResponse.json([{ id: '1' }, { id: '2' }])
+ }),
+ http.get('/api/posts/:postId', ({ params }) => {
+ return HttpResponse.json({ id: params.postId })
+ }),
+]
+```
+
+**Wildcard patterns:**
+
+```typescript
+// Match any path starting with /api/
+http.get('/api/*', () => {
+ return HttpResponse.json({ fallback: true })
+})
+
+// Match any origin with specific path
+http.get('*/api/user', () => {
+ return HttpResponse.json({ name: 'John' })
+})
+
+// Match all requests of a method
+http.get('*', () => {
+ return HttpResponse.json({ catchAll: true })
+})
+```
+
+**Type-safe parameters:**
+
+```typescript
+type UserParams = {
+ userId: string
+}
+
+http.get('/api/user/:userId', ({ params }) => {
+ // params.userId is typed as string
+ return HttpResponse.json({ id: params.userId })
+})
+```
+
+**When NOT to use this pattern:**
+- Exact URL matching for specific endpoints that never vary
+
+Reference: [MSW Request Matching](https://mswjs.io/docs/http/intercepting-requests)
diff --git a/.agents/skills/msw/references/response-custom-headers.md b/.agents/skills/msw/references/response-custom-headers.md
new file mode 100644
index 0000000..e59b273
--- /dev/null
+++ b/.agents/skills/msw/references/response-custom-headers.md
@@ -0,0 +1,125 @@
+---
+title: Set Response Headers Correctly
+impact: HIGH
+impactDescription: Ensures CORS, caching, and authentication headers work as expected
+tags: response, headers, cors, cache-control, authentication
+---
+
+## Set Response Headers Correctly
+
+Set appropriate response headers to simulate real API behavior. Headers like `Set-Cookie`, `Cache-Control`, and CORS headers affect how your application handles responses.
+
+**Incorrect (missing important headers):**
+
+```typescript
+http.post('/api/login', () => {
+ // Missing Set-Cookie header - authentication won't work
+ return HttpResponse.json({ user: { id: '1' } })
+})
+
+http.get('/api/data', () => {
+ // Missing caching headers - can't test cache behavior
+ return HttpResponse.json({ data: 'value' })
+})
+```
+
+**Correct (explicit headers):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // Authentication with cookies
+ http.post('/api/login', () => {
+ return HttpResponse.json(
+ { user: { id: '1', name: 'John' } },
+ {
+ headers: {
+ 'Set-Cookie': 'session=abc123; Path=/; HttpOnly',
+ },
+ }
+ )
+ }),
+
+ // Caching headers
+ http.get('/api/static-data', () => {
+ return HttpResponse.json(
+ { version: '1.0' },
+ {
+ headers: {
+ 'Cache-Control': 'public, max-age=3600',
+ 'ETag': '"abc123"',
+ },
+ }
+ )
+ }),
+
+ // No-cache for dynamic data
+ http.get('/api/user', () => {
+ return HttpResponse.json(
+ { name: 'John' },
+ {
+ headers: {
+ 'Cache-Control': 'no-store',
+ },
+ }
+ )
+ }),
+
+ // Pagination headers
+ http.get('/api/users', () => {
+ return HttpResponse.json(
+ [{ id: '1' }, { id: '2' }],
+ {
+ headers: {
+ 'X-Total-Count': '100',
+ 'X-Page': '1',
+ 'X-Per-Page': '10',
+ 'Link': '; rel="next"',
+ },
+ }
+ )
+ }),
+
+ // Rate limiting headers
+ http.get('/api/limited', () => {
+ return HttpResponse.json(
+ { data: 'value' },
+ {
+ headers: {
+ 'X-RateLimit-Limit': '100',
+ 'X-RateLimit-Remaining': '99',
+ 'X-RateLimit-Reset': String(Date.now() + 3600000),
+ },
+ }
+ )
+ }),
+]
+```
+
+**Testing rate limit handling:**
+
+```typescript
+it('shows rate limit warning when approaching limit', async () => {
+ server.use(
+ http.get('/api/data', () => {
+ return HttpResponse.json(
+ { data: 'value' },
+ {
+ headers: {
+ 'X-RateLimit-Remaining': '5',
+ },
+ }
+ )
+ })
+ )
+
+ render()
+ expect(await screen.findByText('Rate limit warning')).toBeInTheDocument()
+})
+```
+
+**When NOT to use this pattern:**
+- Tests not concerned with header-specific behavior can omit custom headers
+
+Reference: [MSW HttpResponse Options](https://mswjs.io/docs/api/http-response)
diff --git a/.agents/skills/msw/references/response-delay-realistic.md b/.agents/skills/msw/references/response-delay-realistic.md
new file mode 100644
index 0000000..df3bb83
--- /dev/null
+++ b/.agents/skills/msw/references/response-delay-realistic.md
@@ -0,0 +1,92 @@
+---
+title: Add Delays Only for Timing Behavior Under Test
+impact: HIGH
+impactDescription: exercises loading, timeout, cancellation, and race behavior without slowing every test
+tags: response, delay, async, loading, timing
+---
+
+## Add Delays Only for Timing Behavior Under Test
+
+Keep baseline handlers deterministic and fast. Add `delay()` in the specific test or development scenario whose contract includes a loading state, timeout, cancellation, race, or hung request. A random global delay makes tests slower and less reproducible.
+
+**Correct (deterministic baseline handlers):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ http.get('/api/user', () =>
+ HttpResponse.json({ name: 'John' })
+ ),
+]
+```
+
+Override timing in the test that needs it:
+
+```typescript
+import { delay, http, HttpResponse } from 'msw'
+
+it('shows loading while the request is pending', async () => {
+ server.use(
+ http.get('/api/user', async () => {
+ await delay(100)
+ return HttpResponse.json({ name: 'John' })
+ })
+ )
+
+ render()
+
+ expect(screen.getByText('Loading…')).toBeInTheDocument()
+ expect(await screen.findByText('John')).toBeInTheDocument()
+})
+```
+
+**Delay modes:**
+
+```typescript
+// Explicit, reproducible delay - use this when a test needs visible pending time
+await delay(200)
+
+// 'real' / bare delay(): randomized 100-400ms in the browser,
+// but a fixed 5ms under Node, so it will not make a loading state observable there
+await delay('real')
+
+// Infinite delay - simulates a hung request. Under Node this is setTimeout's
+// max int with .unref(), so it will not keep the process alive
+await delay('infinite')
+```
+
+Use `delay('infinite')` only when the test controls cancellation or timeout.
+
+**Incorrect (a global delay applied to every handler):**
+
+```typescript
+import { http, delay } from 'msw'
+
+export const handlers = [
+ // Slows every test in the suite to buy timing realism no assertion depends on
+ http.all('*', async () => {
+ await delay(100)
+ // No return = continue to the next matching handler
+ }),
+
+ http.get('/api/user', () => HttpResponse.json({ name: 'John' })),
+]
+```
+
+Do not use arbitrary delay values to wait in the test itself:
+
+```typescript
+render()
+await new Promise((resolve) => setTimeout(resolve, 200))
+expect(screen.getByText('John')).toBeInTheDocument()
+```
+
+Assert observable state with the testing framework's async utilities instead:
+
+```typescript
+render()
+expect(await screen.findByText('John')).toBeInTheDocument()
+```
+
+Reference: [MSW delay API](https://mswjs.io/docs/api/delay)
diff --git a/.agents/skills/msw/references/response-error-simulation.md b/.agents/skills/msw/references/response-error-simulation.md
new file mode 100644
index 0000000..8d42124
--- /dev/null
+++ b/.agents/skills/msw/references/response-error-simulation.md
@@ -0,0 +1,110 @@
+---
+title: Simulate Error Responses Correctly
+impact: HIGH
+impactDescription: Validates error handling; catches missing error states in UI
+tags: response, error, status, network-error, HttpResponse
+---
+
+## Simulate Error Responses Correctly
+
+Use proper HTTP status codes and `HttpResponse.error()` for network errors. Different error types require different handling in your application, and correct simulation ensures your error handling works.
+
+**Incorrect (ambiguous error responses):**
+
+```typescript
+// Unclear what type of error this represents
+http.get('/api/user', () => {
+ return HttpResponse.json({ error: 'Something went wrong' })
+})
+
+// Missing status code - defaults to 200!
+http.get('/api/user', () => {
+ return new HttpResponse('Error occurred')
+})
+```
+
+**Correct (explicit error types):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+// HTTP 4xx - Client errors
+http.get('/api/user/:id', () => {
+ return HttpResponse.json(
+ { error: 'User not found' },
+ { status: 404 }
+ )
+})
+
+http.post('/api/user', () => {
+ return HttpResponse.json(
+ { error: 'Validation failed', fields: ['email'] },
+ { status: 400 }
+ )
+})
+
+http.get('/api/protected', () => {
+ return HttpResponse.json(
+ { error: 'Unauthorized' },
+ { status: 401 }
+ )
+})
+
+http.get('/api/admin', () => {
+ return HttpResponse.json(
+ { error: 'Forbidden' },
+ { status: 403 }
+ )
+})
+
+// HTTP 5xx - Server errors
+http.get('/api/user', () => {
+ return HttpResponse.json(
+ { error: 'Internal server error' },
+ { status: 500 }
+ )
+})
+
+http.get('/api/data', () => {
+ return new HttpResponse(null, { status: 503 }) // Service unavailable
+})
+
+// Network error (connection failure, DNS failure, etc.)
+http.get('/api/user', () => {
+ return HttpResponse.error() // Causes fetch to reject
+})
+```
+
+**Testing error handling:**
+
+```typescript
+it('displays 404 message when user not found', async () => {
+ server.use(
+ http.get('/api/user/:id', () => {
+ return HttpResponse.json(
+ { error: 'User not found' },
+ { status: 404 }
+ )
+ })
+ )
+
+ render()
+ expect(await screen.findByText('User not found')).toBeInTheDocument()
+})
+
+it('handles network failure gracefully', async () => {
+ server.use(
+ http.get('/api/user', () => {
+ return HttpResponse.error()
+ })
+ )
+
+ render()
+ expect(await screen.findByText('Network error')).toBeInTheDocument()
+})
+```
+
+**When NOT to use this pattern:**
+- Happy path tests should use success responses
+
+Reference: [MSW HttpResponse API](https://mswjs.io/docs/api/http-response)
diff --git a/.agents/skills/msw/references/response-http-response-helpers.md b/.agents/skills/msw/references/response-http-response-helpers.md
new file mode 100644
index 0000000..a5a9408
--- /dev/null
+++ b/.agents/skills/msw/references/response-http-response-helpers.md
@@ -0,0 +1,83 @@
+---
+title: Use HttpResponse Static Methods
+impact: HIGH
+impactDescription: Automatic Content-Type headers; cleaner syntax; type safety
+tags: response, HttpResponse, json, text, xml, helpers
+---
+
+## Use HttpResponse Static Methods
+
+Use `HttpResponse.json()`, `HttpResponse.text()`, and other static methods instead of manually constructing responses. These methods automatically set correct Content-Type headers and provide cleaner, more readable code.
+
+**Incorrect (manual response construction):**
+
+```typescript
+http.get('/api/user', () => {
+ // Verbose, easy to forget Content-Type header
+ return new Response(
+ JSON.stringify({ name: 'John' }),
+ {
+ status: 200,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ }
+ )
+})
+```
+
+**Correct (HttpResponse static methods):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ // JSON - sets Content-Type: application/json automatically
+ http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'John', email: 'john@example.com' })
+ }),
+
+ // JSON with status code
+ http.post('/api/user', () => {
+ return HttpResponse.json(
+ { id: '1', message: 'Created' },
+ { status: 201 }
+ )
+ }),
+
+ // Text - sets Content-Type: text/plain
+ http.get('/api/text', () => {
+ return HttpResponse.text('Hello, World!')
+ }),
+
+ // XML - sets Content-Type: application/xml
+ http.get('/api/xml', () => {
+ return HttpResponse.xml('John')
+ }),
+
+ // HTML - sets Content-Type: text/html
+ http.get('/page', () => {
+ return HttpResponse.html('
Hello
')
+ }),
+
+ // ArrayBuffer for binary data
+ http.get('/api/file', () => {
+ const buffer = new ArrayBuffer(8)
+ return HttpResponse.arrayBuffer(buffer, {
+ headers: { 'Content-Type': 'application/octet-stream' },
+ })
+ }),
+
+ // FormData
+ http.get('/api/form', () => {
+ const form = new FormData()
+ form.append('field', 'value')
+ return HttpResponse.formData(form)
+ }),
+]
+```
+
+**When NOT to use this pattern:**
+- Custom Content-Types not covered by helpers may need manual `new Response()`
+
+Reference: [MSW HttpResponse API](https://mswjs.io/docs/api/http-response)
diff --git a/.agents/skills/msw/references/response-one-time-handlers.md b/.agents/skills/msw/references/response-one-time-handlers.md
new file mode 100644
index 0000000..8d26c55
--- /dev/null
+++ b/.agents/skills/msw/references/response-one-time-handlers.md
@@ -0,0 +1,103 @@
+---
+title: Use One-Time Handlers for Sequential Scenarios
+impact: HIGH
+impactDescription: Models realistic multi-step flows; tests retry logic correctly
+tags: response, once, one-time, sequential, retry
+---
+
+## Use One-Time Handlers for Sequential Scenarios
+
+Use the `{ once: true }` option for handlers that should only respond once, then fall back to the next matching handler. This is essential for testing retry logic, sequential API calls, or state changes between requests.
+
+**Incorrect (permanent override prevents testing retries):**
+
+```typescript
+it('retries after failure', async () => {
+ server.use(
+ http.get('/api/user', () => {
+ return new HttpResponse(null, { status: 500 })
+ })
+ )
+
+ render()
+
+ // Component retries, but always gets 500 - can't test success after retry
+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ // Still failing...
+})
+```
+
+**Correct (one-time handler for first request):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+it('retries after failure and succeeds', async () => {
+ server.use(
+ http.get(
+ '/api/user',
+ () => {
+ return new HttpResponse(null, { status: 500 })
+ },
+ { once: true } // Only affects first request
+ )
+ )
+
+ render()
+
+ // First request fails
+ expect(await screen.findByText('Error loading user')).toBeInTheDocument()
+
+ // Retry succeeds (uses baseline happy-path handler)
+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ expect(await screen.findByText('John')).toBeInTheDocument()
+})
+```
+
+**Sequential state changes:**
+
+```typescript
+it('shows optimistic update then server response', async () => {
+ let callCount = 0
+
+ server.use(
+ http.post('/api/like', () => {
+ callCount++
+ if (callCount === 1) {
+ // First call - slow response simulates network
+ return HttpResponse.json({ likes: 11 })
+ }
+ // Subsequent calls
+ return HttpResponse.json({ likes: 12 })
+ })
+ )
+
+ // Test optimistic update behavior
+})
+```
+
+**Multiple sequential states:**
+
+```typescript
+server.use(
+ // First request: pending
+ http.get('/api/order/:id', () => {
+ return HttpResponse.json({ status: 'pending' })
+ }, { once: true }),
+
+ // Second request: processing
+ http.get('/api/order/:id', () => {
+ return HttpResponse.json({ status: 'processing' })
+ }, { once: true }),
+
+ // Third+ requests: completed
+ http.get('/api/order/:id', () => {
+ return HttpResponse.json({ status: 'completed' })
+ })
+)
+```
+
+**When NOT to use this pattern:**
+- Single-state tests that don't involve retries or polling
+
+Reference: [Network Behavior Overrides](https://mswjs.io/docs/best-practices/network-behavior-overrides)
diff --git a/.agents/skills/msw/references/response-streaming.md b/.agents/skills/msw/references/response-streaming.md
new file mode 100644
index 0000000..3d82862
--- /dev/null
+++ b/.agents/skills/msw/references/response-streaming.md
@@ -0,0 +1,114 @@
+---
+title: Mock Streaming Responses with ReadableStream
+impact: HIGH
+impactDescription: Tests streaming UIs, chat interfaces, and progressive loading
+tags: response, streaming, ReadableStream, sse, progressive
+---
+
+## Mock Streaming Responses with ReadableStream
+
+Use `ReadableStream` to mock streaming responses for Server-Sent Events (SSE), chunked transfers, or streaming APIs. This enables testing of real-time features and progressive UI updates.
+
+**Incorrect (returning complete response immediately):**
+
+```typescript
+// Chat response arrives all at once - doesn't test streaming UI
+http.post('/api/chat', () => {
+ return HttpResponse.json({
+ message: 'Here is the complete response all at once',
+ })
+})
+```
+
+**Correct (streaming response):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+// Text streaming (like AI chat)
+http.post('/api/chat', () => {
+ const encoder = new TextEncoder()
+ const chunks = ['Hello', ' ', 'world', '!']
+
+ const stream = new ReadableStream({
+ async start(controller) {
+ for (const chunk of chunks) {
+ controller.enqueue(encoder.encode(chunk))
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ controller.close()
+ },
+ })
+
+ return new HttpResponse(stream, {
+ headers: {
+ 'Content-Type': 'text/plain',
+ 'Transfer-Encoding': 'chunked',
+ },
+ })
+})
+```
+
+**Server-Sent Events (SSE):**
+
+```typescript
+http.get('/api/events', () => {
+ const encoder = new TextEncoder()
+ const events = [
+ { id: '1', data: { message: 'First event' } },
+ { id: '2', data: { message: 'Second event' } },
+ { id: '3', data: { message: 'Third event' } },
+ ]
+
+ const stream = new ReadableStream({
+ async start(controller) {
+ for (const event of events) {
+ const sseMessage = `id: ${event.id}\ndata: ${JSON.stringify(event.data)}\n\n`
+ controller.enqueue(encoder.encode(sseMessage))
+ await new Promise((resolve) => setTimeout(resolve, 200))
+ }
+ controller.close()
+ },
+ })
+
+ return new HttpResponse(stream, {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ },
+ })
+})
+```
+
+**JSON streaming (newline-delimited):**
+
+```typescript
+http.get('/api/stream-json', () => {
+ const encoder = new TextEncoder()
+ const items = [
+ { id: 1, name: 'Item 1' },
+ { id: 2, name: 'Item 2' },
+ { id: 3, name: 'Item 3' },
+ ]
+
+ const stream = new ReadableStream({
+ async start(controller) {
+ for (const item of items) {
+ controller.enqueue(encoder.encode(JSON.stringify(item) + '\n'))
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ controller.close()
+ },
+ })
+
+ return new HttpResponse(stream, {
+ headers: { 'Content-Type': 'application/x-ndjson' },
+ })
+})
+```
+
+**When NOT to use this pattern:**
+- APIs that return complete responses don't need streaming mocks
+
+Reference: [MSW ReadableStream Support](https://mswjs.io/blog/introducing-msw-2.0)
diff --git a/.agents/skills/msw/references/setup-lifecycle-hooks.md b/.agents/skills/msw/references/setup-lifecycle-hooks.md
new file mode 100644
index 0000000..9c6269d
--- /dev/null
+++ b/.agents/skills/msw/references/setup-lifecycle-hooks.md
@@ -0,0 +1,57 @@
+---
+title: Configure Server Lifecycle in Test Setup
+impact: CRITICAL
+impactDescription: Prevents handler leakage and ensures test isolation; eliminates flaky tests
+tags: setup, lifecycle, vitest, jest, beforeAll, afterEach
+---
+
+## Configure Server Lifecycle in Test Setup
+
+Server lifecycle hooks must be configured in test setup files to ensure proper initialization, cleanup between tests, and graceful shutdown. Missing hooks cause handler pollution and unpredictable test behavior.
+
+**Incorrect (no lifecycle management):**
+
+```typescript
+// handlers.test.ts
+import { server } from './mocks/node'
+
+// Server never started, handlers never reset
+// Tests may pass/fail randomly depending on execution order
+it('fetches user', async () => {
+ const response = await fetch('/user')
+ // This fails silently - no mocking active
+})
+```
+
+**Correct (proper lifecycle hooks):**
+
+```typescript
+// vitest.setup.ts or setupTests.ts
+import { beforeAll, afterEach, afterAll } from 'vitest'
+import { server } from './mocks/node'
+
+// Start server before all tests
+beforeAll(() => server.listen())
+
+// Reset handlers after each test to ensure isolation
+afterEach(() => server.resetHandlers())
+
+// Clean shutdown after all tests complete
+afterAll(() => server.close())
+```
+
+**Jest equivalent:**
+
+```typescript
+// setupTests.ts
+import { server } from './mocks/node'
+
+beforeAll(() => server.listen())
+afterEach(() => server.resetHandlers())
+afterAll(() => server.close())
+```
+
+**When NOT to use this pattern:**
+- Browser-based tests use `worker.start()` and `worker.stop()` instead
+
+Reference: [MSW Quick Start - Test Setup](https://mswjs.io/docs/quick-start)
diff --git a/.agents/skills/msw/references/setup-node-version.md b/.agents/skills/msw/references/setup-node-version.md
new file mode 100644
index 0000000..ffec58c
--- /dev/null
+++ b/.agents/skills/msw/references/setup-node-version.md
@@ -0,0 +1,72 @@
+---
+title: Require Node.js 18+ for MSW v2
+impact: CRITICAL
+impactDescription: MSW v2 requires Node 18+; older versions cause complete failure
+tags: setup, node, version, requirements, compatibility
+---
+
+## Require Node.js 18+ for MSW v2
+
+MSW v2 sets Node.js 18.0.0 as the minimum supported version. Older versions lack native `fetch` and other required APIs, causing complete mocking failure.
+
+**Incorrect (using unsupported Node version):**
+
+```json
+// package.json
+{
+ "engines": {
+ "node": ">=14.0.0"
+ }
+}
+```
+
+```bash
+# Node 16 - MSW v2 fails silently or throws cryptic errors
+$ node -v
+v16.20.0
+
+$ npm test
+# ReferenceError: fetch is not defined
+# or: Cannot read properties of undefined
+```
+
+**Correct (enforce Node 18+ requirement):**
+
+```json
+// package.json
+{
+ "engines": {
+ "node": ">=18.0.0"
+ }
+}
+```
+
+```yaml
+# .nvmrc
+18
+```
+
+```yaml
+# CI configuration (GitHub Actions)
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ node-version: [18, 20, 22]
+```
+
+**Verify installation:**
+
+```bash
+# Check Node version
+node -v # Should be v18.x.x or higher
+
+# Check MSW version
+npm ls msw # Should be v2.x.x
+```
+
+**When NOT to use this pattern:**
+- If stuck on Node 16, use MSW v1.x instead (with different API patterns)
+
+Reference: [MSW v2 Migration - Requirements](https://mswjs.io/docs/migrations/1.x-to-2.x/)
diff --git a/.agents/skills/msw/references/setup-server-node-entrypoint.md b/.agents/skills/msw/references/setup-server-node-entrypoint.md
new file mode 100644
index 0000000..36abfbe
--- /dev/null
+++ b/.agents/skills/msw/references/setup-server-node-entrypoint.md
@@ -0,0 +1,45 @@
+---
+title: Use Correct Entrypoint for Node.js
+impact: CRITICAL
+impactDescription: Zero mocking if wrong entrypoint; 100% test failures
+tags: setup, entrypoint, node, server, msw-node
+---
+
+## Use Correct Entrypoint for Node.js
+
+MSW v2 separates browser and Node.js entrypoints. Using the wrong import causes complete mocking failure with no interception occurring.
+
+**Incorrect (importing from wrong path):**
+
+```typescript
+// This imports browser code into Node.js - mocking silently fails
+import { setupServer } from 'msw'
+import { setupWorker } from 'msw'
+
+const server = setupServer(...handlers)
+```
+
+**Correct (using msw/node entrypoint):**
+
+```typescript
+// Node.js environments (tests, SSR) use msw/node
+import { setupServer } from 'msw/node'
+import { handlers } from './handlers'
+
+export const server = setupServer(...handlers)
+```
+
+**Browser environments use msw/browser:**
+
+```typescript
+// Browser environments use msw/browser
+import { setupWorker } from 'msw/browser'
+import { handlers } from './handlers'
+
+export const worker = setupWorker(...handlers)
+```
+
+**When NOT to use this pattern:**
+- Never deviate from this pattern; entrypoint selection is binary based on environment
+
+Reference: [MSW Node.js Integration](https://mswjs.io/docs/integrations/node)
diff --git a/.agents/skills/msw/references/setup-typescript-config.md b/.agents/skills/msw/references/setup-typescript-config.md
new file mode 100644
index 0000000..b609e97
--- /dev/null
+++ b/.agents/skills/msw/references/setup-typescript-config.md
@@ -0,0 +1,74 @@
+---
+title: Configure TypeScript for MSW v2
+impact: CRITICAL
+impactDescription: TypeScript 4.8+ required; incorrect config causes type errors
+tags: setup, typescript, configuration, types, compiler
+---
+
+## Configure TypeScript for MSW v2
+
+MSW v2 requires TypeScript 4.8+ for proper type inference. Incorrect TypeScript configuration causes confusing type errors and prevents proper handler typing.
+
+**Incorrect (outdated TypeScript or missing config):**
+
+```json
+// tsconfig.json - missing moduleResolution
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext"
+ // No moduleResolution - imports fail to resolve
+ }
+}
+```
+
+```typescript
+// Type errors due to incorrect resolution
+import { http, HttpResponse } from 'msw'
+// Error: Cannot find module 'msw' or its corresponding type declarations
+```
+
+**Correct (proper TypeScript configuration):**
+
+```json
+// tsconfig.json
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler", // or "node16" / "nodenext"
+ "esModuleInterop": true,
+ "strict": true,
+ "skipLibCheck": true
+ }
+}
+```
+
+**Typed handlers with proper inference:**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+
+interface User {
+ id: string
+ name: string
+ email: string
+}
+
+export const handlers = [
+ http.get('/api/user/:id', ({ params }) => {
+ // params.id is typed as string
+ return HttpResponse.json({
+ id: params.id,
+ name: 'John Doe',
+ email: 'john@example.com',
+ })
+ }),
+]
+```
+
+**When NOT to use this pattern:**
+- JavaScript-only projects don't need TypeScript configuration
+- Projects using older bundlers may need `moduleResolution: "node"`
+
+Reference: [MSW v2 Migration - TypeScript](https://mswjs.io/docs/migrations/1.x-to-2.x/)
diff --git a/.agents/skills/msw/references/setup-unhandled-requests.md b/.agents/skills/msw/references/setup-unhandled-requests.md
new file mode 100644
index 0000000..69f3bf8
--- /dev/null
+++ b/.agents/skills/msw/references/setup-unhandled-requests.md
@@ -0,0 +1,70 @@
+---
+title: Configure Unhandled Request Behavior
+impact: CRITICAL
+impactDescription: Catches missing handlers immediately; prevents silent test failures
+tags: setup, unhandled, error, configuration, onUnhandledRequest
+---
+
+## Configure Unhandled Request Behavior
+
+Configure `onUnhandledRequest: 'error'` to fail tests when requests lack handlers. This catches missing mocks immediately instead of allowing silent network calls or undefined behavior.
+
+**Incorrect (default silent behavior):**
+
+```typescript
+// mocks/node.ts
+import { setupServer } from 'msw/node'
+import { handlers } from './handlers'
+
+// Default behavior: warns but doesn't fail
+// Unhandled requests may hit real APIs or return undefined
+export const server = setupServer(...handlers)
+```
+
+```typescript
+// Test passes despite missing handler - false positive!
+it('submits form', async () => {
+ await submitForm({ email: 'test@example.com' })
+ // POST /submit has no handler but test doesn't fail
+ expect(screen.getByText('Success')).toBeInTheDocument()
+})
+```
+
+**Correct (strict unhandled request handling):**
+
+```typescript
+// vitest.setup.ts
+import { server } from './mocks/node'
+
+beforeAll(() => {
+ server.listen({
+ onUnhandledRequest: 'error', // Fail on any unhandled request
+ })
+})
+
+afterEach(() => server.resetHandlers())
+afterAll(() => server.close())
+```
+
+**Custom handling for specific URLs:**
+
+```typescript
+beforeAll(() => {
+ server.listen({
+ onUnhandledRequest(request, print) {
+ // Allow certain requests through (e.g., static assets)
+ if (request.url.includes('/static/')) {
+ return
+ }
+ // Error on all other unhandled requests
+ print.error()
+ },
+ })
+})
+```
+
+**When NOT to use this pattern:**
+- Development environments may prefer `'warn'` for less disruptive feedback
+- Integration tests that intentionally hit real endpoints
+
+Reference: [MSW Best Practices - Avoid Request Assertions](https://mswjs.io/docs/best-practices/avoid-request-assertions/)
diff --git a/.agents/skills/msw/references/setup-worker-script-commit.md b/.agents/skills/msw/references/setup-worker-script-commit.md
new file mode 100644
index 0000000..ad9a013
--- /dev/null
+++ b/.agents/skills/msw/references/setup-worker-script-commit.md
@@ -0,0 +1,65 @@
+---
+title: Commit Worker Script to Version Control
+impact: CRITICAL
+impactDescription: Eliminates setup friction for team members; prevents CI failures
+tags: setup, worker, git, mockServiceWorker, browser
+---
+
+## Commit Worker Script to Version Control
+
+The `mockServiceWorker.js` file generated by `msw init` should be committed to Git. This ensures team members and CI environments can run browser tests without additional setup commands.
+
+**Incorrect (gitignoring worker script):**
+
+```gitignore
+# .gitignore
+# This forces every developer to run msw init manually
+public/mockServiceWorker.js
+```
+
+```bash
+# New team member clones repo, runs tests, gets cryptic errors
+# because worker script doesn't exist
+npm test
+# Error: Cannot find mockServiceWorker.js
+```
+
+**Correct (commit and auto-update worker script):**
+
+```bash
+# Generate worker script with --save flag
+npx msw init public/ --save
+```
+
+```json
+// package.json - auto-updates worker on msw version changes
+{
+ "msw": {
+ "workerDirectory": ["public"]
+ }
+}
+```
+
+```gitignore
+# .gitignore - do NOT ignore the worker script
+# public/mockServiceWorker.js <- remove this line
+```
+
+**Monorepo configuration:**
+
+```json
+// Root package.json for monorepos
+{
+ "msw": {
+ "workerDirectory": [
+ "apps/web/public",
+ "apps/admin/public"
+ ]
+ }
+}
+```
+
+**When NOT to use this pattern:**
+- If treating as generated artifact, ensure CI runs `msw init` before tests
+
+Reference: [Managing the Worker](https://mswjs.io/docs/best-practices/managing-the-worker/)
diff --git a/.agents/skills/msw/references/test-async-utilities.md b/.agents/skills/msw/references/test-async-utilities.md
new file mode 100644
index 0000000..d228a71
--- /dev/null
+++ b/.agents/skills/msw/references/test-async-utilities.md
@@ -0,0 +1,81 @@
+---
+title: Use Async Testing Utilities for Mock Responses
+impact: HIGH
+impactDescription: Prevents race conditions; ensures responses arrive before assertions
+tags: test, async, waitFor, findBy, testing-library, race-condition
+---
+
+## Use Async Testing Utilities for Mock Responses
+
+Use async testing utilities (`findBy`, `waitFor`) instead of `getBy` or manual `setTimeout` when testing components that make API calls. Mock responses are asynchronous, and synchronous assertions will fail before data arrives.
+
+**Incorrect (synchronous assertions):**
+
+```typescript
+it('displays user name', () => {
+ render()
+
+ // Fails! Response hasn't arrived yet
+ expect(screen.getByText('John')).toBeInTheDocument()
+})
+
+// Also incorrect - arbitrary timeout
+it('displays user name', async () => {
+ render()
+
+ await new Promise((resolve) => setTimeout(resolve, 100))
+
+ // Flaky - 100ms might not be enough, or wastes time if faster
+ expect(screen.getByText('John')).toBeInTheDocument()
+})
+```
+
+**Correct (async testing utilities):**
+
+```typescript
+import { render, screen, waitFor } from '@testing-library/react'
+
+it('displays user name', async () => {
+ render()
+
+ // findBy* returns a promise that resolves when element appears
+ expect(await screen.findByText('John')).toBeInTheDocument()
+})
+
+// For non-element assertions, use waitFor
+it('updates document title', async () => {
+ render()
+
+ await waitFor(() => {
+ expect(document.title).toBe('John - Profile')
+ })
+})
+
+// For multiple elements
+it('displays user list', async () => {
+ render()
+
+ const users = await screen.findAllByRole('listitem')
+ expect(users).toHaveLength(3)
+})
+```
+
+**With loading states:**
+
+```typescript
+it('shows loading then content', async () => {
+ render()
+
+ // Loading state appears immediately
+ expect(screen.getByText('Loading...')).toBeInTheDocument()
+
+ // Content replaces loading after response
+ expect(await screen.findByText('John')).toBeInTheDocument()
+ expect(screen.queryByText('Loading...')).not.toBeInTheDocument()
+})
+```
+
+**When NOT to use this pattern:**
+- Synchronous operations that don't involve API calls can use `getBy`
+
+Reference: [Testing Library Async Methods](https://testing-library.com/docs/dom-testing-library/api-async/)
diff --git a/.agents/skills/msw/references/test-avoid-request-assertions.md b/.agents/skills/msw/references/test-avoid-request-assertions.md
new file mode 100644
index 0000000..159a84c
--- /dev/null
+++ b/.agents/skills/msw/references/test-avoid-request-assertions.md
@@ -0,0 +1,87 @@
+---
+title: Avoid Direct Request Assertions
+impact: HIGH
+impactDescription: Tests implementation details; breaks on refactors that preserve behavior
+tags: test, assertions, anti-pattern, implementation-details, behavior
+---
+
+## Avoid Direct Request Assertions
+
+Do not assert that specific requests were made with specific parameters. This tests implementation details rather than behavior. Instead, assert on your application's reaction to responses.
+
+**Incorrect (asserting request details):**
+
+```typescript
+it('sends correct data when creating user', async () => {
+ const requestSpy = vi.fn()
+
+ server.use(
+ http.post('/api/user', async ({ request }) => {
+ requestSpy(await request.json())
+ return HttpResponse.json({ id: '1' })
+ })
+ )
+
+ await createUser({ name: 'John', email: 'john@example.com' })
+
+ // Testing implementation details - what if we add a field?
+ expect(requestSpy).toHaveBeenCalledWith({
+ name: 'John',
+ email: 'john@example.com',
+ })
+})
+```
+
+**Correct (assert behavior through responses):**
+
+```typescript
+it('creates user and shows success message', async () => {
+ server.use(
+ http.post('/api/user', async ({ request }) => {
+ const body = await request.json()
+ // Validate in handler - returns error if invalid
+ if (!body.email) {
+ return HttpResponse.json(
+ { error: 'Email required' },
+ { status: 400 }
+ )
+ }
+ return HttpResponse.json({ id: '1', ...body }, { status: 201 })
+ })
+ )
+
+ render()
+ await userEvent.type(screen.getByLabelText('Name'), 'John')
+ await userEvent.type(screen.getByLabelText('Email'), 'john@example.com')
+ await userEvent.click(screen.getByRole('button', { name: 'Create' }))
+
+ // Assert application behavior, not request details
+ expect(await screen.findByText('User created!')).toBeInTheDocument()
+})
+```
+
+**For one-way requests (analytics, logging):**
+
+```typescript
+import { server } from './mocks/node'
+
+it('tracks page view', async () => {
+ const trackingPromise = new Promise((resolve) => {
+ server.events.on('request:end', ({ request }) => {
+ if (request.url.includes('/analytics')) {
+ resolve()
+ }
+ })
+ })
+
+ render()
+
+ // Verify the request was made without asserting payload
+ await expect(trackingPromise).resolves.toBeUndefined()
+})
+```
+
+**When NOT to use this pattern:**
+- Analytics/telemetry testing may require request payload verification via lifecycle events
+
+Reference: [Avoid Request Assertions](https://mswjs.io/docs/best-practices/avoid-request-assertions/)
diff --git a/.agents/skills/msw/references/test-clear-request-cache.md b/.agents/skills/msw/references/test-clear-request-cache.md
new file mode 100644
index 0000000..8f62502
--- /dev/null
+++ b/.agents/skills/msw/references/test-clear-request-cache.md
@@ -0,0 +1,85 @@
+---
+title: Clear Request Library Caches Between Tests
+impact: HIGH
+impactDescription: Prevents stale cached responses; ensures fresh mock data per test
+tags: test, cache, swr, react-query, tanstack-query, isolation
+---
+
+## Clear Request Library Caches Between Tests
+
+Clear data fetching library caches between tests. Libraries like SWR, TanStack Query, and Apollo cache responses, causing tests to receive stale data from previous tests instead of fresh mocked responses.
+
+**Incorrect (cached data leaks between tests):**
+
+```typescript
+// test-a.spec.ts
+it('displays original user', async () => {
+ // Response cached by SWR/React Query
+ render()
+ expect(await screen.findByText('John')).toBeInTheDocument()
+})
+
+// test-b.spec.ts
+it('displays updated user', async () => {
+ server.use(
+ http.get('/api/user', () => {
+ return HttpResponse.json({ name: 'Jane' }) // Different user
+ })
+ )
+ render()
+ // FAILS! Cache returns 'John' from previous test
+ expect(await screen.findByText('Jane')).toBeInTheDocument()
+})
+```
+
+**Correct (clear caches in test setup):**
+
+```typescript
+// SWR cache clearing
+import { cache } from 'swr'
+
+afterEach(() => {
+ // Clear SWR cache
+ cache.clear()
+})
+```
+
+```typescript
+// TanStack Query cache clearing
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+
+const createTestQueryClient = () =>
+ new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, gcTime: 0 },
+ },
+ })
+
+const renderWithClient = (ui: React.ReactElement) => {
+ const testQueryClient = createTestQueryClient()
+ return render(
+ {ui}
+ )
+}
+
+// Each test gets fresh QueryClient with no cached data
+it('displays user', async () => {
+ renderWithClient()
+ expect(await screen.findByText('John')).toBeInTheDocument()
+})
+```
+
+```typescript
+// Apollo Client cache clearing
+import { ApolloClient, InMemoryCache } from '@apollo/client'
+
+afterEach(async () => {
+ await client.clearStore()
+ // or client.resetStore() to refetch active queries
+})
+```
+
+**When NOT to use this pattern:**
+- Tests intentionally verifying cache behavior should not clear caches
+
+Reference: [MSW Debugging Runbook](https://mswjs.io/docs/runbook/)
diff --git a/.agents/skills/msw/references/test-concurrent-boundary.md b/.agents/skills/msw/references/test-concurrent-boundary.md
new file mode 100644
index 0000000..6735330
--- /dev/null
+++ b/.agents/skills/msw/references/test-concurrent-boundary.md
@@ -0,0 +1,88 @@
+---
+title: Use server.boundary() for Concurrent Tests
+impact: HIGH
+impactDescription: Enables parallel test execution; prevents cross-test handler pollution
+tags: test, concurrent, boundary, isolation, parallel
+---
+
+## Use server.boundary() for Concurrent Tests
+
+Wrap concurrent tests in `server.boundary()` to isolate handler overrides. Without boundaries, concurrent tests share handlers, causing race conditions and unpredictable failures.
+
+**Incorrect (concurrent tests without boundaries):**
+
+```typescript
+// Tests run in parallel - handlers leak between them
+it.concurrent('fetches user', async () => {
+ // Uses initial handlers
+ const response = await fetch('https://api.example.com/user')
+ expect(response.ok).toBe(true)
+})
+
+it.concurrent('handles error', async () => {
+ server.use(
+ http.get('https://api.example.com/user', () => {
+ return new HttpResponse(null, { status: 500 })
+ })
+ )
+ // This override might affect the other concurrent test!
+ const response = await fetch('https://api.example.com/user')
+ expect(response.status).toBe(500)
+})
+```
+
+**Correct (boundary-isolated concurrent tests):**
+
+```typescript
+import { http, HttpResponse } from 'msw'
+import { setupServer } from 'msw/node'
+
+const server = setupServer(
+ http.get('https://api.example.com/user', () => {
+ return HttpResponse.json({ name: 'John' })
+ })
+)
+
+beforeAll(() => server.listen())
+afterAll(() => server.close())
+
+it.concurrent(
+ 'fetches user',
+ server.boundary(async () => {
+ const response = await fetch('https://api.example.com/user')
+ const user = await response.json()
+ expect(user).toEqual({ name: 'John' })
+ })
+)
+
+it.concurrent(
+ 'handles server error',
+ server.boundary(async () => {
+ // Override is scoped to this boundary only
+ server.use(
+ http.get('https://api.example.com/user', () => {
+ return new HttpResponse(null, { status: 500 })
+ })
+ )
+ const response = await fetch('https://api.example.com/user')
+ expect(response.status).toBe(500)
+ })
+)
+
+it.concurrent(
+ 'handles network error',
+ server.boundary(async () => {
+ server.use(
+ http.get('https://api.example.com/user', () => {
+ return HttpResponse.error()
+ })
+ )
+ await expect(fetch('https://api.example.com/user')).rejects.toThrow()
+ })
+)
+```
+
+**When NOT to use this pattern:**
+- Sequential tests (non-concurrent) can use standard `afterEach` reset pattern
+
+Reference: [server.boundary() API](https://mswjs.io/docs/api/setup-server/boundary)
diff --git a/.agents/skills/msw/references/test-fake-timers-config.md b/.agents/skills/msw/references/test-fake-timers-config.md
new file mode 100644
index 0000000..1dbca38
--- /dev/null
+++ b/.agents/skills/msw/references/test-fake-timers-config.md
@@ -0,0 +1,91 @@
+---
+title: Configure Fake Timers to Preserve queueMicrotask
+impact: HIGH
+impactDescription: Prevents request body parsing from hanging indefinitely
+tags: test, timers, jest, vitest, queueMicrotask, fake-timers
+---
+
+## Configure Fake Timers to Preserve queueMicrotask
+
+When using fake timers, configure them to not mock `queueMicrotask`. The global `fetch` uses `queueMicrotask` internally for body parsing, and mocking it causes `request.json()` and similar methods to hang forever.
+
+**Incorrect (default fake timers):**
+
+```typescript
+// vitest.config.ts or jest.config.js
+beforeEach(() => {
+ vi.useFakeTimers() // Mocks ALL timer functions including queueMicrotask
+})
+
+// Test hangs indefinitely
+it('parses request body', async () => {
+ server.use(
+ http.post('/api/user', async ({ request }) => {
+ const body = await request.json() // Never resolves!
+ return HttpResponse.json(body)
+ })
+ )
+
+ await fetch('/api/user', {
+ method: 'POST',
+ body: JSON.stringify({ name: 'John' }),
+ })
+})
+```
+
+**Correct (exclude queueMicrotask from fake timers):**
+
+```typescript
+// Vitest
+beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: [
+ 'setTimeout',
+ 'setInterval',
+ 'clearTimeout',
+ 'clearInterval',
+ 'setImmediate',
+ 'clearImmediate',
+ 'Date',
+ ],
+ // queueMicrotask is NOT in the list - remains real
+ })
+})
+
+// Or more explicitly with shouldAdvanceTime
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+})
+```
+
+```typescript
+// Jest
+beforeEach(() => {
+ jest.useFakeTimers({
+ doNotFake: ['queueMicrotask'], // Explicitly preserve queueMicrotask
+ })
+})
+```
+
+**Alternative - advance timers after async operations:**
+
+```typescript
+it('handles delayed response', async () => {
+ vi.useFakeTimers()
+
+ const fetchPromise = fetch('/api/user')
+
+ // Advance timers to allow microtasks to process
+ await vi.runAllTimersAsync()
+
+ const response = await fetchPromise
+ expect(response.ok).toBe(true)
+
+ vi.useRealTimers()
+})
+```
+
+**When NOT to use this pattern:**
+- If not using fake timers, this configuration is unnecessary
+
+Reference: [MSW Debugging Runbook](https://mswjs.io/docs/runbook/)
diff --git a/.agents/skills/msw/references/test-jsdom-environment.md b/.agents/skills/msw/references/test-jsdom-environment.md
new file mode 100644
index 0000000..de100b0
--- /dev/null
+++ b/.agents/skills/msw/references/test-jsdom-environment.md
@@ -0,0 +1,67 @@
+---
+title: Use Correct JSDOM Environment for Jest
+impact: HIGH
+impactDescription: Prevents Node.js global conflicts; ensures proper fetch availability
+tags: test, jest, jsdom, environment, configuration
+---
+
+## Use Correct JSDOM Environment for Jest
+
+Use `jest-fixed-jsdom` instead of `jest-environment-jsdom` when testing with MSW in Jest. Standard JSDOM uses browser export conditions but runs in Node.js, causing conflicts with MSW's entrypoints.
+
+**Incorrect (standard jsdom environment):**
+
+```javascript
+// jest.config.js
+module.exports = {
+ testEnvironment: 'jsdom', // Uses browser exports incorrectly
+}
+```
+
+```typescript
+// Tests fail with cryptic errors
+// TypeError: Cannot read properties of undefined
+// or: fetch is not defined
+```
+
+**Correct (use jest-fixed-jsdom):**
+
+```bash
+npm install -D jest-fixed-jsdom
+```
+
+```javascript
+// jest.config.js
+module.exports = {
+ testEnvironment: 'jest-fixed-jsdom',
+}
+```
+
+**Alternative - migrate to Vitest:**
+
+```typescript
+// vitest.config.ts
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ environment: 'jsdom', // Vitest handles this correctly
+ setupFiles: ['./vitest.setup.ts'],
+ },
+})
+```
+
+**Why this matters:**
+
+JSDOM uses browser export conditions by default, causing packages like MSW to use browser-specific code in a Node.js context. This leads to:
+- Missing Node.js globals
+- Incorrect module resolution
+- Silent failures or cryptic errors
+
+`jest-fixed-jsdom` and Vitest correctly handle the Node.js/browser boundary.
+
+**When NOT to use this pattern:**
+- Vitest users don't need this; Vitest handles environments correctly
+- Node-only tests (no DOM) should use `testEnvironment: 'node'`
+
+Reference: [MSW v2 Migration - Jest/JSDOM](https://mswjs.io/docs/migrations/1.x-to-2.x/)
diff --git a/.agents/skills/msw/references/test-reset-handlers.md b/.agents/skills/msw/references/test-reset-handlers.md
new file mode 100644
index 0000000..3831bce
--- /dev/null
+++ b/.agents/skills/msw/references/test-reset-handlers.md
@@ -0,0 +1,63 @@
+---
+title: Reset Handlers After Each Test
+impact: HIGH
+impactDescription: Prevents handler pollution; eliminates test order dependencies
+tags: test, reset, isolation, afterEach, resetHandlers
+---
+
+## Reset Handlers After Each Test
+
+Call `server.resetHandlers()` in `afterEach` to remove runtime handlers added during tests. Without reset, handlers from one test can affect subsequent tests, causing mysterious failures that depend on test execution order.
+
+**Incorrect (no handler reset):**
+
+```typescript
+// test-a.spec.ts
+it('handles server error', () => {
+ server.use(
+ http.get('/api/user', () => new HttpResponse(null, { status: 500 }))
+ )
+ // Test passes...
+})
+
+// test-b.spec.ts - runs after test-a
+it('displays user name', () => {
+ // FAILS! Still receiving 500 error from test-a's handler
+ render()
+ expect(screen.getByText('John')).toBeInTheDocument()
+})
+```
+
+**Correct (reset in afterEach):**
+
+```typescript
+// vitest.setup.ts
+import { server } from './mocks/node'
+
+beforeAll(() => server.listen())
+afterEach(() => server.resetHandlers()) // Clean slate for each test
+afterAll(() => server.close())
+```
+
+```typescript
+// user.test.ts
+it('handles server error', () => {
+ server.use(
+ http.get('/api/user', () => new HttpResponse(null, { status: 500 }))
+ )
+ render()
+ expect(screen.getByRole('alert')).toHaveTextContent('Error')
+})
+// Handler is removed after this test completes
+
+it('displays user name', () => {
+ // Uses baseline happy-path handler
+ render()
+ expect(screen.getByText('John')).toBeInTheDocument()
+})
+```
+
+**When NOT to use this pattern:**
+- `server.boundary()` provides automatic isolation for concurrent tests
+
+Reference: [Network Behavior Overrides](https://mswjs.io/docs/best-practices/network-behavior-overrides)
diff --git a/.agents/skills/nextjs/SKILL.md b/.agents/skills/nextjs/SKILL.md
new file mode 100644
index 0000000..40ddc37
--- /dev/null
+++ b/.agents/skills/nextjs/SKILL.md
@@ -0,0 +1,115 @@
+---
+name: nextjs
+description: Next.js 16 App Router caching and routing.
+---
+
+# Next.js Community Next.js 16 App Router Best Practices
+
+Comprehensive performance optimization guide for Next.js 16 App Router applications, maintained by the Next.js Community. Contains 42 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation. Two rules cover Next.js 16.3 preview features (Instant Navigations, Partial Prefetching), gated behind `cacheComponents` and `partialPrefetching`.
+
+## When to Apply
+
+Reference these guidelines when:
+- Writing new Next.js 16 App Router code
+- Configuring caching strategies with 'use cache' directive
+- Implementing server components and data fetching
+- Setting up routing with parallel and intercepting routes
+- Creating server actions for form handling and mutations
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Build & Bundle Optimization | CRITICAL | `build-` |
+| 2 | Caching Strategy | CRITICAL | `cache-` |
+| 3 | Server Components & Data Fetching | HIGH | `server-` |
+| 4 | Routing & Navigation | HIGH | `route-` |
+| 5 | Server Actions & Mutations | MEDIUM-HIGH | `action-` |
+| 6 | Streaming & Loading States | MEDIUM | `stream-` |
+| 7 | Metadata & SEO | MEDIUM | `meta-` |
+| 8 | Client Components | LOW-MEDIUM | `client-` |
+
+## Quick Reference
+
+### 1. Build & Bundle Optimization (CRITICAL)
+
+- `build-optimize-package-imports` - Configure optimizePackageImports for Icon Libraries
+- `build-dynamic-imports` - Use Dynamic Imports for Heavy Components
+- `build-barrel-files` - Avoid Barrel File Imports in App Router
+- `build-turbopack-config` - Configure Turbopack at the top level
+- `build-external-packages` - Configure Server External Packages for Node Dependencies
+
+### 2. Caching Strategy (CRITICAL)
+
+- `cache-use-cache-directive` - Use 'use cache' with Cache Components
+- `cache-revalidate-tag` - Use revalidateTag with cacheLife Profiles
+- `cache-fetch-options` - Configure Fetch Cache Options Explicitly
+- `cache-revalidate-path` - Use revalidatePath for Route-Level Cache Invalidation
+- `cache-react-cache` - Use React cache() for Request Deduplication
+- `cache-segment-config` - Match route configuration to the active cache model
+
+### 3. Server Components & Data Fetching (HIGH)
+
+- `server-parallel-fetching` - Fetch Data in Parallel in Server Components
+- `server-component-streaming` - Stream Server Components for Progressive Loading
+- `server-data-colocation` - Colocate Data Fetching with Components
+- `server-preload-pattern` - Use Preload Pattern for Critical Data
+- `server-avoid-client-fetching` - Avoid Client-Side Data Fetching for Initial Data
+- `server-error-handling` - Handle Server Component Errors Gracefully
+
+### 4. Routing & Navigation (HIGH)
+
+- `route-parallel-routes` - Use Parallel Routes for Independent Content
+- `route-intercepting-routes` - Use Intercepting Routes for Modal Patterns
+- `route-prefetching` - Configure Link Prefetching Appropriately
+- `route-instant-navigations` - Make Navigations Instant with Stream, Cache, or Block (16.3 preview)
+- `route-partial-prefetching` - Use Partial Prefetching for Reusable Route Shells (16.3 preview)
+- `route-proxy-ts` - Use proxy.ts for Network Boundary Logic
+- `route-not-found` - Use notFound() for Missing Resources
+
+### 5. Server Actions & Mutations (MEDIUM-HIGH)
+
+- `action-server-action-forms` - Use Server Actions for Form Submissions
+- `action-pending-states` - Show Pending States with useFormStatus
+- `action-error-handling` - Handle Server Action Errors Gracefully
+- `action-optimistic-updates` - Use Optimistic Updates for Instant Feedback
+- `action-revalidation` - Revalidate Cache After Mutations
+
+### 6. Streaming & Loading States (MEDIUM)
+
+- `stream-suspense-boundaries` - Place Suspense Boundaries Strategically
+- `stream-loading-tsx` - Use loading.tsx for Route-Level Loading States
+- `stream-error-tsx` - Use error.tsx for Route-Level Error Boundaries
+- `stream-skeleton-matching` - Match Skeleton Dimensions to Actual Content
+- `stream-nested-suspense` - Nest Suspense for Progressive Disclosure
+
+### 7. Metadata & SEO (MEDIUM)
+
+- `meta-generate-metadata` - Use generateMetadata for Dynamic Metadata
+- `meta-sitemap` - Generate Sitemaps Dynamically
+- `meta-robots` - Configure Robots for Crawl Control
+- `meta-opengraph-images` - Generate Dynamic OpenGraph Images
+
+### 8. Client Components (LOW-MEDIUM)
+
+- `client-use-client-boundary` - Minimize 'use client' Boundary Scope
+- `client-children-pattern` - Pass Server Components as Children to Client Components
+- `client-hydration-mismatch` - Avoid Hydration Mismatches
+- `client-third-party-scripts` - Load Third-Party Scripts Efficiently
+
+## How to Use
+
+Run in the project root first:
+
+```bash
+npx -y @pymodel/react-frontend-skills detect # installed vs. targeted versions
+npx -y @pymodel/react-frontend-skills scan --skill nextjs # deprecated APIs → rule IDs
+```
+
+Read `references/.md` for each rule above that matches the task and for each `scan` hit: why it matters, then incorrect vs. correct code.
+
+## Related Skills
+
+- For React 19 fundamentals, see `react` skill
+- For data fetching patterns, see `tanstack-query` skill
+- For client-side forms, see `react-hook-form` skill
diff --git a/.agents/skills/nextjs/references/action-error-handling.md b/.agents/skills/nextjs/references/action-error-handling.md
new file mode 100644
index 0000000..98eba94
--- /dev/null
+++ b/.agents/skills/nextjs/references/action-error-handling.md
@@ -0,0 +1,75 @@
+---
+title: Handle Server Action Errors Gracefully
+impact: MEDIUM-HIGH
+impactDescription: prevents silent failures, better error UX
+tags: action, error-handling, validation, useActionState
+---
+
+## Handle Server Action Errors Gracefully
+
+Return error states from Server Actions instead of throwing. Use `useActionState` to manage form state and display errors.
+
+**Incorrect (unhandled errors):**
+
+```typescript
+async function createPost(formData: FormData) {
+ 'use server'
+
+ const title = formData.get('title') as string
+ await db.posts.create({ data: { title } })
+ // If validation fails or DB errors, user sees nothing
+}
+```
+
+**Correct (returning error state):**
+
+```typescript
+// actions.ts
+'use server'
+
+type ActionState = {
+ error?: string
+ success?: boolean
+}
+
+export async function createPost(
+ prevState: ActionState,
+ formData: FormData
+): Promise {
+ const title = formData.get('title') as string
+
+ if (!title || title.length < 3) {
+ return { error: 'Title must be at least 3 characters' }
+ }
+
+ try {
+ await db.posts.create({ data: { title } })
+ revalidatePath('/posts')
+ return { success: true }
+ } catch (e) {
+ return { error: 'Failed to create post. Please try again.' }
+ }
+}
+
+// page.tsx
+'use client'
+
+import { useActionState } from 'react'
+import { createPost } from './actions'
+
+export default function NewPostForm() {
+ const [state, formAction, isPending] = useActionState(createPost, {})
+
+ return (
+
+ )
+}
+```
+
+Reference: [useActionState](https://react.dev/reference/react/useActionState)
diff --git a/.agents/skills/nextjs/references/action-optimistic-updates.md b/.agents/skills/nextjs/references/action-optimistic-updates.md
new file mode 100644
index 0000000..31b1afe
--- /dev/null
+++ b/.agents/skills/nextjs/references/action-optimistic-updates.md
@@ -0,0 +1,74 @@
+---
+title: Use Optimistic Updates for Instant Feedback
+impact: MEDIUM
+impactDescription: instant UI response, better perceived performance
+tags: action, optimistic, useOptimistic, mutation
+---
+
+## Use Optimistic Updates for Instant Feedback
+
+Use `useOptimistic` to update UI immediately before the server confirms. If the action fails, React reverts to the previous state.
+
+**Incorrect (waiting for server response):**
+
+```typescript
+'use client'
+
+import { useState } from 'react'
+
+export function LikeButton({ postId, initialLikes }: { postId: string; initialLikes: number }) {
+ const [likes, setLikes] = useState(initialLikes)
+ const [isLiking, setIsLiking] = useState(false)
+
+ async function handleLike() {
+ setIsLiking(true)
+ const newLikes = await likePost(postId) // Wait for server
+ setLikes(newLikes)
+ setIsLiking(false)
+ }
+
+ return (
+
+ )
+}
+// UI updates only after the server round trip.
+```
+
+**Correct (optimistic update):**
+
+```typescript
+'use client'
+
+import { useOptimistic } from 'react'
+import { likePost } from './actions'
+
+export function LikeButton({ postId, initialLikes }: { postId: string; initialLikes: number }) {
+ const [optimisticLikes, addOptimisticLike] = useOptimistic(
+ initialLikes,
+ (state, _) => state + 1
+ )
+
+ async function handleLike() {
+ addOptimisticLike(null) // Instant UI update
+ await likePost(postId) // Server update in background
+ // If fails, React reverts automatically
+ }
+
+ return (
+
+ )
+}
+// Instant feedback, reverts on failure
+```
+
+**When to use:**
+- Like/vote buttons
+- Adding items to cart
+- Toggling favorites
+- Any action where instant feedback improves UX
diff --git a/.agents/skills/nextjs/references/action-pending-states.md b/.agents/skills/nextjs/references/action-pending-states.md
new file mode 100644
index 0000000..9cea961
--- /dev/null
+++ b/.agents/skills/nextjs/references/action-pending-states.md
@@ -0,0 +1,68 @@
+---
+title: Show Pending States with useFormStatus
+impact: MEDIUM-HIGH
+impactDescription: better UX during form submission
+tags: action, useFormStatus, pending, loading
+---
+
+## Show Pending States with useFormStatus
+
+Use `useFormStatus` to show loading indicators and disable buttons during form submission. This provides immediate feedback to users.
+
+**Incorrect (no feedback during submission):**
+
+```typescript
+// app/posts/new/page.tsx
+export default function NewPostPage() {
+ async function createPost(formData: FormData) {
+ 'use server'
+ await db.posts.create({ data: { title: formData.get('title') } })
+ }
+
+ return (
+
+ )
+}
+```
+
+**Correct (pending state with useFormStatus):**
+
+```typescript
+// app/posts/new/page.tsx
+import { SubmitButton } from './submit-button'
+
+export default function NewPostPage() {
+ async function createPost(formData: FormData) {
+ 'use server'
+ await db.posts.create({ data: { title: formData.get('title') } })
+ }
+
+ return (
+
+ )
+}
+
+// submit-button.tsx
+'use client'
+
+import { useFormStatus } from 'react-dom'
+
+export function SubmitButton() {
+ const { pending } = useFormStatus()
+
+ return (
+
+ )
+}
+```
+
+**Note:** `useFormStatus` must be used in a child component of the form, not in the same component as the form element.
diff --git a/.agents/skills/nextjs/references/action-revalidation.md b/.agents/skills/nextjs/references/action-revalidation.md
new file mode 100644
index 0000000..ad7b791
--- /dev/null
+++ b/.agents/skills/nextjs/references/action-revalidation.md
@@ -0,0 +1,78 @@
+---
+title: Revalidate Cache After Mutations
+impact: MEDIUM
+impactDescription: ensures fresh data after changes
+tags: action, revalidation, cache, mutation
+---
+
+## Revalidate Cache After Mutations
+
+After a mutation, invalidate only cached reads affected by the write. Use `revalidatePath` for route-level invalidation, `revalidateTag(tag, 'max')` for stale-while-revalidate content, or `updateTag(tag)` inside a Server Action for immediate read-your-writes behavior.
+
+**Incorrect (stale cache after mutation):**
+
+```typescript
+'use server'
+
+export async function deletePost(postId: string) {
+ await db.posts.delete({ where: { id: postId } })
+ redirect('/posts')
+ // Posts list still shows deleted post from cache!
+}
+```
+
+**Correct (invalidating cache):**
+
+```typescript
+'use server'
+
+import { revalidatePath, revalidateTag, updateTag } from 'next/cache'
+import { redirect } from 'next/navigation'
+
+export async function deletePost(postId: string) {
+ await db.posts.delete({ where: { id: postId } })
+
+ // Option 1: Revalidate specific path
+ revalidatePath('/posts')
+
+ // Option 2: expire and immediately refresh for this user's write
+ updateTag('posts')
+
+ redirect('/posts')
+}
+
+export async function updatePost(postId: string, formData: FormData) {
+ await db.posts.update({
+ where: { id: postId },
+ data: { title: formData.get('title') }
+ })
+
+ // Revalidate both the list and detail pages
+ revalidatePath('/posts')
+ revalidatePath(`/posts/${postId}`)
+}
+```
+
+**Revalidation strategies:**
+
+```typescript
+// Specific route
+revalidatePath('/posts')
+
+// Dynamic route with specific ID
+revalidatePath(`/posts/${postId}`)
+
+// All routes using a layout
+revalidatePath('/dashboard', 'layout')
+
+// Stale-while-revalidate for webhook/content updates
+revalidateTag('posts', 'max')
+
+// Immediate read-your-writes in a Server Action
+updateTag('posts')
+updateTag(`post-${postId}`)
+```
+
+`updateTag` requires `cacheComponents: true` and can only be called from a Server Action. In Route Handlers and webhooks use `revalidateTag(tag, 'max')` instead.
+
+Reference: [Next.js updating cached data](https://nextjs.org/docs/app/getting-started/caching-and-revalidating#updating-data)
diff --git a/.agents/skills/nextjs/references/action-server-action-forms.md b/.agents/skills/nextjs/references/action-server-action-forms.md
new file mode 100644
index 0000000..13d1655
--- /dev/null
+++ b/.agents/skills/nextjs/references/action-server-action-forms.md
@@ -0,0 +1,75 @@
+---
+title: Use Server Actions for Form Submissions
+impact: MEDIUM-HIGH
+impactDescription: eliminates API routes, type-safe mutations
+tags: action, server-action, form, mutation
+---
+
+## Use Server Actions for Form Submissions
+
+Server Actions handle form submissions directly without creating API routes. They're type-safe, progressively enhanced, and integrate with caching.
+
+**Incorrect (API route for form handling):**
+
+```typescript
+// app/api/posts/route.ts
+export async function POST(request: Request) {
+ const data = await request.json()
+ const post = await db.posts.create({ data })
+ return Response.json(post)
+}
+
+// app/posts/new/page.tsx
+'use client'
+
+export default function NewPostPage() {
+ const handleSubmit = async (e) => {
+ e.preventDefault()
+ const formData = new FormData(e.target)
+ await fetch('/api/posts', {
+ method: 'POST',
+ body: JSON.stringify(Object.fromEntries(formData))
+ })
+ }
+ // Requires client component, manual fetch, no type safety
+}
+```
+
+**Correct (Server Action):**
+
+```typescript
+// app/posts/new/page.tsx
+import { redirect } from 'next/navigation'
+import { revalidatePath } from 'next/cache'
+
+export default function NewPostPage() {
+ async function createPost(formData: FormData) {
+ 'use server'
+
+ const title = formData.get('title') as string
+ const content = formData.get('content') as string
+
+ const post = await db.posts.create({
+ data: { title, content }
+ })
+
+ revalidatePath('/posts')
+ redirect(`/posts/${post.id}`)
+ }
+
+ return (
+
+ )
+}
+// Works without JS, type-safe, integrated caching
+```
+
+**Benefits:**
+- Progressive enhancement (works without JavaScript)
+- Type-safe with TypeScript
+- Direct cache invalidation
+- No API route boilerplate
diff --git a/.agents/skills/nextjs/references/build-barrel-files.md b/.agents/skills/nextjs/references/build-barrel-files.md
new file mode 100644
index 0000000..2a7dcd0
--- /dev/null
+++ b/.agents/skills/nextjs/references/build-barrel-files.md
@@ -0,0 +1,50 @@
+---
+title: Avoid Barrel File Imports in App Router
+impact: CRITICAL
+impactDescription: 2-10× faster dev startup
+tags: build, imports, barrel-files, tree-shaking
+---
+
+## Avoid Barrel File Imports in App Router
+
+Barrel files (index.ts with re-exports) prevent tree-shaking and slow down development. Import directly from source files instead.
+
+**Incorrect (imports through barrel file):**
+
+```typescript
+// lib/utils/index.ts (barrel file)
+export * from './formatDate'
+export * from './formatCurrency'
+export * from './validateEmail'
+// ... 50 more exports
+
+// app/dashboard/page.tsx
+import { formatDate } from '@/lib/utils'
+// Loads all 50+ modules even though only formatDate is used
+```
+
+**Correct (direct import):**
+
+```typescript
+// app/dashboard/page.tsx
+import { formatDate } from '@/lib/utils/formatDate'
+// Loads only the formatDate module
+```
+
+**Alternative (path aliases):**
+
+```typescript
+// tsconfig.json
+{
+ "compilerOptions": {
+ "paths": {
+ "@/utils/*": ["./lib/utils/*"]
+ }
+ }
+}
+
+// app/dashboard/page.tsx
+import { formatDate } from '@/utils/formatDate'
+```
+
+**Note:** If you must use barrel files, configure `optimizePackageImports` or use explicit named exports instead of `export *`.
diff --git a/.agents/skills/nextjs/references/build-dynamic-imports.md b/.agents/skills/nextjs/references/build-dynamic-imports.md
new file mode 100644
index 0000000..3a2156d
--- /dev/null
+++ b/.agents/skills/nextjs/references/build-dynamic-imports.md
@@ -0,0 +1,62 @@
+---
+title: Use Dynamic Imports for Heavy Components
+impact: CRITICAL
+impactDescription: 30-70% smaller initial bundle
+tags: build, dynamic-import, code-splitting, lazy-loading
+---
+
+## Use Dynamic Imports for Heavy Components
+
+Large components like charts, editors, or maps should load on demand. Use `next/dynamic` to split them into separate bundles that load only when rendered.
+
+**Incorrect (always included in main bundle):**
+
+```typescript
+import HeavyChart from '@/components/HeavyChart'
+import CodeEditor from '@/components/CodeEditor'
+
+export default function Dashboard() {
+ const [showChart, setShowChart] = useState(false)
+
+ return (
+
+ {showChart && }
+
+
+ )
+}
+// Both components in initial bundle (~500KB added)
+```
+
+**Correct (loaded on demand):**
+
+```typescript
+'use client' // ssr: false is not allowed in Server Components
+
+import { useState } from 'react'
+import dynamic from 'next/dynamic'
+
+const HeavyChart = dynamic(() => import('@/components/HeavyChart'), {
+ loading: () =>
+})
+
+const CodeEditor = dynamic(() => import('@/components/CodeEditor'), {
+ ssr: false // Client-only component
+})
+
+export default function Dashboard() {
+ const [showChart, setShowChart] = useState(false)
+
+ return (
+
+ {showChart && }
+
+
+ )
+}
+// Components loaded only when rendered
+```
+
+**When to use `ssr: false`:** For libraries that touch `window` or `document` when imported, or when you also want the code split out of the server bundle. It only works from a Client Component. For a component that merely reads browser APIs while rendering, React 19.3's `use(browser())` inside `` skips its server render without a dynamic import (see the react skill's `effect-use-browser-only`).
+
+Reference: [Dynamic Imports](https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading)
diff --git a/.agents/skills/nextjs/references/build-external-packages.md b/.agents/skills/nextjs/references/build-external-packages.md
new file mode 100644
index 0000000..a48d386
--- /dev/null
+++ b/.agents/skills/nextjs/references/build-external-packages.md
@@ -0,0 +1,48 @@
+---
+title: Configure Server External Packages for Node Dependencies
+impact: HIGH
+impactDescription: prevents bundling issues, faster builds
+tags: build, external-packages, node-modules, server
+---
+
+## Configure Server External Packages for Node Dependencies
+
+Some Node.js packages with native bindings or complex dependencies should not be bundled. Use `serverExternalPackages` to exclude them from the server bundle.
+
+**Incorrect (bundling native modules):**
+
+```typescript
+// next.config.ts
+const nextConfig = {
+ // No external packages configured
+}
+
+// lib/pdf.ts
+import puppeteer from 'puppeteer'
+// Build fails or produces oversized bundles
+```
+
+**Correct (excluding native modules):**
+
+```typescript
+// next.config.ts
+const nextConfig = {
+ serverExternalPackages: [
+ 'puppeteer',
+ 'sharp',
+ 'canvas',
+ '@prisma/client',
+ 'bcrypt'
+ ]
+}
+
+// lib/pdf.ts
+import puppeteer from 'puppeteer'
+// Loaded at runtime from node_modules
+```
+
+**Common packages to externalize:**
+- Database drivers: `@prisma/client`, `pg`, `mysql2`
+- Image processing: `sharp`, `canvas`
+- Native bindings: `bcrypt`, `argon2`
+- Browser automation: `puppeteer`, `playwright`
diff --git a/.agents/skills/nextjs/references/build-optimize-package-imports.md b/.agents/skills/nextjs/references/build-optimize-package-imports.md
new file mode 100644
index 0000000..7a5e01a
--- /dev/null
+++ b/.agents/skills/nextjs/references/build-optimize-package-imports.md
@@ -0,0 +1,42 @@
+---
+title: Configure optimizePackageImports for Icon Libraries
+impact: CRITICAL
+impactDescription: 200-800ms faster imports, 50-80% smaller bundles
+tags: build, imports, tree-shaking, icons, turbopack
+---
+
+## Configure optimizePackageImports for Icon Libraries
+
+Icon libraries like `lucide-react` export hundreds of modules. Without optimization, importing one icon loads the entire library. Configure `optimizePackageImports` to automatically tree-shake unused exports.
+
+**Incorrect (loads entire library):**
+
+```typescript
+// next.config.ts
+const nextConfig = {
+ // No optimization configured
+}
+
+// components/Header.tsx
+import { Menu, X, Search } from 'lucide-react'
+// Loads 1,583 modules, adds ~2.8s to dev startup
+```
+
+**Correct (loads only used icons):**
+
+```typescript
+// next.config.ts
+const nextConfig = {
+ experimental: {
+ optimizePackageImports: ['lucide-react', '@heroicons/react', '@mui/icons-material']
+ }
+}
+
+// components/Header.tsx
+import { Menu, X, Search } from 'lucide-react'
+// Loads only 3 modules (~2KB vs ~1MB)
+```
+
+**Note:** Next.js 16 automatically optimizes common libraries. Add custom libraries that export many modules.
+
+Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
diff --git a/.agents/skills/nextjs/references/build-turbopack-config.md b/.agents/skills/nextjs/references/build-turbopack-config.md
new file mode 100644
index 0000000..c8a52eb
--- /dev/null
+++ b/.agents/skills/nextjs/references/build-turbopack-config.md
@@ -0,0 +1,71 @@
+---
+title: Configure Turbopack at the Top Level
+impact: CRITICAL
+impactDescription: uses the supported Next.js 16 bundler and cache configuration
+tags: build, turbopack, caching, development
+---
+
+## Configure Turbopack at the Top Level
+
+Next.js 16 uses Turbopack by default for both `next dev` and `next build`. Turbopack filesystem caching is also enabled by default for development and production builds. Do not add an opt-in flag merely to obtain the default behavior.
+
+**Incorrect (removed or fictitious options):**
+
+```typescript
+const nextConfig = {
+ experimental: {
+ turbo: {
+ persistentCaching: true,
+ },
+ },
+}
+```
+
+**Correct (only configure supported custom behavior):**
+
+```typescript
+import type { NextConfig } from 'next'
+
+const nextConfig: NextConfig = {
+ turbopack: {
+ rules: {
+ '*.svg': {
+ loaders: ['@svgr/webpack'],
+ as: '*.js',
+ },
+ },
+ },
+}
+
+export default nextConfig
+```
+
+```bash
+# Turbopack is the default in Next.js 16.
+next dev
+next build
+
+# Use Webpack only when an unresolved compatibility requirement demands it.
+next build --webpack
+```
+
+A custom `webpack` configuration makes the default `next build` fail rather than silently ignoring that configuration. Migrate the configuration, explicitly choose `--webpack`, or deliberately use `--turbopack` after confirming the Webpack customization is unnecessary.
+
+The filesystem cache is local build output and must remain uncommitted. In Next.js 16.3+, both caches default to `true`. Set the documented experimental keys only to override those defaults for a demonstrated environment-specific reason:
+
+```typescript
+import type { NextConfig } from 'next'
+
+const nextConfig: NextConfig = {
+ experimental: {
+ turbopackFileSystemCacheForDev: false,
+ turbopackFileSystemCacheForBuild: false,
+ },
+}
+
+export default nextConfig
+```
+
+References:
+- [Next.js 16 upgrade guide](https://nextjs.org/docs/app/guides/upgrading/version-16#turbopack-by-default)
+- [Turbopack filesystem cache](https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache)
diff --git a/.agents/skills/nextjs/references/cache-fetch-options.md b/.agents/skills/nextjs/references/cache-fetch-options.md
new file mode 100644
index 0000000..c940217
--- /dev/null
+++ b/.agents/skills/nextjs/references/cache-fetch-options.md
@@ -0,0 +1,53 @@
+---
+title: Configure Fetch Cache Options Explicitly
+impact: HIGH
+impactDescription: makes runtime freshness and revalidation behavior deliberate
+tags: cache, fetch, revalidate, data-fetching
+---
+
+## Configure Fetch Cache Options Explicitly
+
+In Next.js 15 and 16, a server `fetch()` without an explicit cache policy is not cached at runtime. Build-time prerendering may still reuse it during the build. State the intended policy instead of relying on older defaults.
+
+**Incorrect (assuming an implicit runtime cache):**
+
+```typescript
+export async function getProducts() {
+ // This is fresh at runtime in Next.js 15 and 16; it is not an implicit
+ // persistent cache entry.
+ return fetch('https://api.example.com/products')
+}
+```
+
+**Correct (policies match each data contract):**
+
+```typescript
+export default async function Page() {
+ const config = await fetch('https://api.example.com/config', {
+ cache: 'force-cache',
+ })
+
+ const user = await fetch(`https://api.example.com/users/${userId}`, {
+ cache: 'no-store',
+ })
+
+ const products = await fetch('https://api.example.com/products', {
+ next: { revalidate: 300 },
+ })
+
+ const posts = await fetch('https://api.example.com/posts', {
+ next: { tags: ['posts'] },
+ })
+}
+```
+
+Choose from the data contract:
+
+- Request-specific, authorization-dependent, or real-time data: `cache: 'no-store'`.
+- Reusable immutable data: `cache: 'force-cache'`.
+- Reusable data with a bounded freshness window: `next: { revalidate: seconds }`.
+- Reusable data requiring on-demand invalidation: attach `next.tags` and use the matching invalidation API.
+
+Do not cache personalized responses under a key shared by users. Also distinguish the persistent Data Cache from request memoization: identical GET fetches can be deduplicated during one server render without becoming cross-request cached data.
+
+Reference: [Next.js fetch API](https://nextjs.org/docs/app/api-reference/functions/fetch)
diff --git a/.agents/skills/nextjs/references/cache-react-cache.md b/.agents/skills/nextjs/references/cache-react-cache.md
new file mode 100644
index 0000000..6331c49
--- /dev/null
+++ b/.agents/skills/nextjs/references/cache-react-cache.md
@@ -0,0 +1,58 @@
+---
+title: Use React cache() for Request Deduplication
+impact: HIGH
+impactDescription: eliminates duplicate fetches per request
+tags: cache, react-cache, deduplication, server-components
+---
+
+## Use React cache() for Request Deduplication
+
+Wrap data fetching functions with `cache()` to deduplicate identical calls within a single render pass. Multiple components can call the same function without triggering multiple fetches.
+
+**Incorrect (duplicate fetches):**
+
+```typescript
+// lib/data.ts
+export async function getUser(id: string) {
+ const res = await fetch(`/api/users/${id}`)
+ return res.json()
+}
+
+// components/Header.tsx
+export async function Header({ userId }: { userId: string }) {
+ const user = await getUser(userId) // Fetch #1
+ return
+}
+
+// components/Sidebar.tsx
+export async function Sidebar({ userId }: { userId: string }) {
+ const user = await getUser(userId) // Cached result reused
+ return
+}
+```
+
+**Note:** React `cache()` deduplicates within a single request. For cross-request caching, use `unstable_cache` or the `'use cache'` directive.
diff --git a/.agents/skills/nextjs/references/cache-revalidate-path.md b/.agents/skills/nextjs/references/cache-revalidate-path.md
new file mode 100644
index 0000000..27ae2bf
--- /dev/null
+++ b/.agents/skills/nextjs/references/cache-revalidate-path.md
@@ -0,0 +1,62 @@
+---
+title: Use revalidatePath for Route-Level Cache Invalidation
+impact: HIGH
+impactDescription: invalidates all cached data for a route
+tags: cache, revalidate-path, invalidation, server-actions
+---
+
+## Use revalidatePath for Route-Level Cache Invalidation
+
+Use `revalidatePath` to invalidate all cached data associated with a specific route. Prefer `revalidateTag` for granular control.
+
+**Incorrect (forgetting to revalidate after mutation):**
+
+```typescript
+'use server'
+
+export async function createPost(formData: FormData) {
+ const title = formData.get('title') as string
+ const content = formData.get('content') as string
+
+ await db.posts.create({ data: { title, content } })
+
+ // User doesn't see new post until cache expires!
+}
+```
+
+**Correct (revalidating after mutation):**
+
+```typescript
+'use server'
+
+import { revalidatePath } from 'next/cache'
+import { redirect } from 'next/navigation'
+
+export async function createPost(formData: FormData) {
+ const title = formData.get('title') as string
+ const content = formData.get('content') as string
+
+ const post = await db.posts.create({ data: { title, content } })
+
+ revalidatePath('/posts') // Invalidate posts list
+ redirect(`/posts/${post.id}`) // Navigate to new post
+}
+```
+
+**Path patterns:**
+
+```typescript
+// Specific route
+revalidatePath('/posts')
+
+// Dynamic route
+revalidatePath('/posts/[slug]', 'page')
+
+// Layout and all child routes
+revalidatePath('/dashboard', 'layout')
+
+// Entire app (use sparingly)
+revalidatePath('/', 'layout')
+```
+
+**Note:** `redirect` must be called after `revalidatePath` as it throws internally.
diff --git a/.agents/skills/nextjs/references/cache-revalidate-tag.md b/.agents/skills/nextjs/references/cache-revalidate-tag.md
new file mode 100644
index 0000000..80227f8
--- /dev/null
+++ b/.agents/skills/nextjs/references/cache-revalidate-tag.md
@@ -0,0 +1,65 @@
+---
+title: Use revalidateTag with cacheLife Profiles
+impact: CRITICAL
+impactDescription: stale-while-revalidate behavior, instant updates
+tags: cache, revalidate-tag, cache-life, invalidation
+---
+
+## Use revalidateTag with cacheLife Profiles
+
+Next.js 16 deprecates the single-argument `revalidateTag(tag)` form and reports it as a TypeScript error. Pass a cache-life profile such as `'max'` for stale-while-revalidate behavior, or choose `updateTag()` in a Server Action when the current user must immediately read their own write.
+
+**Incorrect (old revalidateTag API):**
+
+```typescript
+// app/actions.ts
+'use server'
+
+import { revalidateTag } from 'next/cache'
+
+export async function updateProduct(id: string, data: FormData) {
+ await db.products.update({ where: { id }, data })
+
+ // Deprecated single-argument API; fails current Next.js type checking.
+ revalidateTag('products')
+}
+```
+
+**Correct (revalidateTag with cacheLife):**
+
+```typescript
+// app/actions.ts
+'use server'
+
+import { revalidateTag } from 'next/cache'
+
+export async function updateProduct(id: string, data: FormData) {
+ await db.products.update({ where: { id }, data })
+
+ // Recommended: 'max' enables stale-while-revalidate
+ revalidateTag('products', 'max')
+}
+
+// 'max' (recommended): serve cached data immediately and refresh in the
+// background the next time the tag is visited (stale-while-revalidate)
+// Built-in cacheLife profiles: 'max', 'hours', 'days', 'weeks'
+// For immediate read-your-writes updates use updateTag(tag) in a Server Action,
+// or revalidateTag(tag, { expire: 0 }) for webhooks needing instant expiry
+```
+
+**Tagging cached data:**
+
+```typescript
+// lib/data.ts
+'use cache'
+
+import { cacheTag } from 'next/cache'
+
+export async function getProducts() {
+ cacheTag('products')
+ const res = await fetch('https://api.store.com/products')
+ return res.json()
+}
+```
+
+Reference: [Next.js revalidateTag](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)
diff --git a/.agents/skills/nextjs/references/cache-segment-config.md b/.agents/skills/nextjs/references/cache-segment-config.md
new file mode 100644
index 0000000..fdd669d
--- /dev/null
+++ b/.agents/skills/nextjs/references/cache-segment-config.md
@@ -0,0 +1,63 @@
+---
+title: Match Route Configuration to the Active Cache Model
+impact: MEDIUM-HIGH
+impactDescription: avoids mixing incompatible Cache Components and legacy segment options
+tags: cache, segment-config, dynamic, revalidate, cache-components
+---
+
+## Match Route Configuration to the Active Cache Model
+
+Next.js 16 supports two caching models. First determine whether `cacheComponents: true` is enabled.
+
+### Cache Components enabled
+
+Use `'use cache'`, `cacheLife()`, `cacheTag()`, ``, and request-time APIs. Exporting `dynamic`, `revalidate`, `fetchCache`, `dynamicParams`, `runtime`, or `experimental_ppr` from a page, layout, or route is a build error when `cacheComponents` is enabled. Remove them rather than layering them onto the new model.
+
+**Incorrect (legacy segment exports under Cache Components):**
+
+```typescript
+// app/about/page.tsx
+export const dynamic = 'force-static'
+export const revalidate = 86400
+```
+
+**Correct (Cache Components model):**
+
+```typescript
+// next.config.ts
+import type { NextConfig } from 'next'
+
+const nextConfig: NextConfig = { cacheComponents: true }
+export default nextConfig
+```
+
+```typescript
+// app/about/page.tsx
+import { cacheLife } from 'next/cache'
+
+export default async function AboutPage() {
+ 'use cache'
+ cacheLife('days')
+
+ const team = await getTeam()
+ return
+}
+```
+
+### Cache Components disabled (previous model)
+
+Route segment configuration remains available. Use it only when the whole segment genuinely shares that rendering policy; prefer per-fetch controls for mixed data.
+
+```typescript
+export const dynamic = 'force-static'
+export const revalidate = 86400
+
+export default async function AboutPage() {
+ const team = await getTeam()
+ return
+}
+```
+
+For request-specific routes in the previous model, use `dynamic = 'force-dynamic'` or explicit uncached fetches. `generateStaticParams()` controls which dynamic route parameters are generated; it is not itself a cache invalidation API.
+
+Reference: [Next.js route segment config](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config)
diff --git a/.agents/skills/nextjs/references/cache-use-cache-directive.md b/.agents/skills/nextjs/references/cache-use-cache-directive.md
new file mode 100644
index 0000000..991bc79
--- /dev/null
+++ b/.agents/skills/nextjs/references/cache-use-cache-directive.md
@@ -0,0 +1,57 @@
+---
+title: Use 'use cache' with Cache Components
+impact: CRITICAL
+impactDescription: opts stable work into the Next.js 16 Cache Components model
+tags: cache, use-cache, directive, data-fetching, cache-components
+---
+
+## Use 'use cache' with Cache Components
+
+The `'use cache'` directive is part of Next.js 16 Cache Components. Enable the model with top-level `cacheComponents: true`, then place the directive at file, component, or function scope for work whose inputs and outputs are serializable and safe to reuse.
+
+**Incorrect (reading request-time data inside a cached scope):**
+
+```typescript
+import { cookies } from 'next/headers'
+
+export async function getDashboard() {
+ 'use cache'
+ const userId = (await cookies()).get('userId')?.value
+ return getDashboardForUser(userId)
+}
+```
+
+Request-time APIs cannot be called inside a cached scope, and caching personalized output under shared arguments can leak data.
+
+**Correct (enable Cache Components and cache stable inputs):**
+
+```typescript
+// next.config.ts
+import type { NextConfig } from 'next'
+
+const nextConfig: NextConfig = { cacheComponents: true }
+export default nextConfig
+```
+
+```typescript
+// lib/data.ts
+import { cacheLife, cacheTag } from 'next/cache'
+
+export async function getProducts() {
+ 'use cache'
+ cacheLife('hours')
+ cacheTag('products')
+
+ const response = await fetch('https://api.store.com/products')
+ if (!response.ok) throw new Error('Failed to load products')
+ return response.json()
+}
+```
+
+Without `'use cache'`, runtime fetches remain fresh by default. With it, the cached function follows its cache-life profile and can be invalidated through its tags; it is not necessarily cached forever.
+
+Do not read request-time values such as `cookies()`, `headers()`, or `searchParams` inside a cached scope. Read them outside and pass only the minimal serializable value as an argument. Do not cache personalized data under shared arguments.
+
+If `cacheComponents` is not enabled, follow the previous caching model (`fetch` cache options and, where needed, `unstable_cache`) rather than copying `'use cache'` into the app. Enabling Cache Components is a model change, not a rename-only migration.
+
+Reference: [Next.js Cache Components](https://nextjs.org/docs/app/getting-started/cache-components)
diff --git a/.agents/skills/nextjs/references/client-children-pattern.md b/.agents/skills/nextjs/references/client-children-pattern.md
new file mode 100644
index 0000000..3125c4d
--- /dev/null
+++ b/.agents/skills/nextjs/references/client-children-pattern.md
@@ -0,0 +1,75 @@
+---
+title: Pass Server Components as Children to Client Components
+impact: LOW-MEDIUM
+impactDescription: keeps static content on server, reduces bundle
+tags: client, children, composition, server-components
+---
+
+## Pass Server Components as Children to Client Components
+
+Client Components can render Server Components passed as children. This keeps static content server-rendered while adding interactivity.
+
+**Incorrect (converting children to Client Components):**
+
+```typescript
+// components/Modal.tsx
+'use client'
+
+import { ProductDetails } from './ProductDetails' // Forces this to be client
+
+export function Modal({ productId }) {
+ const [isOpen, setIsOpen] = useState(false)
+
+ return (
+ <>
+
+ {isOpen && (
+
+ )
+}
+
+// app/dashboard/@analytics/page.tsx
+export default async function AnalyticsSlot() {
+ const data = await fetchAnalytics()
+ return
+}
+// Each slot streams independently
+```
+
+**Benefits:**
+- Each slot loads independently
+- Each slot has its own loading.tsx
+- Each slot can have its own error.tsx
diff --git a/.agents/skills/nextjs/references/route-partial-prefetching.md b/.agents/skills/nextjs/references/route-partial-prefetching.md
new file mode 100644
index 0000000..9fdab2d
--- /dev/null
+++ b/.agents/skills/nextjs/references/route-partial-prefetching.md
@@ -0,0 +1,87 @@
+---
+title: Use Partial Prefetching for Reusable Route Shells
+impact: HIGH
+impactDescription: one prefetch per route instead of per link, instant first click
+tags: route, prefetching, partial-prefetching, shell, link, navigation
+---
+
+## Use Partial Prefetching for Reusable Route Shells
+
+> **Next.js 16.3 (preview, `next@preview`).** Requires `cacheComponents: true` and `partialPrefetching: true` in `next.config.ts`. Planned to become the default behavior in a future major release.
+
+Before 16.2, Next.js sent a prefetch request for **every link** in the viewport — even many links to the same route, producing a flurry of requests on scroll. 16.3 replaces this with a single-page-app trick: **prefetch one reusable loading shell per route**, fetched once and cached on the client for the session.
+
+```typescript
+// next.config.ts
+import type { NextConfig } from 'next'
+
+const nextConfig: NextConfig = {
+ cacheComponents: true,
+ partialPrefetching: true,
+}
+
+export default nextConfig
+```
+
+**Incorrect (relying on per-link prefetch for responsiveness):**
+
+```typescript
+// A sidebar with twenty chat links fires a prefetch per link,
+// most of them for the same /chat/[id] route
+export function Sidebar({ chats }) {
+ return (
+
+ )
+}
+// Wasteful: the same route shell is fetched once per link
+```
+
+**Correct (let the shell be prefetched once per route):**
+
+```typescript
+// With partialPrefetching enabled, Next.js prefetches a single
+// reusable shell for /chat/[id], plus one per other distinct route
+export function Sidebar({ chats }) {
+ return (
+
+ )
+}
+// One request for the route, cached across all twenty links
+```
+
+**Prefetch more than the shell for specific links:**
+
+```tsx
+// Opt a single link into deeper prefetching so the chat header
+// "pops in" instantly instead of waiting for the network
+
+ {chat.name}
+
+```
+
+With ``, Next.js still does not render the entire route. It renders down to content that is:
+
+- available synchronously,
+- known from the URL (`params`, `searchParams`), or
+- marked with `'use cache'`.
+
+This removes the all-or-nothing choice: the instant shell is the baseline, and `` plus `'use cache'` adds per-link depth only where it pays off.
+
+**Notes:**
+
+- Inspect what a shell contains with the **Navigation Inspector** in Next.js DevTools — it pauses each navigation at the shell so you can see what renders instantly versus after the network hop.
+- Actual prefetching happens only in production builds; in development the Inspector simulates it.
+- Because shells are reused across links, they are the foundation for upcoming offline navigation support.
+- Pair with [route-instant-navigations](route-instant-navigations.md) (Stream / Cache / Block) so each route actually has an instant shell to prefetch.
diff --git a/.agents/skills/nextjs/references/route-prefetching.md b/.agents/skills/nextjs/references/route-prefetching.md
new file mode 100644
index 0000000..40a1f04
--- /dev/null
+++ b/.agents/skills/nextjs/references/route-prefetching.md
@@ -0,0 +1,71 @@
+---
+title: Configure Link Prefetching Appropriately
+impact: MEDIUM-HIGH
+impactDescription: instant navigation for likely destinations
+tags: route, prefetching, link, navigation
+---
+
+## Configure Link Prefetching Appropriately
+
+Next.js automatically prefetches linked routes. Control this behavior based on route importance and user likelihood to navigate.
+
+**Incorrect (no prefetch consideration):**
+
+```typescript
+// Prefetches all links, including rarely used ones
+export default function Navigation() {
+ return (
+
+ )
+}
+// Wastes bandwidth prefetching unlikely routes
+```
+
+**Correct (strategic prefetching):**
+
+```typescript
+export default function Navigation() {
+ return (
+
+ )
+}
+```
+
+**Prefetch on hover for conditional routes:**
+
+```typescript
+'use client'
+
+import { useRouter } from 'next/navigation'
+
+export function ProductCard({ product }) {
+ const router = useRouter()
+
+ return (
+