` and animate the wrapper instead.
+
+**Incorrect (animating SVG directly - no hardware acceleration):**
+
+```tsx
+function LoadingSpinner() {
+ return (
+
+
+
+ )
+}
+```
+
+**Correct (animating wrapper div - hardware accelerated):**
+
+```tsx
+function LoadingSpinner() {
+ 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/docs/agent/external/ext-react-best-practices/rules/rendering-conditional-render.md b/docs/agent/external/ext-react-best-practices/rules/rendering-conditional-render.md
new file mode 100644
index 0000000..7e866f5
--- /dev/null
+++ b/docs/agent/external/ext-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:
5
+```
diff --git a/docs/agent/external/ext-react-best-practices/rules/rendering-content-visibility.md b/docs/agent/external/ext-react-best-practices/rules/rendering-content-visibility.md
new file mode 100644
index 0000000..aa66563
--- /dev/null
+++ b/docs/agent/external/ext-react-best-practices/rules/rendering-content-visibility.md
@@ -0,0 +1,38 @@
+---
+title: CSS content-visibility for Long Lists
+impact: HIGH
+impactDescription: faster initial render
+tags: rendering, css, content-visibility, long-lists
+---
+
+## CSS content-visibility for Long Lists
+
+Apply `content-visibility: auto` to defer off-screen rendering.
+
+**CSS:**
+
+```css
+.message-item {
+ content-visibility: auto;
+ contain-intrinsic-size: 0 80px;
+}
+```
+
+**Example:**
+
+```tsx
+function MessageList({ messages }: { messages: Message[] }) {
+ return (
+
+ {messages.map(msg => (
+
+ ))}
+
+ )
+}
+```
+
+For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
diff --git a/docs/agent/external/ext-react-best-practices/rules/rendering-hoist-jsx.md b/docs/agent/external/ext-react-best-practices/rules/rendering-hoist-jsx.md
new file mode 100644
index 0000000..32d2f3f
--- /dev/null
+++ b/docs/agent/external/ext-react-best-practices/rules/rendering-hoist-jsx.md
@@ -0,0 +1,46 @@
+---
+title: Hoist Static JSX Elements
+impact: LOW
+impactDescription: avoids re-creation
+tags: rendering, jsx, static, optimization
+---
+
+## Hoist Static JSX Elements
+
+Extract static JSX outside components to avoid re-creation.
+
+**Incorrect (recreates element every render):**
+
+```tsx
+function LoadingSkeleton() {
+ return
+}
+
+function Container() {
+ return (
+
+ {loading && }
+
+ )
+}
+```
+
+**Correct (reuses same element):**
+
+```tsx
+const loadingSkeleton = (
+
+)
+
+function Container() {
+ return (
+
+ {loading && loadingSkeleton}
+
+ )
+}
+```
+
+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/docs/agent/external/ext-react-best-practices/rules/rendering-hydration-no-flicker.md b/docs/agent/external/ext-react-best-practices/rules/rendering-hydration-no-flicker.md
new file mode 100644
index 0000000..5cf0e79
--- /dev/null
+++ b/docs/agent/external/ext-react-best-practices/rules/rendering-hydration-no-flicker.md
@@ -0,0 +1,82 @@
+---
+title: Prevent Hydration Mismatch Without Flickering
+impact: MEDIUM
+impactDescription: avoids visual flicker and hydration errors
+tags: rendering, ssr, hydration, localStorage, flicker
+---
+
+## Prevent Hydration Mismatch 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 (
+
+ {children}
+
+ )
+}
+```
+
+Server-side rendering will fail because `localStorage` is undefined.
+
+**Incorrect (visual flickering):**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ const [theme, setTheme] = useState('light')
+
+ useEffect(() => {
+ // Runs after hydration - causes visible flash
+ const stored = localStorage.getItem('theme')
+ if (stored) {
+ setTheme(stored)
+ }
+ }, [])
+
+ return (
+
+ {children}
+
+ )
+}
+```
+
+Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
+
+**Correct (no flicker, no hydration mismatch):**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ return (
+ <>
+
+ {children}
+
+
+ >
+ )
+}
+```
+
+The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration 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/docs/agent/external/ext-react-best-practices/rules/rendering-hydration-suppress-warning.md b/docs/agent/external/ext-react-best-practices/rules/rendering-hydration-suppress-warning.md
new file mode 100644
index 0000000..24ba251
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rendering-resource-hints.md b/docs/agent/external/ext-react-best-practices/rules/rendering-resource-hints.md
new file mode 100644
index 0000000..1290bef
--- /dev/null
+++ b/docs/agent/external/ext-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 (
+
+
+ Dashboard
+
+
+ )
+}
+```
+
+**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/docs/agent/external/ext-react-best-practices/rules/rendering-script-defer-async.md b/docs/agent/external/ext-react-best-practices/rules/rendering-script-defer-async.md
new file mode 100644
index 0000000..ee275ed
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rendering-svg-precision.md b/docs/agent/external/ext-react-best-practices/rules/rendering-svg-precision.md
new file mode 100644
index 0000000..6d77128
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rendering-usetransition-loading.md b/docs/agent/external/ext-react-best-practices/rules/rendering-usetransition-loading.md
new file mode 100644
index 0000000..0c1b0b9
--- /dev/null
+++ b/docs/agent/external/ext-react-best-practices/rules/rendering-usetransition-loading.md
@@ -0,0 +1,75 @@
+---
+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 { useTransition, useState } from 'react'
+
+function SearchResults() {
+ const [query, setQuery] = useState('')
+ const [results, setResults] = useState([])
+ const [isPending, startTransition] = useTransition()
+
+ const handleSearch = (value: string) => {
+ setQuery(value) // Update input immediately
+
+ startTransition(async () => {
+ // Fetch and update results
+ const data = await fetchResults(value)
+ 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
+- **Interrupt handling**: New transitions automatically cancel pending ones
+
+Reference: [useTransition](https://react.dev/reference/react/useTransition)
diff --git a/docs/agent/external/ext-react-best-practices/rules/rerender-defer-reads.md b/docs/agent/external/ext-react-best-practices/rules/rerender-defer-reads.md
new file mode 100644
index 0000000..e867c95
--- /dev/null
+++ b/docs/agent/external/ext-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
Share
+}
+```
+
+**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
Share
+}
+```
diff --git a/docs/agent/external/ext-react-best-practices/rules/rerender-dependencies.md b/docs/agent/external/ext-react-best-practices/rules/rerender-dependencies.md
new file mode 100644
index 0000000..47a4d92
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-derived-state-no-effect.md b/docs/agent/external/ext-react-best-practices/rules/rerender-derived-state-no-effect.md
new file mode 100644
index 0000000..3d9fe40
--- /dev/null
+++ b/docs/agent/external/ext-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
{fullName}
+}
+```
+
+**Correct (derive during render):**
+
+```tsx
+function Form() {
+ const [firstName, setFirstName] = useState('First')
+ const [lastName, setLastName] = useState('Last')
+ const fullName = firstName + ' ' + lastName
+
+ return
{fullName}
+}
+```
+
+References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
diff --git a/docs/agent/external/ext-react-best-practices/rules/rerender-derived-state.md b/docs/agent/external/ext-react-best-practices/rules/rerender-derived-state.md
new file mode 100644
index 0000000..e5c899f
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-functional-setstate.md b/docs/agent/external/ext-react-best-practices/rules/rerender-functional-setstate.md
new file mode 100644
index 0000000..b004ef4
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-lazy-state-init.md b/docs/agent/external/ext-react-best-practices/rules/rerender-lazy-state-init.md
new file mode 100644
index 0000000..4ecb350
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-memo-with-default-value.md b/docs/agent/external/ext-react-best-practices/rules/rerender-memo-with-default-value.md
new file mode 100644
index 0000000..6357049
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-memo.md b/docs/agent/external/ext-react-best-practices/rules/rerender-memo.md
new file mode 100644
index 0000000..f8982ab
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-move-effect-to-event.md b/docs/agent/external/ext-react-best-practices/rules/rerender-move-effect-to-event.md
new file mode 100644
index 0000000..dd58a1a
--- /dev/null
+++ b/docs/agent/external/ext-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
setSubmitted(true)}>Submit
+}
+```
+
+**Correct (do it in the handler):**
+
+```tsx
+function Form() {
+ const theme = useContext(ThemeContext)
+
+ function handleSubmit() {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+
+ return
Submit
+}
+```
+
+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/docs/agent/external/ext-react-best-practices/rules/rerender-no-inline-components.md b/docs/agent/external/ext-react-best-practices/rules/rerender-no-inline-components.md
new file mode 100644
index 0000000..d97592a
--- /dev/null
+++ b/docs/agent/external/ext-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 = () => (
+
+ {user.followers} followers
+ {user.posts} posts
+
+ )
+
+ return (
+
+ )
+}
+```
+
+Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
+
+**Correct (pass props instead):**
+
+```tsx
+function Avatar({ src, theme }: { src: string; theme: string }) {
+ return (
+
+ )
+}
+
+function Stats({ followers, posts }: { followers: number; posts: number }) {
+ return (
+
+ {followers} followers
+ {posts} posts
+
+ )
+}
+
+function UserProfile({ user, theme }) {
+ return (
+
+ )
+}
+```
+
+**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/docs/agent/external/ext-react-best-practices/rules/rerender-simple-expression-in-memo.md b/docs/agent/external/ext-react-best-practices/rules/rerender-simple-expression-in-memo.md
new file mode 100644
index 0000000..59dfab0
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-split-combined-hooks.md b/docs/agent/external/ext-react-best-practices/rules/rerender-split-combined-hooks.md
new file mode 100644
index 0000000..89d8056
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-transitions.md b/docs/agent/external/ext-react-best-practices/rules/rerender-transitions.md
new file mode 100644
index 0000000..d99f43f
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-use-deferred-value.md b/docs/agent/external/ext-react-best-practices/rules/rerender-use-deferred-value.md
new file mode 100644
index 0000000..619c04b
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/rerender-use-ref-transient-values.md b/docs/agent/external/ext-react-best-practices/rules/rerender-use-ref-transient-values.md
new file mode 100644
index 0000000..cf04b81
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/server-after-nonblocking.md b/docs/agent/external/ext-react-best-practices/rules/server-after-nonblocking.md
new file mode 100644
index 0000000..e8f5b26
--- /dev/null
+++ b/docs/agent/external/ext-react-best-practices/rules/server-after-nonblocking.md
@@ -0,0 +1,73 @@
+---
+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, cookies } 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'
+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
+
+ logUserAction({ sessionCookie, 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
+
+Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
diff --git a/docs/agent/external/ext-react-best-practices/rules/server-auth-actions.md b/docs/agent/external/ext-react-best-practices/rules/server-auth-actions.md
new file mode 100644
index 0000000..ee82c04
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/server-cache-lru.md b/docs/agent/external/ext-react-best-practices/rules/server-cache-lru.md
new file mode 100644
index 0000000..ef6938a
--- /dev/null
+++ b/docs/agent/external/ext-react-best-practices/rules/server-cache-lru.md
@@ -0,0 +1,41 @@
+---
+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
+})
+
+export async function getUser(id: string) {
+ const cached = cache.get(id)
+ if (cached) return cached
+
+ const user = await db.user.findUnique({ where: { id } })
+ cache.set(id, user)
+ return user
+}
+
+// Request 1: DB query, result cached
+// Request 2: cache hit, no DB query
+```
+
+Use when sequential user actions hit multiple endpoints needing the same data within seconds.
+
+**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/docs/agent/external/ext-react-best-practices/rules/server-cache-react.md b/docs/agent/external/ext-react-best-practices/rules/server-cache-react.md
new file mode 100644
index 0000000..87c9ca3
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/server-dedup-props.md b/docs/agent/external/ext-react-best-practices/rules/server-dedup-props.md
new file mode 100644
index 0000000..fb24a25
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/server-hoist-static-io.md b/docs/agent/external/ext-react-best-practices/rules/server-hoist-static-io.md
new file mode 100644
index 0000000..25205c2
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/server-no-shared-module-state.md b/docs/agent/external/ext-react-best-practices/rules/server-no-shared-module-state.md
new file mode 100644
index 0000000..ff7d9f2
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/server-parallel-fetching.md b/docs/agent/external/ext-react-best-practices/rules/server-parallel-fetching.md
new file mode 100644
index 0000000..1affc83
--- /dev/null
+++ b/docs/agent/external/ext-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 (
+
+ )
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return {items.map(renderItem)}
+}
+```
+
+**Correct (both fetch simultaneously):**
+
+```tsx
+async function Header() {
+ const data = await fetchHeader()
+ return {data}
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return {items.map(renderItem)}
+}
+
+export default function Page() {
+ return (
+
+
+
+
+ )
+}
+```
+
+**Alternative with children prop:**
+
+```tsx
+async function Header() {
+ const data = await fetchHeader()
+ return {data}
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return {items.map(renderItem)}
+}
+
+function Layout({ children }: { children: ReactNode }) {
+ return (
+
+
+ {children}
+
+ )
+}
+
+export default function Page() {
+ return (
+
+
+
+ )
+}
+```
diff --git a/docs/agent/external/ext-react-best-practices/rules/server-parallel-nested-fetching.md b/docs/agent/external/ext-react-best-practices/rules/server-parallel-nested-fetching.md
new file mode 100644
index 0000000..be1dc25
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/ext-react-best-practices/rules/server-serialization.md b/docs/agent/external/ext-react-best-practices/rules/server-serialization.md
new file mode 100644
index 0000000..39c5c41
--- /dev/null
+++ b/docs/agent/external/ext-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/docs/agent/external/manifest.json b/docs/agent/external/manifest.json
new file mode 100644
index 0000000..02bf90b
--- /dev/null
+++ b/docs/agent/external/manifest.json
@@ -0,0 +1,171 @@
+{
+ "note": "Generated by scripts/vendor-external-skills.mjs — do not edit by hand.",
+ "skills": [
+ {
+ "name": "ext-react-best-practices",
+ "publisher": "Vercel",
+ "repo": "https://github.com/vercel-labs/agent-skills",
+ "commit": "1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62",
+ "path": "skills/react-best-practices",
+ "license": "MIT",
+ "files": {
+ "AGENTS.md": "fc93e7421177bbf869cce892bc60a6c83a4517d974bc3bf65c4e2c1e58a6ccf6",
+ "LICENSE": "6da0f12154146d519193545dac885fe808464db64cbf532e038ca40e4865ab1e",
+ "README.md": "9eafb2123d3b8b2aef41fba0db2648a3f4f49996f8c7c8bb2c86263befd8b48a",
+ "SKILL.md": "8ec7dd05b1e92520eaf5660d2c2440b333cfe27ffe773b3c86674fedeba56e98",
+ "SOURCE.md": "8763a44a50774ddfba3d86f97642bbcbb3879f692f1cdcd22714191177eaea14",
+ "metadata.json": "c4e18bac3290fbe1b471a605867d4df68b03144ea26b8befdbe8f9d8fd124354",
+ "rules/_sections.md": "01c59969e4e867f0708c8f8ef9c6d87fab9a07d0586244f429ff84013db8a115",
+ "rules/_template.md": "99df2a3ea088c6c22de2484ddc7e964d0e9923846f44c63380343ecc64455442",
+ "rules/advanced-effect-event-deps.md": "55ed8f9f27a1bff803d6fa55828176207714b02123cbb97ddb8a90d88024a723",
+ "rules/advanced-event-handler-refs.md": "a3097edeecfb2ff6851cd66ed8cdf0617c3c88180504bee824aa6e75a215bbbc",
+ "rules/advanced-init-once.md": "3e4dc22173eb0e2b6dcf583e3babd862b8696328f8f59aee7c4d746c5bc05f6c",
+ "rules/advanced-use-latest.md": "8a3f64dfe5a77d1564248faf17fe662ae75b55d497a243cb30b38eb07ccbbf9a",
+ "rules/async-api-routes.md": "523338540d73427dc14c0cbb19f2741ebccdf8b105a7b2c1b33d2905cf237a42",
+ "rules/async-cheap-condition-before-await.md": "03107c1f70a293cd58a8abc5474c5548e20ea4efdf01b6d45aae7ad0ac1cb32c",
+ "rules/async-defer-await.md": "f3c142d090615abdcc99d31c123be37b31f0f1ed8d9ec9f7789a3bc6883ae0fb",
+ "rules/async-dependencies.md": "16ef469f877e30c6b8e1e1b4bc3e527312fa3c6318cb785a4eca186ea236131a",
+ "rules/async-parallel.md": "6d2f841896279e976dfcdc1ac89e70771ac188baadfd43c096b5706cb838b961",
+ "rules/async-suspense-boundaries.md": "de05fedac2eb7ae563b887b5a424464ec3dfaf84e5b7797467ebe2a796ac8afc",
+ "rules/bundle-analyzable-paths.md": "62090b5c815fd71bf1133dce754f51abc16a9456d0ccd025fd627de27726e92a",
+ "rules/bundle-barrel-imports.md": "e648f6d54525f07a691357040ca5bff6ea3424788a91ff63812adb29622a671b",
+ "rules/bundle-conditional.md": "09c8259c3efb04fc0abb8e412ccbda217c222ae8118516283e571c995fe3a7d4",
+ "rules/bundle-defer-third-party.md": "3719fb47b191e8db4fe22686ec88448ad5af9e6838585425abbe103d0b642e37",
+ "rules/bundle-dynamic-imports.md": "401817a7369f315fc5a68a1095742ff7d53d0461906880dc9d64a41495ee1986",
+ "rules/bundle-preload.md": "d1f7cc28da7cd5ab249acd287edc5b761afcfb194e9cb62cd44c5f3543db2de2",
+ "rules/client-event-listeners.md": "242a873349febc1ce685e85617994784dbab92c2eaa68aed7fed5a83e7680e93",
+ "rules/client-localstorage-schema.md": "0fb7cdf9dc93fdf22f87e3669f953fb9d4ac9b0be42eec4a29fe9a2560610b88",
+ "rules/client-passive-event-listeners.md": "1f35016f9053de69e884ee9be00654e37979c2ca85f5e57764dc2626ff7acb4b",
+ "rules/client-swr-dedup.md": "644652c39c6cc00de8d1c77a7273612e868dc3f7edda30764164c12ec0f764a3",
+ "rules/js-batch-dom-css.md": "480b891b9eaf96e929dc1e964274a4828e3a78009b7d00ccd965a0d425215959",
+ "rules/js-cache-function-results.md": "3daaa11d24f4295cb6be8bc6f407f2ce83cc7b5bd1f0e68891ea8ab835721dc7",
+ "rules/js-cache-property-access.md": "73e47431e74878a927061bf0ddc7cd91a7556cb35d2573f3421e82300d9ae311",
+ "rules/js-cache-storage.md": "11b826b0433898c1ece2d3547010d8e77db9fb240185748c45db91493de9b6cc",
+ "rules/js-combine-iterations.md": "71add08aeeb43091d4ff4c0b2842cce8b4bdef8ad3e732cc034bb5a84827e746",
+ "rules/js-early-exit.md": "925ce5ce87f3347186ca62212f29cc6baa2b8c85a96d2720ad07c3d0abf781c0",
+ "rules/js-flatmap-filter.md": "9e5b166a41914d975bef7635467f8fb32cd98b5c3126c0bc6f163490812fb5f0",
+ "rules/js-hoist-regexp.md": "f9e9aef2f7c2307dd7310f283df85dcada45fc43e9bb941b0c3aa414dec21ec4",
+ "rules/js-index-maps.md": "5df1bdc2cfabb2c98abd55d26762e5c18189535c2e686184f426082e62920391",
+ "rules/js-length-check-first.md": "8b54a311c826b299272f29187fc58bc55772a04c4a72eeb29456ee96dc9fc624",
+ "rules/js-min-max-loop.md": "87dfb67e2f39df6ad8bcfb5b78c5fb364d3c07554ad188a202408d99f3763421",
+ "rules/js-request-idle-callback.md": "ee08f83905b4011abbc33d594033157d77561b5bbd9b36b04f0f409581ffec32",
+ "rules/js-set-map-lookups.md": "a7fd781a6ba9ad49065961b6f9a90ef486bf6b648390e1a08704025f98e1642b",
+ "rules/js-tosorted-immutable.md": "d0a5e1b0fec48a0a81397957e2f068e224329f7c42cb5feeed8aae6fa64025e8",
+ "rules/rendering-activity.md": "1e5e7eaf3555e61d6a2e900089c676527d26259501db5594f59544b6c664f85a",
+ "rules/rendering-animate-svg-wrapper.md": "9c6ae0ca7a51434e803887c64cded760956579a1452ccb80a461a03f9c937c77",
+ "rules/rendering-conditional-render.md": "2ec2fa23c4148285144687050c52369adba3da2fbe3d486f8d3e0aad8f06f2bc",
+ "rules/rendering-content-visibility.md": "64eee6d5b916fe74df33363994b27fc7f71bea3bcedc7ee04bda23107ca3e6e4",
+ "rules/rendering-hoist-jsx.md": "93b229560fae92005ed9a2a829064607b39b2e984e92d221d05b2d41df2b7c0e",
+ "rules/rendering-hydration-no-flicker.md": "dc7ab358c67c177bca6e6f360fbc935ebe4efa928c0ba3ebd3f9f3d9e2000ca3",
+ "rules/rendering-hydration-suppress-warning.md": "915bacb934e2927d84b37a3f3d225a47b309ac8f9e494ed2bcb66ce07c5676a2",
+ "rules/rendering-resource-hints.md": "351b1095d641717b930f1b2253282b7120af3023bc74e06c17675168d4286864",
+ "rules/rendering-script-defer-async.md": "4cea07b7875ba7fc2c7465ff23b63a2bb334f90aaf2d9293d38d67b05fdb32ab",
+ "rules/rendering-svg-precision.md": "ed468533f6e95f622859c884b122cf21f9f593ed6bb3d500a54de4b9f9bcb9fb",
+ "rules/rendering-usetransition-loading.md": "3a1249c3f13026b6f54ab5712c388df219d6af01b12aa542749acd99a46f4bc1",
+ "rules/rerender-defer-reads.md": "234050a77faf50cb306be10a9e15bd4421134ab5907e75f13e6d78e2bd262dc9",
+ "rules/rerender-dependencies.md": "17eb5830956fb56486fd3cfc7431f5849d39751730c05ad9e77dd4f0c27169c5",
+ "rules/rerender-derived-state-no-effect.md": "cb11ec76f50aa7b6847269f02d79b120c889a30d9ecd2c1d578f75144419c77a",
+ "rules/rerender-derived-state.md": "1c326bb67b01fb084eb00c8911b0a7cff54681c2315b629f88e49b64eaa6481d",
+ "rules/rerender-functional-setstate.md": "5e68df6b2ae8058e67f476ff1ac67bde159f5a9d18df439e46eabcdeb7b52e58",
+ "rules/rerender-lazy-state-init.md": "4ae844740f266fc8cbf050701230286624a2440ec5be67b9a63d9edc3c580573",
+ "rules/rerender-memo-with-default-value.md": "81c47476564ad8a79fc68fc442734255ca7d6829424359464503fda0a9f9a0dd",
+ "rules/rerender-memo.md": "1f258990c2f27ff6256b3cc5c43300631bb3f0d81f749aed08d07fcdcc131dd1",
+ "rules/rerender-move-effect-to-event.md": "abc2cbf167bee056743023351e96806a411d3398da8802093620aecf0721f029",
+ "rules/rerender-no-inline-components.md": "1cc32907a770272524ba682eef9e7efdd8ad4533b6f89b718a1fcd7d1d0eb6a3",
+ "rules/rerender-simple-expression-in-memo.md": "5bdcf2d1558ba5204e643c887b7b4060f89630969425651eb68e96427d97f800",
+ "rules/rerender-split-combined-hooks.md": "6f45d703343484ef9acef9388397f3642966ae6a5a258899a0cf1f9977cfbf6c",
+ "rules/rerender-transitions.md": "60f4033909a62df5e5b8c601494f9e50a562e2f8c1c2d81eac24f38142265f1c",
+ "rules/rerender-use-deferred-value.md": "8c3579576a61a949884167745dcfaf1d5426ba305cc61fd0a79602d70fda4909",
+ "rules/rerender-use-ref-transient-values.md": "f1a649af9d1d0b5c762f6c9c4c1c70c90d7df82aa10296ee87aadb78c1b76c54",
+ "rules/server-after-nonblocking.md": "d0b8d24a3db9f0f65f9e2bddbf230b0e03a5f60e1229d93a4a18f5e7a991c7c2",
+ "rules/server-auth-actions.md": "a2ca8aa102839251c7971ec784560fab943c20b36fe6f80365d4110c13260c23",
+ "rules/server-cache-lru.md": "1924b64561841923b88a657085097a0aeba3e0ba2d5470b9f5c15cc10d6ae70f",
+ "rules/server-cache-react.md": "fddeea6c870bb3da4134b61d54b7d09b83d2603f929b7547cd3dc1dc269edd5c",
+ "rules/server-dedup-props.md": "c2747424cdac46be62f835f245a0aa887b0090b416d28e2ac8676702645eeb37",
+ "rules/server-hoist-static-io.md": "5abea4dd882b13661bd5f7dfb93f9e547d5f08176c61c448ade91b210ed5d49f",
+ "rules/server-no-shared-module-state.md": "4d869bf1cd2f1632e5ca4c0e64b1cf0e71c5f5a0f940bc8a22174d205e735ed7",
+ "rules/server-parallel-fetching.md": "569a2e9fc04f9606686cd75c5894ef8781b502786a7fffe241396846c7733472",
+ "rules/server-parallel-nested-fetching.md": "ad5d9656984d4a959997a2367bf59cc6632297b4634a1dd13a087939d83f30b3",
+ "rules/server-serialization.md": "f4c7d68b29c82381baad059c4a7f09e868e71ec9c3115a26ad3ae7d24c0dfe1f"
+ }
+ },
+ {
+ "name": "ext-composition-patterns",
+ "publisher": "Vercel",
+ "repo": "https://github.com/vercel-labs/agent-skills",
+ "commit": "1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62",
+ "path": "skills/composition-patterns",
+ "license": "MIT",
+ "files": {
+ "AGENTS.md": "89e3ddd58fcf99a53a50e25dfd21b8cde1be5f10b7df6bacd3dfa6796932f516",
+ "LICENSE": "6da0f12154146d519193545dac885fe808464db64cbf532e038ca40e4865ab1e",
+ "README.md": "85915a43a6f0b4efe525e3cf6398dd866166da2025837c4460468a24a940da94",
+ "SKILL.md": "1c7cb0f678e493de4ae477a5b05955bbb5fff05afc2e880d1302302d916bebf7",
+ "SOURCE.md": "9552bfe27ec92ae3856ac18825337d96f9deb5caea7f72ca1600042018c97295",
+ "metadata.json": "49262ed5cb4186f31ee980cf8d990be0170c51efed4908d0464a1cff9905bd05",
+ "rules/_sections.md": "a174213b87e6911e2b766995a2cbaf8d1534057076e82fb79fe3f0ecb38047df",
+ "rules/_template.md": "587f7d16b0660eb61fee4a4d3d7df2b3077d6835de170602c7d6e60bee559131",
+ "rules/architecture-avoid-boolean-props.md": "007555ebb020f4d552582a2c4db194db71a1fd33094012e5187bcfa4f8c392d5",
+ "rules/architecture-compound-components.md": "f246af13dc269b521cf20eb8ad99a0cb645beac381c8c9b117262c34612c8457",
+ "rules/patterns-children-over-render-props.md": "7c45a0d21b3c4126a32cba916ee31adeae195386ad1dbbe6634aedb7457aa0ad",
+ "rules/patterns-explicit-variants.md": "8c19e596e61807549d01ce8c6954c6358199f97a8511c0c02c625ec0efda8c0e",
+ "rules/react19-no-forwardref.md": "881830adb7534c4b2d70db426556646ad9837f5478f744f35641f635ada22227",
+ "rules/state-context-interface.md": "09e73afbf9285fa416679cc864a287b9e8b821d0969272ab784295386d8c9bc3",
+ "rules/state-decouple-implementation.md": "76a8c1eb29a70d8996ab3f71260345af2f7bc89deab815a421d6c87c6591a9c3",
+ "rules/state-lift-state.md": "74c54038a6c554c748fe31cec673b80861b5d920b7553cf78cdf10d18b4b759b"
+ }
+ },
+ {
+ "name": "ext-accessibility",
+ "publisher": "Addy Osmani",
+ "repo": "https://github.com/addyosmani/web-quality-skills",
+ "commit": "afa8da942115f2961fdbfa80807ea0b232ff6c00",
+ "path": "skills/accessibility",
+ "license": "MIT",
+ "files": {
+ "LICENSE": "c122223ac43e86421958e18623979942c21b642951e2e3736dcb63eff13587c3",
+ "SKILL.md": "8f30bd9193b7564b759361f248bf21742e2651d37b0cee5b6cb053082559df47",
+ "SOURCE.md": "9c3de995a6f1185aaba54f6b559fc9abebc5feb4bcf09691c4b94f09732ab6b4",
+ "references/A11Y-PATTERNS.md": "f10e238dd4dd3c4f51134c2056bc02d3dd4f8fb6ccc9145c2c1ba7aab4d58140",
+ "references/WCAG.md": "16683e025e3833d931c9d880645d98a448827f97e10189b6c8f12c832e7a2361"
+ }
+ },
+ {
+ "name": "ext-frontend-design",
+ "publisher": "Anthropic",
+ "repo": "https://github.com/anthropics/skills",
+ "commit": "ca45fc496a3436251f191354091d557da31c15b5",
+ "path": "skills/frontend-design",
+ "license": "Apache-2.0",
+ "files": {
+ "LICENSE.txt": "0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594",
+ "SKILL.md": "f500c33d79ace84c4a00beb413db2111a125817af70523f4ff24a9bcac8b2e15",
+ "SOURCE.md": "c33a36e5bfb784d82e8e458f934755632cfb34ad2282e594776f3d34a728b65d"
+ }
+ },
+ {
+ "name": "ext-payload",
+ "publisher": "Payload CMS",
+ "repo": "https://github.com/payloadcms/payload",
+ "commit": "9c396345dad3c831a34fd212299532e03dc4818f",
+ "path": "tools/claude-plugin/skills/payload",
+ "license": "MIT",
+ "files": {
+ "LICENSE.md": "f5622f480e4419ef6be7691d4b04521a5f18365ddedb9a160e92a4b365e94ecd",
+ "SKILL.md": "23cb08fc54a17fbe09105c786916d0063dbccb6df97d3e7f87ab510eba4597cd",
+ "SOURCE.md": "ed4d139767edd9dc65f7626be70ad48e88a2f3e7aa829d0afe36664b7ebfeb63",
+ "reference/ACCESS-CONTROL-ADVANCED.md": "6872b8e35424a2ab0358d3b8c206f278394249150a24ba0cdcd5f346bea55a79",
+ "reference/ACCESS-CONTROL.md": "3fe23ce036cf5c05c2d20871149a8b42ca31f8d7e2c48fc1a4f9347814784467",
+ "reference/ADAPTERS.md": "2d468490d29756dc3dfdddcfdd07914f7d76b3208338fa903db034a32bc594b2",
+ "reference/ADVANCED.md": "08006ac9024760a3c6644be03a462b7a07af24c09a85a85dc9bc14066637399c",
+ "reference/COLLECTIONS.md": "ecfa655259b196722907229a544af9c426ae3c1440bf2bfc686b29cee6db9547",
+ "reference/ENDPOINTS.md": "126c5bc1d99e794720c21b38b748b85d118a9b6c13fbf7913df7f90ae310f874",
+ "reference/FIELD-TYPE-GUARDS.md": "cb8a4eecb78a0cb5eb151345ff8079f33b05a5bb9ce4f182c598416e3bab3951",
+ "reference/FIELDS.md": "9e453a9a3f9b26c3c0bd016658dbd3cb9e758f124c211898002e9cebb504ce42",
+ "reference/HOOKS.md": "e05d83b013ef2d1f61ada2579fc627167dd6bbb21b612deafb738ec7cba08e98",
+ "reference/PLUGIN-DEVELOPMENT.md": "897c9134af099b09b450720b6404093f3e97a03f3196774e5aec18375386116d",
+ "reference/QUERIES.md": "dd9ca3100fa8e12c06e3e496a173f4fa33fd6c6839081c022461e1cbf668e5a2"
+ }
+ }
+ ]
+}
diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md
index f383626..55325f0 100644
--- a/docs/agent/skills/ipal-setup/SKILL.md
+++ b/docs/agent/skills/ipal-setup/SKILL.md
@@ -108,6 +108,12 @@ with `twoFactor: false` / without `buildR2Storage` (both mandatory in §0b). Nev
yourself); `--dest .claude/skills` — another directory (then exclude `.claude` and replace the `.agents/skills` paths in
commands); `--dry-run` — preview. Name your own skills without the `ipal-` prefix — they are left untouched.
+**Optional — external skills** (after the architecture answers; only if the owner wants them, record it in
+"Project decisions"): `pnpm exec ipal-skills --external` (all) or `--external ext-react-best-practices,ext-accessibility`
+— Vercel React best practices and composition patterns, Addy Osmani accessibility, Anthropic frontend design,
+the official Payload 3 skill (reference). Pinned, text only, nothing downloaded; our rules win over them (AGENT.md §14).
+**Check:** `ls .agents/skills | grep '^ext-'`; each folder has `SOURCE.md` with the pinned commit.
+
## 3. Configuration
**Code.**
diff --git a/scripts/vendor-external-skills.mjs b/scripts/vendor-external-skills.mjs
new file mode 100644
index 0000000..85a11d3
--- /dev/null
+++ b/scripts/vendor-external-skills.mjs
@@ -0,0 +1,193 @@
+#!/usr/bin/env node
+// Maintainer script (not shipped): vendors the third-party agent skills into docs/agent/external/
+// at the commits pinned below. Projects never fetch anything — `ipal-skills --external` copies
+// these vendored folders. To update a pin: change `commit`, run this script, review the diff
+// (`git diff docs/agent/external`), run `pnpm vitest run test/externalSkills.test.ts`, commit.
+//
+// node scripts/vendor-external-skills.mjs → fetch, copy, write manifest.json
+// node scripts/vendor-external-skills.mjs --check → only verify manifest checksums
+//
+// Only text files are copied (.md, .json, .txt); anything else fails the run.
+
+import { createHash } from 'node:crypto'
+import { execFileSync } from 'node:child_process'
+import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join, relative, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
+const outDir = join(root, 'docs', 'agent', 'external')
+
+const COMMON = `> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
+> \`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md\`, the project's \`AGENTS.md\` or \`DESIGN.md\`, those win:
+> ipal-kit features first (the \`ipal-reference\` skill), Payload 3 + Next 16 App Router, data from Server Components
+> through Payload / \`@/lib/content\`, every visible text from the CMS, design values from \`DESIGN.md\` tokens.
+> Never add a dependency this skill suggests without the owner's decision.`
+
+/** Pinned sources. `commit` must be a full 40-character SHA — never a branch. */
+const SOURCES = [
+ {
+ name: 'ext-react-best-practices',
+ repo: 'https://github.com/vercel-labs/agent-skills',
+ commit: '1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62',
+ path: 'skills/react-best-practices',
+ publisher: 'Vercel',
+ license: 'MIT',
+ licenseFile: null, // the repo ships no LICENSE file; MIT is declared in SKILL.md and README
+ override: `> **Data fetching:** ignore \`client-swr-dedup\` and any advice to add \`swr\`, \`better-all\`, \`lru-cache\` or another
+> client-fetch library. Fetch in Server Components with the Payload Local API / \`@/lib/content\` helpers (React \`cache()\`).`,
+ },
+ {
+ name: 'ext-composition-patterns',
+ repo: 'https://github.com/vercel-labs/agent-skills',
+ commit: '1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62',
+ path: 'skills/composition-patterns',
+ publisher: 'Vercel',
+ license: 'MIT',
+ licenseFile: null,
+ override: `> **Blocks:** composition applies inside a block's own components; the block schema, shared fields and
+> \`RenderBlocks\` follow AGENT.md §6.`,
+ },
+ {
+ name: 'ext-accessibility',
+ repo: 'https://github.com/addyosmani/web-quality-skills',
+ commit: 'afa8da942115f2961fdbfa80807ea0b232ff6c00',
+ path: 'skills/accessibility',
+ publisher: 'Addy Osmani',
+ license: 'MIT',
+ licenseFile: 'LICENSE',
+ override: `> **Tools:** never run \`npx lighthouse\` / \`npx @axe-core/cli\` unpinned — add them as devDependencies at fixed versions
+> first. Use the ipal-kit components (CookieBanner, AccessibilityWidget, RenderForm…) and fix their markup through
+> their props or a plugin gap report, not by copying them.`,
+ },
+ {
+ name: 'ext-frontend-design',
+ repo: 'https://github.com/anthropics/skills',
+ commit: 'ca45fc496a3436251f191354091d557da31c15b5',
+ path: 'skills/frontend-design',
+ publisher: 'Anthropic',
+ license: 'Apache-2.0',
+ licenseFile: 'skills/frontend-design/LICENSE.txt',
+ override: `> **Design tokens:** the project's \`DESIGN.md\` tokens win. Use this skill to write or extend \`DESIGN.md\` (with the
+> owner's approval); components never contain hex colours, font names or text — only Tailwind tokens and CMS text.`,
+ },
+ {
+ name: 'ext-payload',
+ repo: 'https://github.com/payloadcms/payload',
+ commit: '9c396345dad3c831a34fd212299532e03dc4818f', // tag v3.92.1
+ path: 'tools/claude-plugin/skills/payload',
+ publisher: 'Payload CMS',
+ license: 'MIT',
+ licenseFile: 'LICENSE.md',
+ override: `> **Reference only — Payload 3 (v3.92.1).** Never apply Payload 4 guidance. ipal-kit already provides users and roles,
+> 2FA, SEO, forms, i18n, the site globals, revalidation and storage — check the \`ipal-reference\` skill before you
+> write Payload config, hooks or access rules by hand.`,
+ },
+]
+
+const MIT = `MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of
+the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+`
+
+const TEXT = /\.(?:json|md|txt)$/
+const sha256 = (file) => createHash('sha256').update(readFileSync(file)).digest('hex')
+const filesOf = (dir) =>
+ readdirSync(dir).flatMap((n) => (statSync(join(dir, n)).isDirectory() ? filesOf(join(dir, n)) : [join(dir, n)]))
+
+function checksums(dir) {
+ return Object.fromEntries(filesOf(dir).map((f) => [relative(dir, f).split('\\').join('/'), sha256(f)]).sort())
+}
+
+if (process.argv.includes('--check')) {
+ const manifest = JSON.parse(readFileSync(join(outDir, 'manifest.json'), 'utf8'))
+ let bad = 0
+ for (const skill of manifest.skills) {
+ const actual = checksums(join(outDir, skill.name))
+ if (JSON.stringify(actual) !== JSON.stringify(skill.files)) {
+ console.error(`✗ ${skill.name}: files differ from manifest.json`)
+ bad++
+ }
+ }
+ console.log(bad ? `${bad} skill(s) changed` : 'all vendored skills match manifest.json')
+ process.exit(bad ? 1 : 0)
+}
+
+const work = mkdtempSync(join(tmpdir(), 'ipal-ext-'))
+const git = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'inherit'] }).toString().trim()
+const checkouts = new Map()
+
+function checkout(repo, commit) {
+ const key = `${repo}@${commit}`
+ if (checkouts.has(key)) {return checkouts.get(key)}
+ if (!/^[0-9a-f]{40}$/.test(commit)) {throw new Error(`${repo}: commit must be a full SHA, got "${commit}"`)}
+ const dir = join(work, String(checkouts.size))
+ execFileSync('git', ['init', '-q', dir])
+ git(dir, 'fetch', '-q', '--depth', '1', '--filter=blob:none', repo, commit)
+ git(dir, '-c', 'advice.detachedHead=false', 'checkout', '-q', 'FETCH_HEAD')
+ if (git(dir, 'rev-parse', 'HEAD') !== commit) {throw new Error(`${repo}: fetched commit differs from ${commit}`)}
+ checkouts.set(key, dir)
+ return dir
+}
+
+const manifest = { note: 'Generated by scripts/vendor-external-skills.mjs — do not edit by hand.', skills: [] }
+try {
+ for (const src of SOURCES) {
+ const repoDir = checkout(src.repo, src.commit)
+ const from = join(repoDir, src.path)
+ const to = join(outDir, src.name)
+ const nonText = filesOf(from).filter((f) => !TEXT.test(f) || (statSync(f).mode & 0o111) !== 0)
+ if (nonText.length) {throw new Error(`${src.name}: not text-only: ${nonText.map((f) => relative(from, f)).join(', ')}`)}
+ rmSync(to, { force: true, recursive: true })
+ cpSync(from, to, { recursive: true })
+
+ // Our name and our overrides go in front of the upstream text.
+ const skillFile = join(to, 'SKILL.md')
+ const skill = readFileSync(skillFile, 'utf8')
+ const end = skill.indexOf('\n---', 3)
+ const frontmatter = skill.slice(0, end).replace(/^name: .+$/m, `name: ${src.name}`)
+ writeFileSync(skillFile, `${frontmatter}${skill.slice(end, end + 4)}\n\n${COMMON}\n>\n${src.override}\n${skill.slice(end + 4)}`)
+
+ if (src.licenseFile && !existsSync(join(to, src.licenseFile.split('/').pop()))) {
+ cpSync(join(repoDir, src.licenseFile), join(to, src.licenseFile.split('/').pop()))
+ }
+ if (!src.licenseFile) {
+ writeFileSync(join(to, 'LICENSE'), `${MIT}\nThe upstream repository (${src.repo}) declares the MIT licence in its README and in\nthe SKILL.md frontmatter; it ships no LICENSE file with a copyright line. Copyright: ${src.publisher}.\n`)
+ }
+ writeFileSync(join(to, 'SOURCE.md'), `# ${src.name}
+
+Vendored by @intecion/ipal-kit (\`ipal-skills --external\`). Do not edit — regenerate with
+\`scripts/vendor-external-skills.mjs\` in the ipal-kit repository.
+
+| | |
+|---|---|
+| Publisher | ${src.publisher} |
+| Source | ${src.repo}/tree/${src.commit}/${src.path} |
+| Commit | \`${src.commit}\` |
+| Licence | ${src.license} (see the LICENSE file in this folder) |
+
+Changes from the upstream text: the \`name\` in the SKILL.md frontmatter is \`${src.name}\`, and an
+override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
+`)
+ manifest.skills.push({
+ name: src.name, publisher: src.publisher, repo: src.repo, commit: src.commit, path: src.path, license: src.license,
+ files: checksums(to),
+ })
+ console.log(`vendored ${src.name} @ ${src.commit.slice(0, 12)}`)
+ }
+ writeFileSync(join(outDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`)
+} finally {
+ rmSync(work, { force: true, recursive: true })
+}
diff --git a/test/docsConsistency.test.ts b/test/docsConsistency.test.ts
index e53e2af..9028f09 100644
--- a/test/docsConsistency.test.ts
+++ b/test/docsConsistency.test.ts
@@ -48,9 +48,13 @@ function contentHelperNames(): Set {
return new Set([...block.slice(0, block.indexOf('}')).matchAll(/^\s+(\w+),?$/gm)].map((m) => m[1]))
}
+// Third-party skills vendored as-is (docs/agent/external) — test/externalSkills.test.ts checks them.
+const VENDORED = path.join('docs', 'agent', 'external')
+
function docFiles(dir = 'docs'): string[] {
return readdirSync(path.join(root, dir)).flatMap((name) => {
const rel = path.join(dir, name)
+ if (rel === VENDORED) {return []}
return statSync(path.join(root, rel)).isDirectory() ? docFiles(rel) : /\.(?:md|ts|tsx|mjs)$/.test(name) ? [rel] : []
})
}
diff --git a/test/externalSkills.test.ts b/test/externalSkills.test.ts
new file mode 100644
index 0000000..e787c63
--- /dev/null
+++ b/test/externalSkills.test.ts
@@ -0,0 +1,122 @@
+/**
+ * Third-party agent skills vendored into the package (docs/agent/external) and installed by
+ * `ipal-skills --external`. They are pinned, text-only and carry their licence; the installer
+ * downloads nothing and leaves the project's own skill folders alone.
+ */
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { afterAll, describe, expect, test } from 'vitest'
+
+type VendoredSkill = {
+ commit: string
+ files: Record
+ license: string
+ name: string
+ path: string
+ publisher: string
+ repo: string
+}
+
+const root = path.resolve(import.meta.dirname, '..')
+const extDir = path.join(root, 'docs/agent/external')
+const manifest = JSON.parse(readFileSync(path.join(extDir, 'manifest.json'), 'utf8')) as { skills: VendoredSkill[] }
+const read = (file: string) => readFileSync(file, 'utf8')
+
+function filesOf(dir: string, base = dir): string[] {
+ return readdirSync(dir).flatMap((name) => {
+ const full = path.join(dir, name)
+ return statSync(full).isDirectory() ? filesOf(full, base) : [path.relative(base, full).split(path.sep).join('/')]
+ })
+}
+
+describe('vendored external skills', () => {
+ test('every skill is pinned to a full commit SHA, never a branch', () => {
+ expect(manifest.skills.length).toBeGreaterThan(0)
+ for (const skill of manifest.skills) {
+ expect(skill.commit, skill.name).toMatch(/^[0-9a-f]{40}$/)
+ expect(skill.repo, skill.name).toMatch(/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+$/)
+ }
+ // The vendoring script holds the same pins, and fetches by commit only.
+ const script = read(path.join(root, 'scripts/vendor-external-skills.mjs'))
+ const pins = [...script.matchAll(/commit: '([^']+)'/g)].map((m) => m[1])
+ expect(pins.sort()).toEqual(manifest.skills.map((s) => s.commit).sort())
+ expect(script).not.toMatch(/--branch|refs\/heads|\/main\b|\/master\b/)
+ })
+
+ test('the installer downloads nothing', () => {
+ const bin = read(path.join(root, 'bin/ipal-skills.mjs'))
+ expect(bin).not.toMatch(/https?:\/\/|\bfetch\(|child_process|execFile|spawn/)
+ })
+
+ test('the files match manifest.json, are text only, and carry a licence and the source', () => {
+ for (const skill of manifest.skills) {
+ const dir = path.join(extDir, skill.name)
+ const files = filesOf(dir).sort()
+ expect(files, skill.name).toEqual(Object.keys(skill.files).sort())
+ for (const file of files) {
+ const full = path.join(dir, file)
+ expect(createHash('sha256').update(readFileSync(full)).digest('hex'), `${skill.name}/${file}`).toBe(skill.files[file])
+ expect(file, `${skill.name}: text only`).toMatch(/\.(?:json|md|txt)$|^LICENSE$/)
+ expect(statSync(full).mode & 0o111, `${skill.name}/${file} is executable`).toBe(0)
+ }
+ expect(files.some((f) => /^LICENSE(?:\.md|\.txt)?$/.test(f)), `${skill.name}: licence`).toBe(true)
+ expect(read(path.join(dir, 'SOURCE.md'))).toContain(skill.commit)
+ }
+ })
+
+ test('each SKILL.md is renamed to its folder and starts with the project-rules override', () => {
+ for (const skill of manifest.skills) {
+ expect(skill.name).toMatch(/^ext-/)
+ const text = read(path.join(extDir, skill.name, 'SKILL.md'))
+ expect(text).toMatch(new RegExp(`^---\\nname: ${skill.name}\\n`))
+ const body = text.slice(text.indexOf('\n---', 3) + 4).trimStart()
+ expect(body.startsWith('> **Project rules win.**'), skill.name).toBe(true)
+ // No instruction to pull rules from a live URL at run time.
+ expect(text).not.toMatch(/raw\.githubusercontent\.com/)
+ }
+ })
+})
+
+describe('ipal-skills --external', () => {
+ const work = mkdtempSync(path.join(tmpdir(), 'ipal-ext-test-'))
+ afterAll(() => rmSync(work, { force: true, recursive: true }))
+ const skillsDir = path.join(work, '.agents/skills')
+ const run = (...args: string[]) =>
+ execFileSync('node', [path.join(root, 'bin/ipal-skills.mjs'), '--no-pointer', ...args], { cwd: work, encoding: 'utf8' })
+ const names = () => readdirSync(skillsDir).sort()
+
+ test('adds ext-* only on request and leaves the project\'s own folders alone', () => {
+ mkdirSync(path.join(skillsDir, 'my-skill'), { recursive: true })
+ writeFileSync(path.join(skillsDir, 'my-skill/SKILL.md'), 'own')
+ mkdirSync(path.join(skillsDir, 'ext-mine'))
+ writeFileSync(path.join(skillsDir, 'ext-mine/SKILL.md'), 'own ext')
+
+ run()
+ expect(names().filter((n) => n.startsWith('ext-') && n !== 'ext-mine')).toEqual([])
+
+ run('--external')
+ for (const skill of manifest.skills) {expect(existsSync(path.join(skillsDir, skill.name, 'SKILL.md')), skill.name).toBe(true)}
+ expect(read(path.join(skillsDir, 'my-skill/SKILL.md'))).toBe('own')
+ expect(read(path.join(skillsDir, 'ext-mine/SKILL.md'))).toBe('own ext')
+ })
+
+ test('removes only retired ext-* folders that ipal-kit installed', () => {
+ const retired = path.join(skillsDir, 'ext-retired')
+ mkdirSync(retired)
+ cpSync(path.join(extDir, manifest.skills[0].name, 'SOURCE.md'), path.join(retired, 'SOURCE.md'))
+ run('--external', manifest.skills[0].name)
+ expect(existsSync(retired)).toBe(false)
+ expect(existsSync(path.join(skillsDir, 'ext-mine'))).toBe(true)
+ })
+
+ test('an unknown name stops the run before anything is copied', () => {
+ const empty = mkdtempSync(path.join(work, 'empty-'))
+ expect(() =>
+ execFileSync('node', [path.join(root, 'bin/ipal-skills.mjs'), '--no-pointer', '--external', 'ext-nope'], { cwd: empty, stdio: 'pipe' }),
+ ).toThrow()
+ expect(readdirSync(empty)).toEqual([])
+ })
+})