diff --git a/.ai/README.md b/.ai/README.md
index 38adffd9..70a8841f 100644
--- a/.ai/README.md
+++ b/.ai/README.md
@@ -11,6 +11,7 @@ future coding agent read the same instructions from here.
| Directory | Contains |
| ------------- | --------------------------------------------------------------------- |
| `skills/` | Reusable **operational playbooks** — how to do a kind of work well. |
+| `references/` | Supporting material loaded only when a skill needs it. |
| `roles/` | Reusable **agent personas** — focused roles with a mission and scope. |
| `workflows/` | **Task workflows** — how to execute common end-to-end tasks. |
@@ -55,6 +56,11 @@ Area skills:
| [prompt-rendering](skills/prompt-rendering.md) | Prompt templates and rendering. |
| [sidecar-auth-context](skills/sidecar-auth-context.md) | Plugin context and protected-node access. |
| [mcp-tools](skills/mcp-tools.md) | Tool plugins and MCP servers. |
+| [vercel-react-best-practices](skills/vercel-react-best-practices.md) | React chat widget implementation, review, and performance. |
+
+The Vercel skill includes 70 vendored rules under
+`references/vercel-react-best-practices/rules/`. Its canonical entrypoint records
+the upstream revision and license; generated adapters use the same references.
### `roles/` — agent personas
diff --git a/.ai/references/vercel-react-best-practices/rules/advanced-effect-event-deps.md b/.ai/references/vercel-react-best-practices/rules/advanced-effect-event-deps.md
new file mode 100644
index 00000000..24d901b6
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/advanced-effect-event-deps.md
@@ -0,0 +1,56 @@
+---
+title: Do Not Put Effect Events in Dependency Arrays
+impact: LOW
+impactDescription: avoids unnecessary effect re-runs and lint errors
+tags: advanced, hooks, useEffectEvent, dependencies, effects
+---
+
+## Do Not Put Effect Events in Dependency Arrays
+
+Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
+
+**Incorrect (Effect Event added as a dependency):**
+
+```tsx
+import { useEffect, useEffectEvent } from 'react'
+
+function ChatRoom({ roomId, onConnected }: {
+ roomId: string
+ onConnected: () => void
+}) {
+ const handleConnected = useEffectEvent(onConnected)
+
+ useEffect(() => {
+ const connection = createConnection(roomId)
+ connection.on('connected', handleConnected)
+ connection.connect()
+
+ return () => connection.disconnect()
+ }, [roomId, handleConnected])
+}
+```
+
+Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
+
+**Correct (depend on reactive values, not the Effect Event):**
+
+```tsx
+import { useEffect, useEffectEvent } from 'react'
+
+function ChatRoom({ roomId, onConnected }: {
+ roomId: string
+ onConnected: () => void
+}) {
+ const handleConnected = useEffectEvent(onConnected)
+
+ useEffect(() => {
+ const connection = createConnection(roomId)
+ connection.on('connected', handleConnected)
+ connection.connect()
+
+ return () => connection.disconnect()
+ }, [roomId])
+}
+```
+
+Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
diff --git a/.ai/references/vercel-react-best-practices/rules/advanced-event-handler-refs.md b/.ai/references/vercel-react-best-practices/rules/advanced-event-handler-refs.md
new file mode 100644
index 00000000..75916ab4
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/advanced-event-handler-refs.md
@@ -0,0 +1,55 @@
+---
+title: Store Event Handlers in Refs
+impact: LOW
+impactDescription: stable subscriptions
+tags: advanced, hooks, refs, event-handlers, optimization
+---
+
+## Store Event Handlers in Refs
+
+Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
+
+**Incorrect (re-subscribes on every render):**
+
+```tsx
+function useWindowEvent(event: string, handler: (e) => void) {
+ useEffect(() => {
+ window.addEventListener(event, handler)
+ return () => window.removeEventListener(event, handler)
+ }, [event, handler])
+}
+```
+
+**Correct (stable subscription):**
+
+```tsx
+function useWindowEvent(event: string, handler: (e) => void) {
+ const handlerRef = useRef(handler)
+ useEffect(() => {
+ handlerRef.current = handler
+ }, [handler])
+
+ useEffect(() => {
+ const listener = (e) => handlerRef.current(e)
+ window.addEventListener(event, listener)
+ return () => window.removeEventListener(event, listener)
+ }, [event])
+}
+```
+
+**Alternative: use `useEffectEvent` if you're on latest React:**
+
+```tsx
+import { useEffectEvent } from 'react'
+
+function useWindowEvent(event: string, handler: (e) => void) {
+ const onEvent = useEffectEvent(handler)
+
+ useEffect(() => {
+ window.addEventListener(event, onEvent)
+ return () => window.removeEventListener(event, onEvent)
+ }, [event])
+}
+```
+
+`useEffectEvent` provides a cleaner API for the same pattern. Its returned function is not stable: React returns a new one on every render, so keep it out of dependency arrays (see `advanced-effect-event-deps.md`). The subscription still works because the function registered by the effect, from whichever render, always runs the latest handler with the latest props and state.
diff --git a/.ai/references/vercel-react-best-practices/rules/advanced-init-once.md b/.ai/references/vercel-react-best-practices/rules/advanced-init-once.md
new file mode 100644
index 00000000..73ee38e5
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/advanced-init-once.md
@@ -0,0 +1,42 @@
+---
+title: Initialize App Once, Not Per Mount
+impact: LOW-MEDIUM
+impactDescription: avoids duplicate init in development
+tags: initialization, useEffect, app-startup, side-effects
+---
+
+## Initialize App Once, Not Per Mount
+
+Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
+
+**Incorrect (runs twice in dev, re-runs on remount):**
+
+```tsx
+function Comp() {
+ useEffect(() => {
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+**Correct (once per app load):**
+
+```tsx
+let didInit = false
+
+function Comp() {
+ useEffect(() => {
+ if (didInit) return
+ didInit = true
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
diff --git a/.ai/references/vercel-react-best-practices/rules/advanced-use-latest.md b/.ai/references/vercel-react-best-practices/rules/advanced-use-latest.md
new file mode 100644
index 00000000..e1a41967
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/advanced-use-latest.md
@@ -0,0 +1,41 @@
+---
+title: useEffectEvent for Latest-Value Callbacks
+impact: LOW
+impactDescription: prevents effect re-runs
+tags: advanced, hooks, useEffectEvent, refs, optimization
+---
+
+## useEffectEvent for Latest-Value Callbacks
+
+Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
+
+The function returned by `useEffectEvent` is not stable: React intentionally returns a new one on every render. Call it only from inside effects, and keep it out of dependency arrays (see `advanced-effect-event-deps.md`). It avoids re-runs because it always reads the latest props and state, not because its identity is stable.
+
+**Incorrect (effect re-runs on every callback change):**
+
+```tsx
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearch(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query, onSearch])
+}
+```
+
+**Correct (using React's useEffectEvent):**
+
+```tsx
+import { useEffectEvent } from 'react';
+
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+ const onSearchEvent = useEffectEvent(onSearch)
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearchEvent(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query])
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/async-api-routes.md b/.ai/references/vercel-react-best-practices/rules/async-api-routes.md
new file mode 100644
index 00000000..c94dea68
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/async-api-routes.md
@@ -0,0 +1,44 @@
+---
+title: Prevent Waterfall Chains in API Routes
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: api-routes, server-actions, waterfalls, parallelization
+---
+
+## Prevent Waterfall Chains in API Routes
+
+In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
+
+**Incorrect (config waits for auth, data waits for both):**
+
+```typescript
+export async function GET(request: Request) {
+ const session = await auth()
+ const config = await fetchConfig()
+ const data = await fetchData(session.user.id)
+ return Response.json({ data, config })
+}
+```
+
+**Correct (auth and config start immediately):**
+
+```typescript
+export async function GET(request: Request) {
+ const sessionPromise = auth()
+ const configPromise = fetchConfig()
+ // Mark the early start as handled: if auth fails or returns early, a later
+ // config rejection must not become an unhandled rejection.
+ configPromise.catch(() => {})
+ const session = await sessionPromise
+ if (!session) return new Response('Unauthorized', { status: 401 })
+ const [config, data] = await Promise.all([
+ configPromise,
+ fetchData(session.user.id)
+ ])
+ return Response.json({ data, config })
+}
+```
+
+Start work before authentication only when it is safe for an unauthenticated caller to trigger: cheap, free of side effects, and independent of the caller. Otherwise wait for authentication first.
+
+For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
diff --git a/.ai/references/vercel-react-best-practices/rules/async-cheap-condition-before-await.md b/.ai/references/vercel-react-best-practices/rules/async-cheap-condition-before-await.md
new file mode 100644
index 00000000..5799d7f6
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/async-cheap-condition-before-await.md
@@ -0,0 +1,37 @@
+---
+title: Check Cheap Conditions Before Async Flags
+impact: HIGH
+impactDescription: avoids unnecessary async work when a synchronous guard already fails
+tags: async, await, feature-flags, short-circuit, conditional
+---
+
+## Check Cheap Conditions Before Async Flags
+
+When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
+
+This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
+
+**Incorrect:**
+
+```typescript
+const someFlag = await getFlag()
+
+if (someFlag && someCondition) {
+ // ...
+}
+```
+
+**Correct:**
+
+```typescript
+if (someCondition) {
+ const someFlag = await getFlag()
+ if (someFlag) {
+ // ...
+ }
+}
+```
+
+This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
+
+Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
diff --git a/.ai/references/vercel-react-best-practices/rules/async-defer-await.md b/.ai/references/vercel-react-best-practices/rules/async-defer-await.md
new file mode 100644
index 00000000..8eada33f
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/async-defer-await.md
@@ -0,0 +1,82 @@
+---
+title: Defer Await Until Needed
+impact: HIGH
+impactDescription: avoids blocking unused code paths
+tags: async, await, conditional, optimization
+---
+
+## Defer Await Until Needed
+
+Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
+
+**Incorrect (blocks both branches):**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ const userData = await fetchUserData(userId)
+
+ if (skipProcessing) {
+ // Returns immediately but still waited for userData
+ return { skipped: true }
+ }
+
+ // Only this branch uses userData
+ return processUserData(userData)
+}
+```
+
+**Correct (only blocks when needed):**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ if (skipProcessing) {
+ // Returns immediately without waiting
+ return { skipped: true }
+ }
+
+ // Fetch only when needed
+ const userData = await fetchUserData(userId)
+ return processUserData(userData)
+}
+```
+
+**Another example (early return optimization):**
+
+```typescript
+// Incorrect: always fetches permissions
+async function updateResource(resourceId: string, userId: string) {
+ const permissions = await fetchPermissions(userId)
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+
+// Correct: fetches only when needed
+async function updateResource(resourceId: string, userId: string) {
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ const permissions = await fetchPermissions(userId)
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+```
+
+This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
+
+For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
diff --git a/.ai/references/vercel-react-best-practices/rules/async-dependencies.md b/.ai/references/vercel-react-best-practices/rules/async-dependencies.md
new file mode 100644
index 00000000..0484ebab
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/async-dependencies.md
@@ -0,0 +1,51 @@
+---
+title: Dependency-Based Parallelization
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: async, parallelization, dependencies, better-all
+---
+
+## Dependency-Based Parallelization
+
+For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
+
+**Incorrect (profile waits for config unnecessarily):**
+
+```typescript
+const [user, config] = await Promise.all([
+ fetchUser(),
+ fetchConfig()
+])
+const profile = await fetchProfile(user.id)
+```
+
+**Correct (config and profile run in parallel):**
+
+```typescript
+import { all } from 'better-all'
+
+const { user, config, profile } = await all({
+ async user() { return fetchUser() },
+ async config() { return fetchConfig() },
+ async profile() {
+ return fetchProfile((await this.$.user).id)
+ }
+})
+```
+
+**Alternative without extra dependencies:**
+
+We can also create all the promises first, and do `Promise.all()` at the end.
+
+```typescript
+const userPromise = fetchUser()
+const profilePromise = userPromise.then(user => fetchProfile(user.id))
+
+const [user, config, profile] = await Promise.all([
+ userPromise,
+ fetchConfig(),
+ profilePromise
+])
+```
+
+Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
diff --git a/.ai/references/vercel-react-best-practices/rules/async-parallel.md b/.ai/references/vercel-react-best-practices/rules/async-parallel.md
new file mode 100644
index 00000000..64133f6c
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/async-parallel.md
@@ -0,0 +1,28 @@
+---
+title: Promise.all() for Independent Operations
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: async, parallelization, promises, waterfalls
+---
+
+## Promise.all() for Independent Operations
+
+When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
+
+**Incorrect (sequential execution, 3 round trips):**
+
+```typescript
+const user = await fetchUser()
+const posts = await fetchPosts()
+const comments = await fetchComments()
+```
+
+**Correct (parallel execution, 1 round trip):**
+
+```typescript
+const [user, posts, comments] = await Promise.all([
+ fetchUser(),
+ fetchPosts(),
+ fetchComments()
+])
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.ai/references/vercel-react-best-practices/rules/async-suspense-boundaries.md
new file mode 100644
index 00000000..b12794c5
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/async-suspense-boundaries.md
@@ -0,0 +1,99 @@
+---
+title: Strategic Suspense Boundaries
+impact: HIGH
+impactDescription: faster initial paint
+tags: async, suspense, streaming, layout-shift
+---
+
+## Strategic Suspense Boundaries
+
+Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
+
+**Incorrect (wrapper blocked by data fetching):**
+
+```tsx
+async function Page() {
+ const data = await fetchData() // Blocks entire page
+
+ return (
+
+
Sidebar
+
Header
+
+
+
+
Footer
+
+ )
+}
+```
+
+The entire layout waits for data even though only the middle section needs it.
+
+**Correct (wrapper shows immediately, data streams in):**
+
+```tsx
+function Page() {
+ return (
+
+
Sidebar
+
Header
+
+ }>
+
+
+
+
Footer
+
+ )
+}
+
+async function DataDisplay() {
+ const data = await fetchData() // Only blocks this component
+ return
{data.content}
+}
+```
+
+Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
+
+**Alternative (share promise across components):**
+
+```tsx
+function Page() {
+ // Start fetch immediately, but don't await
+ const dataPromise = fetchData()
+
+ return (
+
+ )
+}
+```
+
+Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
+
+See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
diff --git a/.ai/references/vercel-react-best-practices/rules/js-cache-function-results.md b/.ai/references/vercel-react-best-practices/rules/js-cache-function-results.md
new file mode 100644
index 00000000..74eb1cef
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-cache-function-results.md
@@ -0,0 +1,88 @@
+---
+title: Cache Repeated Function Calls
+impact: MEDIUM
+impactDescription: avoid redundant computation
+tags: javascript, cache, memoization, performance
+---
+
+## Cache Repeated Function Calls
+
+Use a module-level Map to cache the results of a pure function that is called repeatedly with the same inputs during render. Cache only results that depend solely on the arguments, and bound the cache: a module-level Map lives as long as the page or server process, so unbounded inputs make it grow forever. Never cache user- or request-specific results in module scope on a server.
+
+**Incorrect (redundant computation):**
+
+```typescript
+function ProjectList({ projects }: { projects: Project[] }) {
+ return (
+
+ {projects.map(project => {
+ // slugify() called 100+ times for same project names
+ const slug = slugify(project.name)
+
+ return
+ })}
+
+ )
+}
+```
+
+**Correct (cached results):**
+
+```typescript
+// Module-level cache for a pure function, bounded by size
+const MAX_SLUGS = 1000
+const slugifyCache = new Map()
+
+function cachedSlugify(text: string): string {
+ const cached = slugifyCache.get(text)
+ if (cached !== undefined) {
+ return cached
+ }
+ const result = slugify(text)
+ if (slugifyCache.size >= MAX_SLUGS) {
+ // Maps keep insertion order, so this evicts the oldest entry
+ slugifyCache.delete(slugifyCache.keys().next().value!)
+ }
+ slugifyCache.set(text, result)
+ return result
+}
+
+function ProjectList({ projects }: { projects: Project[] }) {
+ return (
+
+ {projects.map(project => {
+ // Computed only once per unique project name
+ const slug = cachedSlugify(project.name)
+
+ return
+ })}
+
+ )
+}
+```
+
+**Single-value cache with explicit invalidation:**
+
+This result depends on browser state, not arguments, so it is correct only if every change to that state calls the invalidation function. If you cannot guarantee that, recompute instead.
+
+```typescript
+let isLoggedInCache: boolean | null = null
+
+function isLoggedIn(): boolean {
+ if (isLoggedInCache !== null) {
+ return isLoggedInCache
+ }
+
+ isLoggedInCache = document.cookie.includes('auth=')
+ return isLoggedInCache
+}
+
+// Clear cache when auth changes
+function onAuthChange() {
+ isLoggedInCache = null
+}
+```
+
+Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
+
+Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
diff --git a/.ai/references/vercel-react-best-practices/rules/js-cache-property-access.md b/.ai/references/vercel-react-best-practices/rules/js-cache-property-access.md
new file mode 100644
index 00000000..39eec906
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-cache-property-access.md
@@ -0,0 +1,28 @@
+---
+title: Cache Property Access in Loops
+impact: LOW-MEDIUM
+impactDescription: reduces lookups
+tags: javascript, loops, optimization, caching
+---
+
+## Cache Property Access in Loops
+
+Cache object property lookups in hot paths.
+
+**Incorrect (3 lookups × N iterations):**
+
+```typescript
+for (let i = 0; i < arr.length; i++) {
+ process(obj.config.settings.value)
+}
+```
+
+**Correct (1 lookup total):**
+
+```typescript
+const value = obj.config.settings.value
+const len = arr.length
+for (let i = 0; i < len; i++) {
+ process(value)
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/js-cache-storage.md b/.ai/references/vercel-react-best-practices/rules/js-cache-storage.md
new file mode 100644
index 00000000..4e898d81
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-cache-storage.md
@@ -0,0 +1,86 @@
+---
+title: Cache Storage API Calls
+impact: LOW-MEDIUM
+impactDescription: reduces expensive I/O
+tags: javascript, localStorage, storage, caching, performance
+---
+
+## Cache Storage API Calls
+
+`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
+
+**Incorrect (reads storage on every call):**
+
+```typescript
+function getTheme() {
+ return localStorage.getItem('theme') ?? 'light'
+}
+// Called 10 times = 10 storage reads
+```
+
+**Correct (Map cache):**
+
+```typescript
+const storageCache = new Map()
+
+function getLocalStorage(key: string) {
+ if (!storageCache.has(key)) {
+ storageCache.set(key, localStorage.getItem(key))
+ }
+ return storageCache.get(key)
+}
+
+function setLocalStorage(key: string, value: string) {
+ localStorage.setItem(key, value)
+ storageCache.set(key, value) // keep cache in sync
+}
+```
+
+Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
+
+**Cookie caching:**
+
+```typescript
+let cookieCache: Record | null = null
+
+function getCookie(name: string) {
+ if (!cookieCache) {
+ cookieCache = Object.fromEntries(
+ document.cookie
+ .split('; ')
+ .filter(Boolean)
+ // Split on the first "=" only; cookie values may contain "="
+ .map(c => {
+ const i = c.indexOf('=')
+ return i < 0 ? ['', c] : [c.slice(0, i), c.slice(i + 1)]
+ })
+ )
+ }
+ return cookieCache[name]
+}
+
+function setCookie(cookie: string) {
+ document.cookie = cookie
+ cookieCache = null // re-read on next access
+}
+```
+
+**Important (invalidate on external changes):**
+
+If storage can change outside this code (another tab, the server), invalidate both caches:
+
+```typescript
+window.addEventListener('storage', (e) => {
+ if (e.key) storageCache.delete(e.key)
+ else storageCache.clear() // storage.clear() in another tab
+})
+
+document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'visible') {
+ storageCache.clear()
+ cookieCache = null
+ }
+})
+```
+
+The `storage` event fires only for `localStorage`/`sessionStorage` changes made by other documents; it never fires for cookies. A cookie set by a server response (`Set-Cookie`) or by other code changes with no event at all, so cache a cookie only when your own code is its sole writer, and reset `cookieCache` after any request that can set it. Otherwise read `document.cookie` directly.
diff --git a/.ai/references/vercel-react-best-practices/rules/js-combine-iterations.md b/.ai/references/vercel-react-best-practices/rules/js-combine-iterations.md
new file mode 100644
index 00000000..044d017e
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-combine-iterations.md
@@ -0,0 +1,32 @@
+---
+title: Combine Multiple Array Iterations
+impact: LOW-MEDIUM
+impactDescription: reduces iterations
+tags: javascript, arrays, loops, performance
+---
+
+## Combine Multiple Array Iterations
+
+Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
+
+**Incorrect (3 iterations):**
+
+```typescript
+const admins = users.filter(u => u.isAdmin)
+const testers = users.filter(u => u.isTester)
+const inactive = users.filter(u => !u.isActive)
+```
+
+**Correct (1 iteration):**
+
+```typescript
+const admins: User[] = []
+const testers: User[] = []
+const inactive: User[] = []
+
+for (const user of users) {
+ if (user.isAdmin) admins.push(user)
+ if (user.isTester) testers.push(user)
+ if (!user.isActive) inactive.push(user)
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/js-early-exit.md b/.ai/references/vercel-react-best-practices/rules/js-early-exit.md
new file mode 100644
index 00000000..44a8c58c
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-early-exit.md
@@ -0,0 +1,50 @@
+---
+title: Early Return from Functions
+impact: LOW-MEDIUM
+impactDescription: avoids unnecessary computation
+tags: javascript, functions, optimization, early-return
+---
+
+## Early Return from Functions
+
+Return early when result is determined to skip unnecessary processing.
+
+**Incorrect (processes all items even after finding answer):**
+
+```typescript
+function validateUsers(users: User[]) {
+ let hasError = false
+ let errorMessage = ''
+
+ for (const user of users) {
+ if (!user.email) {
+ hasError = true
+ errorMessage = 'Email required'
+ }
+ if (!user.name) {
+ hasError = true
+ errorMessage = 'Name required'
+ }
+ // Continues checking all users even after error found
+ }
+
+ return hasError ? { valid: false, error: errorMessage } : { valid: true }
+}
+```
+
+**Correct (returns immediately on first error):**
+
+```typescript
+function validateUsers(users: User[]) {
+ for (const user of users) {
+ if (!user.email) {
+ return { valid: false, error: 'Email required' }
+ }
+ if (!user.name) {
+ return { valid: false, error: 'Name required' }
+ }
+ }
+
+ return { valid: true }
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/js-flatmap-filter.md b/.ai/references/vercel-react-best-practices/rules/js-flatmap-filter.md
new file mode 100644
index 00000000..ee0edf0d
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-flatmap-filter.md
@@ -0,0 +1,60 @@
+---
+title: Use flatMap to Map and Filter in One Pass
+impact: LOW-MEDIUM
+impactDescription: eliminates intermediate array
+tags: javascript, arrays, flatMap, filter, performance
+---
+
+## Use flatMap to Map and Filter in One Pass
+
+**Impact: LOW-MEDIUM (eliminates intermediate array)**
+
+Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
+
+**Incorrect (2 iterations, intermediate array):**
+
+```typescript
+const userNames = users
+ .map(user => user.isActive ? user.name : null)
+ .filter(Boolean)
+```
+
+**Correct (1 iteration, no intermediate array):**
+
+```typescript
+const userNames = users.flatMap(user =>
+ user.isActive ? [user.name] : []
+)
+```
+
+**More examples:**
+
+```typescript
+// Extract valid emails from responses
+// Before
+const emails = responses
+ .map(r => r.success ? r.data.email : null)
+ .filter(Boolean)
+
+// After
+const emails = responses.flatMap(r =>
+ r.success ? [r.data.email] : []
+)
+
+// Parse and filter valid numbers
+// Before
+const numbers = strings
+ .map(s => parseInt(s, 10))
+ .filter(n => !isNaN(n))
+
+// After
+const numbers = strings.flatMap(s => {
+ const n = parseInt(s, 10)
+ return isNaN(n) ? [] : [n]
+})
+```
+
+**When to use:**
+- Transforming items while filtering some out
+- Conditional mapping where some inputs produce no output
+- Parsing/validating where invalid inputs should be skipped
diff --git a/.ai/references/vercel-react-best-practices/rules/js-hoist-regexp.md b/.ai/references/vercel-react-best-practices/rules/js-hoist-regexp.md
new file mode 100644
index 00000000..dae3fefd
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-hoist-regexp.md
@@ -0,0 +1,45 @@
+---
+title: Hoist RegExp Creation
+impact: LOW-MEDIUM
+impactDescription: avoids recreation
+tags: javascript, regexp, optimization, memoization
+---
+
+## Hoist RegExp Creation
+
+Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
+
+**Incorrect (new RegExp every render):**
+
+```tsx
+function Highlighter({ text, query }: Props) {
+ const regex = new RegExp(`(${query})`, 'gi')
+ const parts = text.split(regex)
+ return <>{parts.map((part, i) => ...)}>
+}
+```
+
+**Correct (memoize or hoist):**
+
+```tsx
+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
+
+function Highlighter({ text, query }: Props) {
+ const regex = useMemo(
+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
+ [query]
+ )
+ const parts = text.split(regex)
+ return <>{parts.map((part, i) => ...)}>
+}
+```
+
+**Warning (global regex has mutable state):**
+
+Global regex (`/g`) has mutable `lastIndex` state:
+
+```typescript
+const regex = /foo/g
+regex.test('foo') // true, lastIndex = 3
+regex.test('foo') // false, lastIndex = 0
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/js-index-maps.md b/.ai/references/vercel-react-best-practices/rules/js-index-maps.md
new file mode 100644
index 00000000..9d357a00
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-index-maps.md
@@ -0,0 +1,37 @@
+---
+title: Build Index Maps for Repeated Lookups
+impact: LOW-MEDIUM
+impactDescription: 1M ops to 2K ops
+tags: javascript, map, indexing, optimization, performance
+---
+
+## Build Index Maps for Repeated Lookups
+
+Multiple `.find()` calls by the same key should use a Map.
+
+**Incorrect (O(n) per lookup):**
+
+```typescript
+function processOrders(orders: Order[], users: User[]) {
+ return orders.map(order => ({
+ ...order,
+ user: users.find(u => u.id === order.userId)
+ }))
+}
+```
+
+**Correct (O(1) per lookup):**
+
+```typescript
+function processOrders(orders: Order[], users: User[]) {
+ const userById = new Map(users.map(u => [u.id, u]))
+
+ return orders.map(order => ({
+ ...order,
+ user: userById.get(order.userId)
+ }))
+}
+```
+
+Build map once (O(n)), then all lookups are O(1).
+For 1000 orders × 1000 users: 1M ops → 2K ops.
diff --git a/.ai/references/vercel-react-best-practices/rules/js-length-check-first.md b/.ai/references/vercel-react-best-practices/rules/js-length-check-first.md
new file mode 100644
index 00000000..8b895736
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-length-check-first.md
@@ -0,0 +1,49 @@
+---
+title: Early Length Check for Array Comparisons
+impact: MEDIUM-HIGH
+impactDescription: avoids expensive operations when lengths differ
+tags: javascript, arrays, performance, optimization, comparison
+---
+
+## Early Length Check for Array Comparisons
+
+When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
+
+In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
+
+**Incorrect (always runs expensive comparison):**
+
+```typescript
+function hasChanges(current: string[], original: string[]) {
+ // Always sorts and joins, even when lengths differ
+ return current.sort().join() !== original.sort().join()
+}
+```
+
+Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
+
+**Correct (O(1) length check first):**
+
+```typescript
+function hasChanges(current: string[], original: string[]) {
+ // Early return if lengths differ
+ if (current.length !== original.length) {
+ return true
+ }
+ // Only sort when lengths match
+ const currentSorted = current.toSorted()
+ const originalSorted = original.toSorted()
+ for (let i = 0; i < currentSorted.length; i++) {
+ if (currentSorted[i] !== originalSorted[i]) {
+ return true
+ }
+ }
+ return false
+}
+```
+
+This new approach is more efficient because:
+- It avoids the overhead of sorting and joining the arrays when lengths differ
+- It avoids consuming memory for the joined strings (especially important for large arrays)
+- It avoids mutating the original arrays
+- It returns early when a difference is found
diff --git a/.ai/references/vercel-react-best-practices/rules/js-min-max-loop.md b/.ai/references/vercel-react-best-practices/rules/js-min-max-loop.md
new file mode 100644
index 00000000..60029866
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-min-max-loop.md
@@ -0,0 +1,82 @@
+---
+title: Use Loop for Min/Max Instead of Sort
+impact: LOW
+impactDescription: O(n) instead of O(n log n)
+tags: javascript, arrays, performance, sorting, algorithms
+---
+
+## Use Loop for Min/Max Instead of Sort
+
+Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
+
+**Incorrect (O(n log n) - sort to find latest):**
+
+```typescript
+interface Project {
+ id: string
+ name: string
+ updatedAt: number
+}
+
+function getLatestProject(projects: Project[]) {
+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
+ return sorted[0]
+}
+```
+
+Sorts the entire array just to find the maximum value.
+
+**Incorrect (O(n log n) - sort for oldest and newest):**
+
+```typescript
+function getOldestAndNewest(projects: Project[]) {
+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
+}
+```
+
+Still sorts unnecessarily when only min/max are needed.
+
+**Correct (O(n) - single loop):**
+
+```typescript
+function getLatestProject(projects: Project[]) {
+ if (projects.length === 0) return null
+
+ let latest = projects[0]
+
+ for (let i = 1; i < projects.length; i++) {
+ if (projects[i].updatedAt > latest.updatedAt) {
+ latest = projects[i]
+ }
+ }
+
+ return latest
+}
+
+function getOldestAndNewest(projects: Project[]) {
+ if (projects.length === 0) return { oldest: null, newest: null }
+
+ let oldest = projects[0]
+ let newest = projects[0]
+
+ for (let i = 1; i < projects.length; i++) {
+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
+ }
+
+ return { oldest, newest }
+}
+```
+
+Single pass through the array, no copying, no sorting.
+
+**Alternative (Math.min/Math.max for small arrays):**
+
+```typescript
+const numbers = [5, 2, 8, 1, 9]
+const min = Math.min(...numbers)
+const max = Math.max(...numbers)
+```
+
+This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
diff --git a/.ai/references/vercel-react-best-practices/rules/js-request-idle-callback.md b/.ai/references/vercel-react-best-practices/rules/js-request-idle-callback.md
new file mode 100644
index 00000000..d81927e5
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-request-idle-callback.md
@@ -0,0 +1,105 @@
+---
+title: Defer Non-Critical Work with requestIdleCallback
+impact: MEDIUM
+impactDescription: keeps UI responsive during background tasks
+tags: javascript, performance, idle, scheduling, analytics
+---
+
+## Defer Non-Critical Work with requestIdleCallback
+
+**Impact: MEDIUM (keeps UI responsive during background tasks)**
+
+Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
+
+**Incorrect (blocks main thread during user interaction):**
+
+```typescript
+function handleSearch(query: string) {
+ const results = searchItems(query)
+ setResults(results)
+
+ // These block the main thread immediately
+ analytics.track('search', { query })
+ saveToRecentSearches(query)
+ prefetchTopResults(results.slice(0, 3))
+}
+```
+
+**Correct (defers non-critical work to idle time):**
+
+```typescript
+function handleSearch(query: string) {
+ const results = searchItems(query)
+ setResults(results)
+
+ // Defer non-critical work to idle periods
+ requestIdleCallback(() => {
+ analytics.track('search', { query })
+ })
+
+ requestIdleCallback(() => {
+ saveToRecentSearches(query)
+ })
+
+ requestIdleCallback(() => {
+ prefetchTopResults(results.slice(0, 3))
+ })
+}
+```
+
+**With timeout for required work:**
+
+```typescript
+// Ensure analytics fires within 2 seconds even if browser stays busy
+requestIdleCallback(
+ () => analytics.track('page_view', { path: location.pathname }),
+ { timeout: 2000 }
+)
+```
+
+**Chunking large tasks:**
+
+```typescript
+function processLargeDataset(items: Item[]) {
+ let index = 0
+
+ function processChunk(deadline: IdleDeadline) {
+ // Process items while we have idle time (aim for <50ms chunks)
+ while (index < items.length && deadline.timeRemaining() > 0) {
+ processItem(items[index])
+ index++
+ }
+
+ // Schedule next chunk if more items remain
+ if (index < items.length) {
+ requestIdleCallback(processChunk)
+ }
+ }
+
+ requestIdleCallback(processChunk)
+}
+```
+
+**With fallback for unsupported browsers:**
+
+```typescript
+const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
+
+scheduleIdleWork(() => {
+ // Non-critical work
+})
+```
+
+**When to use:**
+
+- Analytics and telemetry
+- Saving state to localStorage/IndexedDB
+- Prefetching resources for likely next actions
+- Processing non-urgent data transformations
+- Lazy initialization of non-critical features
+
+**When NOT to use:**
+
+- User-initiated actions that need immediate feedback
+- Rendering updates the user is waiting for
+- Time-sensitive operations
diff --git a/.ai/references/vercel-react-best-practices/rules/js-set-map-lookups.md b/.ai/references/vercel-react-best-practices/rules/js-set-map-lookups.md
new file mode 100644
index 00000000..680a4892
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-set-map-lookups.md
@@ -0,0 +1,24 @@
+---
+title: Use Set/Map for O(1) Lookups
+impact: LOW-MEDIUM
+impactDescription: O(n) to O(1)
+tags: javascript, set, map, data-structures, performance
+---
+
+## Use Set/Map for O(1) Lookups
+
+Convert arrays to Set/Map for repeated membership checks.
+
+**Incorrect (O(n) per check):**
+
+```typescript
+const allowedIds = ['a', 'b', 'c', ...]
+items.filter(item => allowedIds.includes(item.id))
+```
+
+**Correct (O(1) per check):**
+
+```typescript
+const allowedIds = new Set(['a', 'b', 'c', ...])
+items.filter(item => allowedIds.has(item.id))
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/js-tosorted-immutable.md b/.ai/references/vercel-react-best-practices/rules/js-tosorted-immutable.md
new file mode 100644
index 00000000..eae8b3f8
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/js-tosorted-immutable.md
@@ -0,0 +1,57 @@
+---
+title: Use toSorted() Instead of sort() for Immutability
+impact: MEDIUM-HIGH
+impactDescription: prevents mutation bugs in React state
+tags: javascript, arrays, immutability, react, state, mutation
+---
+
+## Use toSorted() Instead of sort() for Immutability
+
+`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
+
+**Incorrect (mutates original array):**
+
+```typescript
+function UserList({ users }: { users: User[] }) {
+ // Mutates the users prop array!
+ const sorted = useMemo(
+ () => users.sort((a, b) => a.name.localeCompare(b.name)),
+ [users]
+ )
+ return
+ )
+}
+```
+
+This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-conditional-render.md b/.ai/references/vercel-react-best-practices/rules/rendering-conditional-render.md
new file mode 100644
index 00000000..7e866f58
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rendering-conditional-render.md
@@ -0,0 +1,40 @@
+---
+title: Use Explicit Conditional Rendering
+impact: LOW
+impactDescription: prevents rendering 0 or NaN
+tags: rendering, conditional, jsx, falsy-values
+---
+
+## Use Explicit Conditional Rendering
+
+Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
+
+**Incorrect (renders "0" when count is 0):**
+
+```tsx
+function Badge({ count }: { count: number }) {
+ return (
+
+ {count && {count}}
+
+ )
+}
+
+// When count = 0, renders:
0
+// When count = 5, renders:
5
+```
+
+**Correct (renders nothing when count is 0):**
+
+```tsx
+function Badge({ count }: { count: number }) {
+ return (
+
+ {count > 0 ? {count} : null}
+
+ )
+}
+
+// When count = 0, renders:
+// When count = 5, renders:
+ )
+}
+```
+
+This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md b/.ai/references/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md
new file mode 100644
index 00000000..340cdd4e
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md
@@ -0,0 +1,82 @@
+---
+title: Render Client-Stored Values Without Flickering
+impact: MEDIUM
+impactDescription: avoids visual flicker and unexpected hydration warnings
+tags: rendering, ssr, hydration, localStorage, flicker
+---
+
+## Render Client-Stored Values Without Flickering
+
+When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
+
+**Incorrect (breaks SSR):**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ // localStorage is not available on server - throws error
+ const theme = localStorage.getItem('theme') || 'light'
+
+ return (
+
+ )
+}
+```
+
+Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
+
+**Correct (no flicker; the expected mismatch is marked as intentional):**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ return (
+ <>
+
+ {children}
+
+
+ >
+ )
+}
+```
+
+The inline script executes synchronously before the element is painted, so the stored theme shows immediately with no flicker. The element's class then differs from what React rendered, which React reports as a hydration mismatch. `suppressHydrationWarning` marks that difference as intentional for this element's own attributes only; its children are still checked. Without it, the pattern prevents the flash but not the mismatch.
+
+This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md b/.ai/references/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md
new file mode 100644
index 00000000..24ba2513
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md
@@ -0,0 +1,30 @@
+---
+title: Suppress Expected Hydration Mismatches
+impact: LOW-MEDIUM
+impactDescription: avoids noisy hydration warnings for known differences
+tags: rendering, hydration, ssr, nextjs
+---
+
+## Suppress Expected Hydration Mismatches
+
+In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
+
+**Incorrect (known mismatch warnings):**
+
+```tsx
+function Timestamp() {
+ return {new Date().toLocaleString()}
+}
+```
+
+**Correct (suppress expected mismatch only):**
+
+```tsx
+function Timestamp() {
+ return (
+
+ {new Date().toLocaleString()}
+
+ )
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-resource-hints.md b/.ai/references/vercel-react-best-practices/rules/rendering-resource-hints.md
new file mode 100644
index 00000000..1290bef0
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rendering-resource-hints.md
@@ -0,0 +1,85 @@
+---
+title: Use React DOM Resource Hints
+impact: HIGH
+impactDescription: reduces load time for critical resources
+tags: rendering, preload, preconnect, prefetch, resource-hints
+---
+
+## Use React DOM Resource Hints
+
+**Impact: HIGH (reduces load time for critical resources)**
+
+React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
+
+- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
+- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
+- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
+- **`preloadModule(href)`**: Fetch an ES module you'll use soon
+- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
+- **`preinitModule(href)`**: Fetch and evaluate an ES module
+
+**Example (preconnect to third-party APIs):**
+
+```tsx
+import { preconnect, prefetchDNS } from 'react-dom'
+
+export default function App() {
+ prefetchDNS('https://analytics.example.com')
+ preconnect('https://api.example.com')
+
+ return {/* content */}
+}
+```
+
+**Example (preload critical fonts and styles):**
+
+```tsx
+import { preload, preinit } from 'react-dom'
+
+export default function RootLayout({ children }) {
+ // Preload font file
+ preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
+
+ // Fetch and apply critical stylesheet immediately
+ preinit('/styles/critical.css', { as: 'style' })
+
+ return (
+
+ {children}
+
+ )
+}
+```
+
+**Example (preload modules for code-split routes):**
+
+```tsx
+import { preloadModule, preinitModule } from 'react-dom'
+
+function Navigation() {
+ const preloadDashboard = () => {
+ preloadModule('/dashboard.js', { as: 'script' })
+ }
+
+ return (
+
+ )
+}
+```
+
+**When to use each:**
+
+| API | Use case |
+|-----|----------|
+| `prefetchDNS` | Third-party domains you'll connect to later |
+| `preconnect` | APIs or CDNs you'll fetch from immediately |
+| `preload` | Critical resources needed for current page |
+| `preloadModule` | JS modules for likely next navigation |
+| `preinit` | Stylesheets/scripts that must execute early |
+| `preinitModule` | ES modules that must execute early |
+
+Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-script-defer-async.md b/.ai/references/vercel-react-best-practices/rules/rendering-script-defer-async.md
new file mode 100644
index 00000000..ee275ed1
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rendering-script-defer-async.md
@@ -0,0 +1,68 @@
+---
+title: Use defer or async on Script Tags
+impact: HIGH
+impactDescription: eliminates render-blocking
+tags: rendering, script, defer, async, performance
+---
+
+## Use defer or async on Script Tags
+
+**Impact: HIGH (eliminates render-blocking)**
+
+Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
+
+- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
+- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
+
+Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
+
+**Incorrect (blocks rendering):**
+
+```tsx
+export default function Document() {
+ return (
+
+
+
+
+
+ {/* content */}
+
+ )
+}
+```
+
+**Correct (non-blocking):**
+
+```tsx
+export default function Document() {
+ return (
+
+
+ {/* Independent script - use async */}
+
+ {/* DOM-dependent script - use defer */}
+
+
+ {/* content */}
+
+ )
+}
+```
+
+**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
+
+```tsx
+import Script from 'next/script'
+
+export default function Page() {
+ return (
+ <>
+
+
+ >
+ )
+}
+```
+
+Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-svg-precision.md b/.ai/references/vercel-react-best-practices/rules/rendering-svg-precision.md
new file mode 100644
index 00000000..6d771286
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rendering-svg-precision.md
@@ -0,0 +1,28 @@
+---
+title: Optimize SVG Precision
+impact: LOW
+impactDescription: reduces file size
+tags: rendering, svg, optimization, svgo
+---
+
+## Optimize SVG Precision
+
+Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
+
+**Incorrect (excessive precision):**
+
+```svg
+
+```
+
+**Correct (1 decimal place):**
+
+```svg
+
+```
+
+**Automate with SVGO:**
+
+```bash
+npx svgo --precision=1 --multipass icon.svg
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-usetransition-loading.md b/.ai/references/vercel-react-best-practices/rules/rendering-usetransition-loading.md
new file mode 100644
index 00000000..7533e51a
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rendering-usetransition-loading.md
@@ -0,0 +1,79 @@
+---
+title: Use useTransition Over Manual Loading States
+impact: LOW
+impactDescription: reduces re-renders and improves code clarity
+tags: rendering, transitions, useTransition, loading, state
+---
+
+## Use useTransition Over Manual Loading States
+
+Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
+
+**Incorrect (manual loading state):**
+
+```tsx
+function SearchResults() {
+ const [query, setQuery] = useState('')
+ const [results, setResults] = useState([])
+ const [isLoading, setIsLoading] = useState(false)
+
+ const handleSearch = async (value: string) => {
+ setIsLoading(true)
+ setQuery(value)
+ const data = await fetchResults(value)
+ setResults(data)
+ setIsLoading(false)
+ }
+
+ return (
+ <>
+ handleSearch(e.target.value)} />
+ {isLoading && }
+
+ >
+ )
+}
+```
+
+**Correct (useTransition with built-in pending state):**
+
+```tsx
+import { useRef, useTransition, useState } from 'react'
+
+function SearchResults() {
+ const [query, setQuery] = useState('')
+ const [results, setResults] = useState([])
+ const [isPending, startTransition] = useTransition()
+ const latestRequest = useRef(0)
+
+ const handleSearch = (value: string) => {
+ setQuery(value) // Update input immediately
+ const request = ++latestRequest.current
+
+ startTransition(async () => {
+ const data = await fetchResults(value)
+ // A newer search may have started; never let an older response win.
+ if (request !== latestRequest.current) return
+ // Updates after an await must be wrapped again to stay in the transition.
+ startTransition(() => setResults(data))
+ })
+ }
+
+ return (
+ <>
+ handleSearch(e.target.value)} />
+ {isPending && }
+
+ >
+ )
+}
+```
+
+**Benefits:**
+
+- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
+- **Error resilience**: Pending state correctly resets even if the transition throws
+- **Better responsiveness**: Keeps the UI responsive during updates
+- **No cancellation**: A transition does not cancel an earlier request. Ignore stale responses, as above, or abort them with an `AbortController`
+
+Reference: [useTransition](https://react.dev/reference/react/useTransition)
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-defer-reads.md b/.ai/references/vercel-react-best-practices/rules/rerender-defer-reads.md
new file mode 100644
index 00000000..e867c95f
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-defer-reads.md
@@ -0,0 +1,39 @@
+---
+title: Defer State Reads to Usage Point
+impact: MEDIUM
+impactDescription: avoids unnecessary subscriptions
+tags: rerender, searchParams, localStorage, optimization
+---
+
+## Defer State Reads to Usage Point
+
+Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
+
+**Incorrect (subscribes to all searchParams changes):**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const searchParams = useSearchParams()
+
+ const handleShare = () => {
+ const ref = searchParams.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return
+}
+```
+
+**Correct (reads on demand, no subscription):**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const handleShare = () => {
+ const params = new URLSearchParams(window.location.search)
+ const ref = params.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-dependencies.md b/.ai/references/vercel-react-best-practices/rules/rerender-dependencies.md
new file mode 100644
index 00000000..47a4d926
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-dependencies.md
@@ -0,0 +1,45 @@
+---
+title: Narrow Effect Dependencies
+impact: LOW
+impactDescription: minimizes effect re-runs
+tags: rerender, useEffect, dependencies, optimization
+---
+
+## Narrow Effect Dependencies
+
+Specify primitive dependencies instead of objects to minimize effect re-runs.
+
+**Incorrect (re-runs on any user field change):**
+
+```tsx
+useEffect(() => {
+ console.log(user.id)
+}, [user])
+```
+
+**Correct (re-runs only when id changes):**
+
+```tsx
+useEffect(() => {
+ console.log(user.id)
+}, [user.id])
+```
+
+**For derived state, compute outside effect:**
+
+```tsx
+// Incorrect: runs on width=767, 766, 765...
+useEffect(() => {
+ if (width < 768) {
+ enableMobileMode()
+ }
+}, [width])
+
+// Correct: runs only on boolean transition
+const isMobile = width < 768
+useEffect(() => {
+ if (isMobile) {
+ enableMobileMode()
+ }
+}, [isMobile])
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md b/.ai/references/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md
new file mode 100644
index 00000000..3d9fe405
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md
@@ -0,0 +1,40 @@
+---
+title: Calculate Derived State During Rendering
+impact: MEDIUM
+impactDescription: avoids redundant renders and state drift
+tags: rerender, derived-state, useEffect, state
+---
+
+## Calculate Derived State During Rendering
+
+If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
+
+**Incorrect (redundant state and effect):**
+
+```tsx
+function Form() {
+ const [firstName, setFirstName] = useState('First')
+ const [lastName, setLastName] = useState('Last')
+ const [fullName, setFullName] = useState('')
+
+ useEffect(() => {
+ setFullName(firstName + ' ' + lastName)
+ }, [firstName, lastName])
+
+ return
+}
+```
+
+References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-derived-state.md b/.ai/references/vercel-react-best-practices/rules/rerender-derived-state.md
new file mode 100644
index 00000000..e5c899f6
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-derived-state.md
@@ -0,0 +1,29 @@
+---
+title: Subscribe to Derived State
+impact: MEDIUM
+impactDescription: reduces re-render frequency
+tags: rerender, derived-state, media-query, optimization
+---
+
+## Subscribe to Derived State
+
+Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
+
+**Incorrect (re-renders on every pixel change):**
+
+```tsx
+function Sidebar() {
+ const width = useWindowWidth() // updates continuously
+ const isMobile = width < 768
+ return
+}
+```
+
+**Correct (re-renders only when boolean changes):**
+
+```tsx
+function Sidebar() {
+ const isMobile = useMediaQuery('(max-width: 767px)')
+ return
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-functional-setstate.md b/.ai/references/vercel-react-best-practices/rules/rerender-functional-setstate.md
new file mode 100644
index 00000000..69d224ed
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-functional-setstate.md
@@ -0,0 +1,74 @@
+---
+title: Use Functional setState Updates
+impact: MEDIUM
+impactDescription: prevents stale closures and unnecessary callback recreations
+tags: react, hooks, useState, useCallback, callbacks, closures
+---
+
+## Use Functional setState Updates
+
+When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
+
+**Incorrect (requires state as dependency):**
+
+```tsx
+function TodoList() {
+ const [items, setItems] = useState(initialItems)
+
+ // Callback must depend on items, recreated on every items change
+ const addItems = useCallback((newItems: Item[]) => {
+ setItems([...items, ...newItems])
+ }, [items]) // ❌ items dependency causes recreations
+
+ // Risk of stale closure if dependency is forgotten
+ const removeItem = useCallback((id: string) => {
+ setItems(items.filter(item => item.id !== id))
+ }, []) // ❌ Missing items dependency - will use stale items!
+
+ return
+}
+```
+
+The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
+
+**Correct (stable callbacks, no stale closures):**
+
+```tsx
+function TodoList() {
+ const [items, setItems] = useState(initialItems)
+
+ // Stable callback, never recreated
+ const addItems = useCallback((newItems: Item[]) => {
+ setItems(curr => [...curr, ...newItems])
+ }, []) // ✅ No dependencies needed
+
+ // Always uses latest state, no stale closure risk
+ const removeItem = useCallback((id: string) => {
+ setItems(curr => curr.filter(item => item.id !== id))
+ }, []) // ✅ Safe and stable
+
+ return
+}
+```
+
+**Benefits:**
+
+1. **Stable callback references** - Callbacks don't need to be recreated when state changes
+2. **No stale closures** - Always operates on the latest state value
+3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
+4. **Prevents bugs** - Eliminates the most common source of React closure bugs
+
+**When to use functional updates:**
+
+- Any setState that depends on the current state value
+- Inside useCallback/useMemo when state is needed
+- Event handlers that reference state
+- Async operations that update state
+
+**When direct updates are fine:**
+
+- Setting state to a static value: `setCount(0)`
+- Setting state from props/arguments only: `setName(newName)`
+- State doesn't depend on previous value
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-lazy-state-init.md b/.ai/references/vercel-react-best-practices/rules/rerender-lazy-state-init.md
new file mode 100644
index 00000000..d86d827d
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-lazy-state-init.md
@@ -0,0 +1,58 @@
+---
+title: Use Lazy State Initialization
+impact: MEDIUM
+impactDescription: wasted computation on every render
+tags: react, hooks, useState, performance, initialization
+---
+
+## Use Lazy State Initialization
+
+Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
+
+**Incorrect (runs on every render):**
+
+```tsx
+function FilteredList({ items }: { items: Item[] }) {
+ // buildSearchIndex() runs on EVERY render, even after initialization
+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
+ const [query, setQuery] = useState('')
+
+ // When query changes, buildSearchIndex runs again unnecessarily
+ return
+}
+
+function UserProfile() {
+ // JSON.parse runs on every render
+ const [settings, setSettings] = useState(
+ JSON.parse(localStorage.getItem('settings') || '{}')
+ )
+
+ return
+}
+```
+
+**Correct (runs only once):**
+
+```tsx
+function FilteredList({ items }: { items: Item[] }) {
+ // buildSearchIndex() runs ONLY on initial render
+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
+ const [query, setQuery] = useState('')
+
+ return
+}
+
+function UserProfile() {
+ // JSON.parse runs only on initial render
+ const [settings, setSettings] = useState(() => {
+ const stored = localStorage.getItem('settings')
+ return stored ? JSON.parse(stored) : {}
+ })
+
+ return
+}
+```
+
+Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
+
+For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-memo-with-default-value.md b/.ai/references/vercel-react-best-practices/rules/rerender-memo-with-default-value.md
new file mode 100644
index 00000000..63570491
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-memo-with-default-value.md
@@ -0,0 +1,38 @@
+---
+
+title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
+impact: MEDIUM
+impactDescription: restores memoization by using a constant for default value
+tags: rerender, memo, optimization
+
+---
+
+## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
+
+When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
+
+To address this issue, extract the default value into a constant.
+
+**Incorrect (`onClick` has different values on every rerender):**
+
+```tsx
+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
+ // ...
+})
+
+// Used without optional onClick
+
+```
+
+**Correct (stable default value):**
+
+```tsx
+const NOOP = () => {};
+
+const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
+ // ...
+})
+
+// Used without optional onClick
+
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-memo.md b/.ai/references/vercel-react-best-practices/rules/rerender-memo.md
new file mode 100644
index 00000000..f8982ab6
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-memo.md
@@ -0,0 +1,44 @@
+---
+title: Extract to Memoized Components
+impact: MEDIUM
+impactDescription: enables early returns
+tags: rerender, memo, useMemo, optimization
+---
+
+## Extract to Memoized Components
+
+Extract expensive work into memoized components to enable early returns before computation.
+
+**Incorrect (computes avatar even when loading):**
+
+```tsx
+function Profile({ user, loading }: Props) {
+ const avatar = useMemo(() => {
+ const id = computeAvatarId(user)
+ return
+ }, [user])
+
+ if (loading) return
+ return
{avatar}
+}
+```
+
+**Correct (skips computation when loading):**
+
+```tsx
+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
+ const id = useMemo(() => computeAvatarId(user), [user])
+ return
+})
+
+function Profile({ user, loading }: Props) {
+ if (loading) return
+ return (
+
+
+
+ )
+}
+```
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-move-effect-to-event.md b/.ai/references/vercel-react-best-practices/rules/rerender-move-effect-to-event.md
new file mode 100644
index 00000000..dd58a1af
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-move-effect-to-event.md
@@ -0,0 +1,45 @@
+---
+title: Put Interaction Logic in Event Handlers
+impact: MEDIUM
+impactDescription: avoids effect re-runs and duplicate side effects
+tags: rerender, useEffect, events, side-effects, dependencies
+---
+
+## Put Interaction Logic in Event Handlers
+
+If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
+
+**Incorrect (event modeled as state + effect):**
+
+```tsx
+function Form() {
+ const [submitted, setSubmitted] = useState(false)
+ const theme = useContext(ThemeContext)
+
+ useEffect(() => {
+ if (submitted) {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+ }, [submitted, theme])
+
+ return
+}
+```
+
+**Correct (do it in the handler):**
+
+```tsx
+function Form() {
+ const theme = useContext(ThemeContext)
+
+ function handleSubmit() {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+
+ return
+}
+```
+
+Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-no-inline-components.md b/.ai/references/vercel-react-best-practices/rules/rerender-no-inline-components.md
new file mode 100644
index 00000000..d97592ac
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-no-inline-components.md
@@ -0,0 +1,82 @@
+---
+title: Don't Define Components Inside Components
+impact: HIGH
+impactDescription: prevents remount on every render
+tags: rerender, components, remount, performance
+---
+
+## Don't Define Components Inside Components
+
+**Impact: HIGH (prevents remount on every render)**
+
+Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
+
+A common reason developers do this is to access parent variables without passing props. Always pass props instead.
+
+**Incorrect (remounts on every render):**
+
+```tsx
+function UserProfile({ user, theme }) {
+ // Defined inside to access `theme` - BAD
+ const Avatar = () => (
+
+ )
+
+ // Defined inside to access `user` - BAD
+ const Stats = () => (
+
+ )
+}
+```
+
+**Symptoms of this bug:**
+- Input fields lose focus on every keystroke
+- Animations restart unexpectedly
+- `useEffect` cleanup/setup runs on every parent render
+- Scroll position resets inside the component
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md b/.ai/references/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md
new file mode 100644
index 00000000..59dfab0f
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md
@@ -0,0 +1,35 @@
+---
+title: Do not wrap a simple expression with a primitive result type in useMemo
+impact: LOW-MEDIUM
+impactDescription: wasted computation on every render
+tags: rerender, useMemo, optimization
+---
+
+## Do not wrap a simple expression with a primitive result type in useMemo
+
+When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
+Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
+
+**Incorrect:**
+
+```tsx
+function Header({ user, notifications }: Props) {
+ const isLoading = useMemo(() => {
+ return user.isLoading || notifications.isLoading
+ }, [user.isLoading, notifications.isLoading])
+
+ if (isLoading) return
+ // return some markup
+}
+```
+
+**Correct:**
+
+```tsx
+function Header({ user, notifications }: Props) {
+ const isLoading = user.isLoading || notifications.isLoading
+
+ if (isLoading) return
+ // return some markup
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-split-combined-hooks.md b/.ai/references/vercel-react-best-practices/rules/rerender-split-combined-hooks.md
new file mode 100644
index 00000000..89d80564
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-split-combined-hooks.md
@@ -0,0 +1,64 @@
+---
+title: Split Combined Hook Computations
+impact: MEDIUM
+impactDescription: avoids recomputing independent steps
+tags: rerender, useMemo, useEffect, dependencies, optimization
+---
+
+## Split Combined Hook Computations
+
+When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
+
+**Incorrect (changing `sortOrder` recomputes filtering):**
+
+```tsx
+const sortedProducts = useMemo(() => {
+ const filtered = products.filter((p) => p.category === category)
+ const sorted = filtered.toSorted((a, b) =>
+ sortOrder === "asc" ? a.price - b.price : b.price - a.price
+ )
+ return sorted
+}, [products, category, sortOrder])
+```
+
+**Correct (filtering only recomputes when products or category change):**
+
+```tsx
+const filteredProducts = useMemo(
+ () => products.filter((p) => p.category === category),
+ [products, category]
+)
+
+const sortedProducts = useMemo(
+ () =>
+ filteredProducts.toSorted((a, b) =>
+ sortOrder === "asc" ? a.price - b.price : b.price - a.price
+ ),
+ [filteredProducts, sortOrder]
+)
+```
+
+This pattern also applies to `useEffect` when combining unrelated side effects:
+
+**Incorrect (both effects run when either dependency changes):**
+
+```tsx
+useEffect(() => {
+ analytics.trackPageView(pathname)
+ document.title = `${pageTitle} | My App`
+}, [pathname, pageTitle])
+```
+
+**Correct (effects run independently):**
+
+```tsx
+useEffect(() => {
+ analytics.trackPageView(pathname)
+}, [pathname])
+
+useEffect(() => {
+ document.title = `${pageTitle} | My App`
+}, [pageTitle])
+```
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-transitions.md b/.ai/references/vercel-react-best-practices/rules/rerender-transitions.md
new file mode 100644
index 00000000..d99f43f7
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-transitions.md
@@ -0,0 +1,40 @@
+---
+title: Use Transitions for Non-Urgent Updates
+impact: MEDIUM
+impactDescription: maintains UI responsiveness
+tags: rerender, transitions, startTransition, performance
+---
+
+## Use Transitions for Non-Urgent Updates
+
+Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
+
+**Incorrect (blocks UI on every scroll):**
+
+```tsx
+function ScrollTracker() {
+ const [scrollY, setScrollY] = useState(0)
+ useEffect(() => {
+ const handler = () => setScrollY(window.scrollY)
+ window.addEventListener('scroll', handler, { passive: true })
+ return () => window.removeEventListener('scroll', handler)
+ }, [])
+}
+```
+
+**Correct (non-blocking updates):**
+
+```tsx
+import { startTransition } from 'react'
+
+function ScrollTracker() {
+ const [scrollY, setScrollY] = useState(0)
+ useEffect(() => {
+ const handler = () => {
+ startTransition(() => setScrollY(window.scrollY))
+ }
+ window.addEventListener('scroll', handler, { passive: true })
+ return () => window.removeEventListener('scroll', handler)
+ }, [])
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-use-deferred-value.md b/.ai/references/vercel-react-best-practices/rules/rerender-use-deferred-value.md
new file mode 100644
index 00000000..619c04b0
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-use-deferred-value.md
@@ -0,0 +1,59 @@
+---
+title: Use useDeferredValue for Expensive Derived Renders
+impact: MEDIUM
+impactDescription: keeps input responsive during heavy computation
+tags: rerender, useDeferredValue, optimization, concurrent
+---
+
+## Use useDeferredValue for Expensive Derived Renders
+
+When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
+
+**Incorrect (input feels laggy while filtering):**
+
+```tsx
+function Search({ items }: { items: Item[] }) {
+ const [query, setQuery] = useState('')
+ const filtered = items.filter(item => fuzzyMatch(item, query))
+
+ return (
+ <>
+ setQuery(e.target.value)} />
+
+ >
+ )
+}
+```
+
+**Correct (input stays snappy, results render when ready):**
+
+```tsx
+function Search({ items }: { items: Item[] }) {
+ const [query, setQuery] = useState('')
+ const deferredQuery = useDeferredValue(query)
+ const filtered = useMemo(
+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),
+ [items, deferredQuery]
+ )
+ const isStale = query !== deferredQuery
+
+ return (
+ <>
+ setQuery(e.target.value)} />
+
+
+
+ >
+ )
+}
+```
+
+**When to use:**
+
+- Filtering/searching large lists
+- Expensive visualizations (charts, graphs) reacting to input
+- Any derived state that causes noticeable render delays
+
+**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
+
+Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)
diff --git a/.ai/references/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md b/.ai/references/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md
new file mode 100644
index 00000000..cf04b81f
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md
@@ -0,0 +1,73 @@
+---
+title: Use useRef for Transient Values
+impact: MEDIUM
+impactDescription: avoids unnecessary re-renders on frequent updates
+tags: rerender, useref, state, performance
+---
+
+## Use useRef for Transient Values
+
+When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
+
+**Incorrect (renders every update):**
+
+```tsx
+function Tracker() {
+ const [lastX, setLastX] = useState(0)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => setLastX(e.clientX)
+ window.addEventListener('mousemove', onMove)
+ return () => window.removeEventListener('mousemove', onMove)
+ }, [])
+
+ return (
+
+ )
+}
+```
+
+**Correct (no re-render for tracking):**
+
+```tsx
+function Tracker() {
+ const lastXRef = useRef(0)
+ const dotRef = useRef(null)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => {
+ lastXRef.current = e.clientX
+ const node = dotRef.current
+ if (node) {
+ node.style.transform = `translateX(${e.clientX}px)`
+ }
+ }
+ window.addEventListener('mousemove', onMove)
+ return () => window.removeEventListener('mousemove', onMove)
+ }, [])
+
+ return (
+
+ )
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/server-after-nonblocking.md b/.ai/references/vercel-react-best-practices/rules/server-after-nonblocking.md
new file mode 100644
index 00000000..0b6bade0
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-after-nonblocking.md
@@ -0,0 +1,76 @@
+---
+title: Use after() for Non-Blocking Operations
+impact: MEDIUM
+impactDescription: faster response times
+tags: server, async, logging, analytics, side-effects
+---
+
+## Use after() for Non-Blocking Operations
+
+Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
+
+**Incorrect (blocks response):**
+
+```tsx
+import { logUserAction } from '@/app/utils'
+
+export async function POST(request: Request) {
+ // Perform mutation
+ await updateDatabase(request)
+
+ // Logging blocks the response
+ const userAgent = request.headers.get('user-agent') || 'unknown'
+ await logUserAction({ userAgent })
+
+ return new Response(JSON.stringify({ status: 'success' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' }
+ })
+}
+```
+
+**Correct (non-blocking):**
+
+```tsx
+import { after } from 'next/server'
+import { headers } from 'next/headers'
+import { logUserAction } from '@/app/utils'
+
+export async function POST(request: Request) {
+ // Perform mutation
+ await updateDatabase(request)
+
+ // Log after response is sent
+ after(async () => {
+ const userAgent = (await headers()).get('user-agent') || 'unknown'
+
+ // Await the work: after() keeps it alive only until this callback settles.
+ // Never log session cookies or tokens; they are credentials.
+ await logUserAction({ userAgent })
+ })
+
+ return new Response(JSON.stringify({ status: 'success' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' }
+ })
+}
+```
+
+The response is sent immediately while logging happens in the background.
+
+**Common use cases:**
+
+- Analytics tracking
+- Audit logging
+- Sending notifications
+- Cache invalidation
+- Cleanup tasks
+
+**Important notes:**
+
+- `after()` runs even if the response fails or redirects
+- Works in Server Actions, Route Handlers, and Server Components
+- Await or return every promise in the callback; work that is merely started can be cut off when the callback resolves
+- Work in `after()` is lost if the process stops first. Write audit records that must never be lost durably before responding
+
+Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
diff --git a/.ai/references/vercel-react-best-practices/rules/server-auth-actions.md b/.ai/references/vercel-react-best-practices/rules/server-auth-actions.md
new file mode 100644
index 00000000..f5368fca
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-auth-actions.md
@@ -0,0 +1,96 @@
+---
+title: Authenticate Server Actions Like API Routes
+impact: CRITICAL
+impactDescription: prevents unauthorized access to server mutations
+tags: server, server-actions, authentication, security, authorization
+---
+
+## Authenticate Server Actions Like API Routes
+
+**Impact: CRITICAL (prevents unauthorized access to server mutations)**
+
+Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
+
+Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
+
+**Incorrect (no authentication check):**
+
+```typescript
+'use server'
+
+export async function deleteUser(userId: string) {
+ // Anyone can call this! No auth check
+ await db.user.delete({ where: { id: userId } })
+ return { success: true }
+}
+```
+
+**Correct (authentication inside the action):**
+
+```typescript
+'use server'
+
+import { verifySession } from '@/lib/auth'
+import { unauthorized } from '@/lib/errors'
+
+export async function deleteUser(userId: string) {
+ // Always check auth inside the action
+ const session = await verifySession()
+
+ if (!session) {
+ throw unauthorized('Must be logged in')
+ }
+
+ // Check authorization too
+ if (session.user.role !== 'admin' && session.user.id !== userId) {
+ throw unauthorized('Cannot delete other users')
+ }
+
+ await db.user.delete({ where: { id: userId } })
+ return { success: true }
+}
+```
+
+**With input validation:**
+
+```typescript
+'use server'
+
+import { verifySession } from '@/lib/auth'
+import { z } from 'zod'
+
+const updateProfileSchema = z.object({
+ userId: z.string().uuid(),
+ name: z.string().min(1).max(100),
+ email: z.string().email()
+})
+
+export async function updateProfile(data: unknown) {
+ // Validate input first
+ const validated = updateProfileSchema.parse(data)
+
+ // Then authenticate
+ const session = await verifySession()
+ if (!session) {
+ throw new Error('Unauthorized')
+ }
+
+ // Then authorize
+ if (session.user.id !== validated.userId) {
+ throw new Error('Can only update own profile')
+ }
+
+ // Finally perform the mutation
+ await db.user.update({
+ where: { id: validated.userId },
+ data: {
+ name: validated.name,
+ email: validated.email
+ }
+ })
+
+ return { success: true }
+}
+```
+
+Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
diff --git a/.ai/references/vercel-react-best-practices/rules/server-cache-lru.md b/.ai/references/vercel-react-best-practices/rules/server-cache-lru.md
new file mode 100644
index 00000000..b9e6e03b
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-cache-lru.md
@@ -0,0 +1,57 @@
+---
+title: Cross-Request LRU Caching
+impact: HIGH
+impactDescription: caches across requests
+tags: server, cache, lru, cross-request
+---
+
+## Cross-Request LRU Caching
+
+`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
+
+**Implementation:**
+
+```typescript
+import { LRUCache } from 'lru-cache'
+
+const cache = new LRUCache({
+ max: 1000,
+ ttl: 5 * 60 * 1000 // 5 minutes
+})
+
+// Not exported: only reachable after the caller is authorized
+async function loadUser(tenantId: string, id: string) {
+ // Key by every input that changes the result, never by the record ID alone.
+ // Encode the parts unambiguously: with a plain separator, ("a:b", "c") and
+ // ("a", "b:c") would collide when an ID can contain the separator.
+ const key = JSON.stringify([tenantId, id])
+ const cached = cache.get(key)
+ if (cached) return cached
+
+ const user = await db.user.findFirst({ where: { tenantId, id } })
+ cache.set(key, user)
+ return user
+}
+
+export async function getUser(caller: Caller, id: string) {
+ // Authorize on every request, before any cached data can be returned
+ if (!(await canReadUser(caller, id))) {
+ throw new ForbiddenError()
+ }
+ // The tenant comes from the authenticated caller, never from request input
+ return loadUser(caller.tenantId, id)
+}
+
+// Request 1: authorized, DB query, result cached
+// Request 2: authorized again, cache hit, no DB query
+```
+
+Use when sequential user actions hit multiple endpoints needing the same data within seconds.
+
+This cache is shared by every request in the process, so only the unexported loader touches it and every exported entry point authorizes the caller first. Cache only data that is identical for every caller allowed to see it, and never cache the authorization decision or caller-specific views. Keep the TTL short, because permission and data changes take effect only when an entry expires.
+
+**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
+
+**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
+
+Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
diff --git a/.ai/references/vercel-react-best-practices/rules/server-cache-react.md b/.ai/references/vercel-react-best-practices/rules/server-cache-react.md
new file mode 100644
index 00000000..87c9ca33
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-cache-react.md
@@ -0,0 +1,76 @@
+---
+title: Per-Request Deduplication with React.cache()
+impact: MEDIUM
+impactDescription: deduplicates within request
+tags: server, cache, react-cache, deduplication
+---
+
+## Per-Request Deduplication with React.cache()
+
+Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
+
+**Usage:**
+
+```typescript
+import { cache } from 'react'
+
+export const getCurrentUser = cache(async () => {
+ const session = await auth()
+ if (!session?.user?.id) return null
+ return await db.user.findUnique({
+ where: { id: session.user.id }
+ })
+})
+```
+
+Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
+
+**Avoid inline objects as arguments:**
+
+`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
+
+**Incorrect (always cache miss):**
+
+```typescript
+const getUser = cache(async (params: { uid: number }) => {
+ return await db.user.findUnique({ where: { id: params.uid } })
+})
+
+// Each call creates new object, never hits cache
+getUser({ uid: 1 })
+getUser({ uid: 1 }) // Cache miss, runs query again
+```
+
+**Correct (cache hit):**
+
+```typescript
+const getUser = cache(async (uid: number) => {
+ return await db.user.findUnique({ where: { id: uid } })
+})
+
+// Primitive args use value equality
+getUser(1)
+getUser(1) // Cache hit, returns cached result
+```
+
+If you must pass objects, pass the same reference:
+
+```typescript
+const params = { uid: 1 }
+getUser(params) // Query runs
+getUser(params) // Cache hit (same reference)
+```
+
+**Next.js-Specific Note:**
+
+In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
+
+- Database queries (Prisma, Drizzle, etc.)
+- Heavy computations
+- Authentication checks
+- File system operations
+- Any non-fetch async work
+
+Use `React.cache()` to deduplicate these operations across your component tree.
+
+Reference: [React.cache documentation](https://react.dev/reference/react/cache)
diff --git a/.ai/references/vercel-react-best-practices/rules/server-dedup-props.md b/.ai/references/vercel-react-best-practices/rules/server-dedup-props.md
new file mode 100644
index 00000000..fb24a256
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-dedup-props.md
@@ -0,0 +1,65 @@
+---
+title: Avoid Duplicate Serialization in RSC Props
+impact: LOW
+impactDescription: reduces network payload by avoiding duplicate serialization
+tags: server, rsc, serialization, props, client-components
+---
+
+## Avoid Duplicate Serialization in RSC Props
+
+**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
+
+RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
+
+**Incorrect (duplicates array):**
+
+```tsx
+// RSC: sends 6 strings (2 arrays × 3 items)
+
+```
+
+**Correct (sends 3 strings):**
+
+```tsx
+// RSC: send once
+
+
+// Client: transform there
+'use client'
+const sorted = useMemo(() => [...usernames].sort(), [usernames])
+```
+
+**Nested deduplication behavior:**
+
+Deduplication works recursively. Impact varies by data type:
+
+- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
+- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
+
+```tsx
+// string[] - duplicates everything
+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
+
+// object[] - duplicates array structure only
+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
+```
+
+**Operations breaking deduplication (create new references):**
+
+- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
+- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
+
+**More examples:**
+
+```tsx
+// ❌ Bad
+ u.active)} />
+
+
+// ✅ Good
+
+
+// Do filtering/destructuring in client
+```
+
+**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
diff --git a/.ai/references/vercel-react-best-practices/rules/server-hoist-static-io.md b/.ai/references/vercel-react-best-practices/rules/server-hoist-static-io.md
new file mode 100644
index 00000000..25205c2f
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-hoist-static-io.md
@@ -0,0 +1,149 @@
+---
+title: Hoist Static I/O to Module Level
+impact: HIGH
+impactDescription: avoids repeated file/network I/O per request
+tags: server, io, performance, next.js, route-handlers, og-image
+---
+
+## Hoist Static I/O to Module Level
+
+**Impact: HIGH (avoids repeated file/network I/O per request)**
+
+When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
+
+**Incorrect (reads font file on every request):**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+
+export async function GET(request: Request) {
+ // Runs on EVERY request - expensive!
+ const fontData = await fetch(
+ new URL('./fonts/Inter.ttf', import.meta.url)
+ ).then(res => res.arrayBuffer())
+
+ const logoData = await fetch(
+ new URL('./images/logo.png', import.meta.url)
+ ).then(res => res.arrayBuffer())
+
+ return new ImageResponse(
+
+
+ Hello World
+
,
+ { fonts: [{ name: 'Inter', data: fontData }] }
+ )
+}
+```
+
+**Correct (loads once at module initialization):**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+
+// Module-level: runs ONCE when module is first imported
+const fontData = fetch(
+ new URL('./fonts/Inter.ttf', import.meta.url)
+).then(res => res.arrayBuffer())
+
+const logoData = fetch(
+ new URL('./images/logo.png', import.meta.url)
+).then(res => res.arrayBuffer())
+
+export async function GET(request: Request) {
+ // Await the already-started promises
+ const [font, logo] = await Promise.all([fontData, logoData])
+
+ return new ImageResponse(
+
+
+ Hello World
+
,
+ { fonts: [{ name: 'Inter', data: font }] }
+ )
+}
+```
+
+**Correct (synchronous fs at module level):**
+
+```typescript
+// app/api/og/route.tsx
+import { ImageResponse } from 'next/og'
+import { readFileSync } from 'fs'
+import { join } from 'path'
+
+// Synchronous read at module level - blocks only during module init
+const fontData = readFileSync(
+ join(process.cwd(), 'public/fonts/Inter.ttf')
+)
+
+const logoData = readFileSync(
+ join(process.cwd(), 'public/images/logo.png')
+)
+
+export async function GET(request: Request) {
+ return new ImageResponse(
+
+
+ Hello World
+
,
+ { fonts: [{ name: 'Inter', data: fontData }] }
+ )
+}
+```
+
+**Incorrect (reads config on every call):**
+
+```typescript
+import fs from 'node:fs/promises'
+
+export async function processRequest(data: Data) {
+ const config = JSON.parse(
+ await fs.readFile('./config.json', 'utf-8')
+ )
+ const template = await fs.readFile('./template.html', 'utf-8')
+
+ return render(template, data, config)
+}
+```
+
+**Correct (hoists config and template to module level):**
+
+```typescript
+import fs from 'node:fs/promises'
+
+const configPromise = fs
+ .readFile('./config.json', 'utf-8')
+ .then(JSON.parse)
+const templatePromise = fs.readFile('./template.html', 'utf-8')
+
+export async function processRequest(data: Data) {
+ const [config, template] = await Promise.all([
+ configPromise,
+ templatePromise,
+ ])
+
+ return render(template, data, config)
+}
+```
+
+When to use this pattern:
+
+- Loading fonts for OG image generation
+- Loading static logos, icons, or watermarks
+- Reading configuration files that don't change at runtime
+- Loading email templates or other static templates
+- Any static asset that's the same across all requests
+
+When not to use this pattern:
+
+- Assets that vary per request or user
+- Files that may change during runtime (use caching with TTL instead)
+- Large files that would consume too much memory if kept loaded
+- Sensitive data that shouldn't persist in memory
+
+With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
+
+In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
diff --git a/.ai/references/vercel-react-best-practices/rules/server-no-shared-module-state.md b/.ai/references/vercel-react-best-practices/rules/server-no-shared-module-state.md
new file mode 100644
index 00000000..ff7d9f29
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-no-shared-module-state.md
@@ -0,0 +1,50 @@
+---
+title: Avoid Shared Module State for Request Data
+impact: HIGH
+impactDescription: prevents concurrency bugs and request data leaks
+tags: server, rsc, ssr, concurrency, security, state
+---
+
+## Avoid Shared Module State for Request Data
+
+For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.
+
+Treat module scope on the server as process-wide shared memory, not request-local state.
+
+**Incorrect (request data leaks across concurrent renders):**
+
+```tsx
+let currentUser: User | null = null
+
+export default async function Page() {
+ currentUser = await auth()
+ return
+}
+
+async function Dashboard() {
+ return
{currentUser?.name}
+}
+```
+
+If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.
+
+**Correct (keep request data local to the render tree):**
+
+```tsx
+export default async function Page() {
+ const user = await auth()
+ return
+}
+
+function Dashboard({ user }: { user: User | null }) {
+ return
{user?.name}
+}
+```
+
+Safe exceptions:
+
+- Immutable static assets or config loaded once at module scope
+- Shared caches intentionally designed for cross-request reuse and keyed correctly
+- Process-wide singletons that do not store request- or user-specific mutable data
+
+For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).
diff --git a/.ai/references/vercel-react-best-practices/rules/server-parallel-fetching.md b/.ai/references/vercel-react-best-practices/rules/server-parallel-fetching.md
new file mode 100644
index 00000000..1affc835
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-parallel-fetching.md
@@ -0,0 +1,83 @@
+---
+title: Parallel Data Fetching with Component Composition
+impact: CRITICAL
+impactDescription: eliminates server-side waterfalls
+tags: server, rsc, parallel-fetching, composition
+---
+
+## Parallel Data Fetching with Component Composition
+
+React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
+
+**Incorrect (Sidebar waits for Page's fetch to complete):**
+
+```tsx
+export default async function Page() {
+ const header = await fetchHeader()
+ return (
+
+ )
+}
+
+export default function Page() {
+ return (
+
+
+
+ )
+}
+```
diff --git a/.ai/references/vercel-react-best-practices/rules/server-parallel-nested-fetching.md b/.ai/references/vercel-react-best-practices/rules/server-parallel-nested-fetching.md
new file mode 100644
index 00000000..be1dc250
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-parallel-nested-fetching.md
@@ -0,0 +1,34 @@
+---
+title: Parallel Nested Data Fetching
+impact: CRITICAL
+impactDescription: eliminates server-side waterfalls
+tags: server, rsc, parallel-fetching, promise-chaining
+---
+
+## Parallel Nested Data Fetching
+
+When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.
+
+**Incorrect (a single slow item blocks all nested fetches):**
+
+```tsx
+const chats = await Promise.all(
+ chatIds.map(id => getChat(id))
+)
+
+const chatAuthors = await Promise.all(
+ chats.map(chat => getUser(chat.author))
+)
+```
+
+If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.
+
+**Correct (each item chains its own nested fetch):**
+
+```tsx
+const chatAuthors = await Promise.all(
+ chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
+)
+```
+
+Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.
diff --git a/.ai/references/vercel-react-best-practices/rules/server-serialization.md b/.ai/references/vercel-react-best-practices/rules/server-serialization.md
new file mode 100644
index 00000000..39c5c416
--- /dev/null
+++ b/.ai/references/vercel-react-best-practices/rules/server-serialization.md
@@ -0,0 +1,38 @@
+---
+title: Minimize Serialization at RSC Boundaries
+impact: HIGH
+impactDescription: reduces data transfer size
+tags: server, rsc, serialization, props
+---
+
+## Minimize Serialization at RSC Boundaries
+
+The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
+
+**Incorrect (serializes all 50 fields):**
+
+```tsx
+async function Page() {
+ const user = await fetchUser() // 50 fields
+ return
+}
+
+'use client'
+function Profile({ user }: { user: User }) {
+ return
{user.name}
// uses 1 field
+}
+```
+
+**Correct (serializes only 1 field):**
+
+```tsx
+async function Page() {
+ const user = await fetchUser()
+ return
+}
+
+'use client'
+function Profile({ name }: { name: string }) {
+ return
{name}
+}
+```
diff --git a/.ai/skills/vercel-react-best-practices.md b/.ai/skills/vercel-react-best-practices.md
new file mode 100644
index 00000000..1d1f85c9
--- /dev/null
+++ b/.ai/skills/vercel-react-best-practices.md
@@ -0,0 +1,113 @@
+---
+name: vercel-react-best-practices
+description: Apply Vercel React performance guidance when implementing, reviewing, or optimizing the React chat widget, including data fetching, rendering, effects, and bundle size.
+license: MIT
+metadata:
+ author: vercel
+---
+
+# Skill: Vercel React Best Practices
+
+## Purpose
+
+Apply Vercel's performance guidance to Extra's React chat widget. The 70
+upstream rules and examples are available locally under
+`.ai/references/vercel-react-best-practices/rules/`; read the rules relevant
+to the change rather than loading the entire collection.
+
+All paths in this playbook are relative to the repository root, including
+when reading a generated Codex or Claude adapter.
+
+## When to Use This Skill
+
+- Implementing or reviewing components under
+ `src/agent_manager/api/static/widget/react/`.
+- Changing widget effects, event listeners, state, or data fetching.
+- Investigating slow rendering, unnecessary requests, or bundle growth.
+
+## Files to Read First
+
+- `AGENTS.md` and `.ai/skills/project-architecture.md`.
+- `docs/WIDGET_ARCHITECTURE.md` and `docs/WIDGET.md`.
+- `package.json`, the components being changed, and their existing tests.
+- Relevant rules from the local reference directory, using this routing table:
+
+| Concern | Rule prefix | Starting point |
+| --- | --- | --- |
+| Sequential independent requests | `async-` | `async-parallel.md` |
+| Unnecessary module loading | `bundle-` | `bundle-conditional.md` |
+| Duplicate browser subscriptions | `client-` | `client-event-listeners.md` |
+| Stale state or unnecessary renders | `rerender-` | `rerender-functional-setstate.md`, `rerender-dependencies.md` |
+| Expensive rendering | `rendering-` | `rendering-hoist-jsx.md`, `rendering-content-visibility.md` |
+| Repeated JavaScript work | `js-` | `js-set-map-lookups.md`, `js-combine-iterations.md` |
+| Callback and initialization patterns | `advanced-` | `advanced-event-handler-refs.md` |
+| Server rendering, if introduced separately | `server-` | `server-no-shared-module-state.md` |
+
+## Core Principles
+
+- The shipped widget is React inside a custom element and Shadow DOM, bundled
+ with esbuild. Select rules that fit that environment; Next.js routing, RSC,
+ SSR caching, and `next/dynamic` examples do not justify adding Next.js.
+- Prioritize observable request waterfalls, bundle growth, and rendering costs
+ over speculative micro-optimizations. Match APIs to the installed React
+ version and esbuild browser target in `package.json`.
+- Preserve custom-element attributes/events, Shadow DOM styling, stream
+ ownership, cancellation, and approval behavior while optimizing components.
+- Keep request-specific identity and credentials out of shared caches.
+- Treat upstream examples as guidance. Add dependencies or abstractions only
+ when the concrete change benefits from them.
+
+## Process
+
+1. Identify the affected interaction and its performance or correctness issue.
+2. Read the relevant local rule files and existing widget implementation.
+3. Make a focused change that preserves the widget's public behavior.
+4. Run `npm run typecheck:widget` and `npm run test:widget` for widget changes.
+ Run `npm run test:widget:e2e` when changing browser interactions such as
+ scrolling, focus, streaming, cancellation, or approvals.
+5. Rebuild changed widget sources with `npm run build:widget`, include the
+ generated `src/agent_manager/api/static/widget.js`, and run `make check`.
+
+## Checklist Before Finishing
+
+- [ ] Applied rules match Extra's React/custom-element architecture.
+- [ ] The change fixes an observed problem or has a clear performance rationale.
+- [ ] Effect cleanup, callback state, and active stream behavior remain correct.
+- [ ] Relevant widget checks pass and the bundle is rebuilt when sources change.
+- [ ] `make check` passes.
+
+## Common Mistakes to Avoid
+
+- Applying Next.js-specific examples directly to this browser-only widget.
+- Adding blanket memoization or caching without identifying the expensive work.
+- Optimizing rendering by removing lifecycle, ownership, or approval checks.
+- Editing the built bundle directly or changing generated skill adapters by hand.
+
+## Expected Final Report
+
+Use the `AGENTS.md` report format. State the affected interaction, relevant
+rules, why the change helps, checks run, and any remaining performance limits.
+
+## Upstream Source
+
+Adapted from [Vercel React Best Practices](https://github.com/vercel-labs/agent-skills/tree/063bee94c3f4df8453406c830b0a7df0f2860278/skills/react-best-practices),
+by Vercel Engineering, version 1.0.0, at commit
+`063bee94c3f4df8453406c830b0a7df0f2860278`. Upstream declares the MIT license
+in its `SKILL.md`. The 70 local rule files are copies from that revision; the
+entrypoint above supplies Extra's project context and commands.
+
+Eleven rules carry local correctness and security corrections from review:
+`rendering-usetransition-loading` (stale responses are ignored, since a
+transition does not cancel requests), `js-cache-function-results` (pure,
+bounded caches only), `bundle-conditional` and `bundle-preload` (a
+`typeof window` guard does not affect bundling), `server-cache-lru`
+(unambiguous scope-complete keys, and authorization before any cached value is
+returned),
+`rendering-hydration-no-flicker` (the class change is still a hydration
+mismatch), `async-api-routes` (handled early starts and an authentication
+exit), `advanced-event-handler-refs` and `advanced-use-latest` (Effect Events
+are not stable),
+`js-cache-storage` (cookie caches are reset, and cookie changes raise no
+event), and `server-after-nonblocking` (work in `after()` is awaited, and
+session cookies are not logged). Trailing whitespace was also removed from the
+copied rules. Reapply these changes when updating from upstream.
diff --git a/.claude/skills/vercel-react-best-practices/SKILL.md b/.claude/skills/vercel-react-best-practices/SKILL.md
new file mode 100644
index 00000000..960066a1
--- /dev/null
+++ b/.claude/skills/vercel-react-best-practices/SKILL.md
@@ -0,0 +1,118 @@
+---
+name: vercel-react-best-practices
+description: "Apply Vercel React performance guidance when implementing, reviewing, or optimizing the React chat widget, including data fetching, rendering, effects, and bundle size."
+generated: true
+source: .ai/skills/vercel-react-best-practices.md
+---
+
+
+
+# Skill: Vercel React Best Practices
+
+## Purpose
+
+Apply Vercel's performance guidance to Extra's React chat widget. The 70
+upstream rules and examples are available locally under
+`.ai/references/vercel-react-best-practices/rules/`; read the rules relevant
+to the change rather than loading the entire collection.
+
+All paths in this playbook are relative to the repository root, including
+when reading a generated Codex or Claude adapter.
+
+## When to Use This Skill
+
+- Implementing or reviewing components under
+ `src/agent_manager/api/static/widget/react/`.
+- Changing widget effects, event listeners, state, or data fetching.
+- Investigating slow rendering, unnecessary requests, or bundle growth.
+
+## Files to Read First
+
+- `AGENTS.md` and `.ai/skills/project-architecture.md`.
+- `docs/WIDGET_ARCHITECTURE.md` and `docs/WIDGET.md`.
+- `package.json`, the components being changed, and their existing tests.
+- Relevant rules from the local reference directory, using this routing table:
+
+| Concern | Rule prefix | Starting point |
+| --- | --- | --- |
+| Sequential independent requests | `async-` | `async-parallel.md` |
+| Unnecessary module loading | `bundle-` | `bundle-conditional.md` |
+| Duplicate browser subscriptions | `client-` | `client-event-listeners.md` |
+| Stale state or unnecessary renders | `rerender-` | `rerender-functional-setstate.md`, `rerender-dependencies.md` |
+| Expensive rendering | `rendering-` | `rendering-hoist-jsx.md`, `rendering-content-visibility.md` |
+| Repeated JavaScript work | `js-` | `js-set-map-lookups.md`, `js-combine-iterations.md` |
+| Callback and initialization patterns | `advanced-` | `advanced-event-handler-refs.md` |
+| Server rendering, if introduced separately | `server-` | `server-no-shared-module-state.md` |
+
+## Core Principles
+
+- The shipped widget is React inside a custom element and Shadow DOM, bundled
+ with esbuild. Select rules that fit that environment; Next.js routing, RSC,
+ SSR caching, and `next/dynamic` examples do not justify adding Next.js.
+- Prioritize observable request waterfalls, bundle growth, and rendering costs
+ over speculative micro-optimizations. Match APIs to the installed React
+ version and esbuild browser target in `package.json`.
+- Preserve custom-element attributes/events, Shadow DOM styling, stream
+ ownership, cancellation, and approval behavior while optimizing components.
+- Keep request-specific identity and credentials out of shared caches.
+- Treat upstream examples as guidance. Add dependencies or abstractions only
+ when the concrete change benefits from them.
+
+## Process
+
+1. Identify the affected interaction and its performance or correctness issue.
+2. Read the relevant local rule files and existing widget implementation.
+3. Make a focused change that preserves the widget's public behavior.
+4. Run `npm run typecheck:widget` and `npm run test:widget` for widget changes.
+ Run `npm run test:widget:e2e` when changing browser interactions such as
+ scrolling, focus, streaming, cancellation, or approvals.
+5. Rebuild changed widget sources with `npm run build:widget`, include the
+ generated `src/agent_manager/api/static/widget.js`, and run `make check`.
+
+## Checklist Before Finishing
+
+- [ ] Applied rules match Extra's React/custom-element architecture.
+- [ ] The change fixes an observed problem or has a clear performance rationale.
+- [ ] Effect cleanup, callback state, and active stream behavior remain correct.
+- [ ] Relevant widget checks pass and the bundle is rebuilt when sources change.
+- [ ] `make check` passes.
+
+## Common Mistakes to Avoid
+
+- Applying Next.js-specific examples directly to this browser-only widget.
+- Adding blanket memoization or caching without identifying the expensive work.
+- Optimizing rendering by removing lifecycle, ownership, or approval checks.
+- Editing the built bundle directly or changing generated skill adapters by hand.
+
+## Expected Final Report
+
+Use the `AGENTS.md` report format. State the affected interaction, relevant
+rules, why the change helps, checks run, and any remaining performance limits.
+
+## Upstream Source
+
+Adapted from [Vercel React Best Practices](https://github.com/vercel-labs/agent-skills/tree/063bee94c3f4df8453406c830b0a7df0f2860278/skills/react-best-practices),
+by Vercel Engineering, version 1.0.0, at commit
+`063bee94c3f4df8453406c830b0a7df0f2860278`. Upstream declares the MIT license
+in its `SKILL.md`. The 70 local rule files are copies from that revision; the
+entrypoint above supplies Extra's project context and commands.
+
+Eleven rules carry local correctness and security corrections from review:
+`rendering-usetransition-loading` (stale responses are ignored, since a
+transition does not cancel requests), `js-cache-function-results` (pure,
+bounded caches only), `bundle-conditional` and `bundle-preload` (a
+`typeof window` guard does not affect bundling), `server-cache-lru`
+(unambiguous scope-complete keys, and authorization before any cached value is
+returned),
+`rendering-hydration-no-flicker` (the class change is still a hydration
+mismatch), `async-api-routes` (handled early starts and an authentication
+exit), `advanced-event-handler-refs` and `advanced-use-latest` (Effect Events
+are not stable),
+`js-cache-storage` (cookie caches are reset, and cookie changes raise no
+event), and `server-after-nonblocking` (work in `after()` is awaited, and
+session cookies are not logged). Trailing whitespace was also removed from the
+copied rules. Reapply these changes when updating from upstream.
diff --git a/.codex/skills/vercel-react-best-practices.md b/.codex/skills/vercel-react-best-practices.md
new file mode 100644
index 00000000..960066a1
--- /dev/null
+++ b/.codex/skills/vercel-react-best-practices.md
@@ -0,0 +1,118 @@
+---
+name: vercel-react-best-practices
+description: "Apply Vercel React performance guidance when implementing, reviewing, or optimizing the React chat widget, including data fetching, rendering, effects, and bundle size."
+generated: true
+source: .ai/skills/vercel-react-best-practices.md
+---
+
+
+
+# Skill: Vercel React Best Practices
+
+## Purpose
+
+Apply Vercel's performance guidance to Extra's React chat widget. The 70
+upstream rules and examples are available locally under
+`.ai/references/vercel-react-best-practices/rules/`; read the rules relevant
+to the change rather than loading the entire collection.
+
+All paths in this playbook are relative to the repository root, including
+when reading a generated Codex or Claude adapter.
+
+## When to Use This Skill
+
+- Implementing or reviewing components under
+ `src/agent_manager/api/static/widget/react/`.
+- Changing widget effects, event listeners, state, or data fetching.
+- Investigating slow rendering, unnecessary requests, or bundle growth.
+
+## Files to Read First
+
+- `AGENTS.md` and `.ai/skills/project-architecture.md`.
+- `docs/WIDGET_ARCHITECTURE.md` and `docs/WIDGET.md`.
+- `package.json`, the components being changed, and their existing tests.
+- Relevant rules from the local reference directory, using this routing table:
+
+| Concern | Rule prefix | Starting point |
+| --- | --- | --- |
+| Sequential independent requests | `async-` | `async-parallel.md` |
+| Unnecessary module loading | `bundle-` | `bundle-conditional.md` |
+| Duplicate browser subscriptions | `client-` | `client-event-listeners.md` |
+| Stale state or unnecessary renders | `rerender-` | `rerender-functional-setstate.md`, `rerender-dependencies.md` |
+| Expensive rendering | `rendering-` | `rendering-hoist-jsx.md`, `rendering-content-visibility.md` |
+| Repeated JavaScript work | `js-` | `js-set-map-lookups.md`, `js-combine-iterations.md` |
+| Callback and initialization patterns | `advanced-` | `advanced-event-handler-refs.md` |
+| Server rendering, if introduced separately | `server-` | `server-no-shared-module-state.md` |
+
+## Core Principles
+
+- The shipped widget is React inside a custom element and Shadow DOM, bundled
+ with esbuild. Select rules that fit that environment; Next.js routing, RSC,
+ SSR caching, and `next/dynamic` examples do not justify adding Next.js.
+- Prioritize observable request waterfalls, bundle growth, and rendering costs
+ over speculative micro-optimizations. Match APIs to the installed React
+ version and esbuild browser target in `package.json`.
+- Preserve custom-element attributes/events, Shadow DOM styling, stream
+ ownership, cancellation, and approval behavior while optimizing components.
+- Keep request-specific identity and credentials out of shared caches.
+- Treat upstream examples as guidance. Add dependencies or abstractions only
+ when the concrete change benefits from them.
+
+## Process
+
+1. Identify the affected interaction and its performance or correctness issue.
+2. Read the relevant local rule files and existing widget implementation.
+3. Make a focused change that preserves the widget's public behavior.
+4. Run `npm run typecheck:widget` and `npm run test:widget` for widget changes.
+ Run `npm run test:widget:e2e` when changing browser interactions such as
+ scrolling, focus, streaming, cancellation, or approvals.
+5. Rebuild changed widget sources with `npm run build:widget`, include the
+ generated `src/agent_manager/api/static/widget.js`, and run `make check`.
+
+## Checklist Before Finishing
+
+- [ ] Applied rules match Extra's React/custom-element architecture.
+- [ ] The change fixes an observed problem or has a clear performance rationale.
+- [ ] Effect cleanup, callback state, and active stream behavior remain correct.
+- [ ] Relevant widget checks pass and the bundle is rebuilt when sources change.
+- [ ] `make check` passes.
+
+## Common Mistakes to Avoid
+
+- Applying Next.js-specific examples directly to this browser-only widget.
+- Adding blanket memoization or caching without identifying the expensive work.
+- Optimizing rendering by removing lifecycle, ownership, or approval checks.
+- Editing the built bundle directly or changing generated skill adapters by hand.
+
+## Expected Final Report
+
+Use the `AGENTS.md` report format. State the affected interaction, relevant
+rules, why the change helps, checks run, and any remaining performance limits.
+
+## Upstream Source
+
+Adapted from [Vercel React Best Practices](https://github.com/vercel-labs/agent-skills/tree/063bee94c3f4df8453406c830b0a7df0f2860278/skills/react-best-practices),
+by Vercel Engineering, version 1.0.0, at commit
+`063bee94c3f4df8453406c830b0a7df0f2860278`. Upstream declares the MIT license
+in its `SKILL.md`. The 70 local rule files are copies from that revision; the
+entrypoint above supplies Extra's project context and commands.
+
+Eleven rules carry local correctness and security corrections from review:
+`rendering-usetransition-loading` (stale responses are ignored, since a
+transition does not cancel requests), `js-cache-function-results` (pure,
+bounded caches only), `bundle-conditional` and `bundle-preload` (a
+`typeof window` guard does not affect bundling), `server-cache-lru`
+(unambiguous scope-complete keys, and authorization before any cached value is
+returned),
+`rendering-hydration-no-flicker` (the class change is still a hydration
+mismatch), `async-api-routes` (handled early starts and an authentication
+exit), `advanced-event-handler-refs` and `advanced-use-latest` (Effect Events
+are not stable),
+`js-cache-storage` (cookie caches are reset, and cookie changes raise no
+event), and `server-after-nonblocking` (work in `after()` is awaited, and
+session cookies are not logged). Trailing whitespace was also removed from the
+copied rules. Reapply these changes when updating from upstream.
diff --git a/AGENTS.md b/AGENTS.md
index d1e80ebd..6e88bb85 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -234,6 +234,7 @@ first; then pick by the *kind* of task and the *area* of the system.
| Prompt templates / rendering | `.ai/skills/prompt-rendering.md` |
| Plugin context/access resolution | `.ai/skills/sidecar-auth-context.md` |
| Tools, MCP servers, permissions | `.ai/skills/mcp-tools.md` |
+| React chat widget / frontend performance | `.ai/skills/vercel-react-best-practices.md` |
Each skill ends with an **Expected Final Report** (or validation checklist) —
apply it before declaring work done.