diff --git a/.gitignore b/.gitignore
index 5d37bfd..2e496ee 100644
--- a/.gitignore
+++ b/.gitignore
@@ -45,10 +45,7 @@ next-env.d.ts
# local agent/tooling artifacts
.agents/
-.pi/
-prompts/
-docs-component-format-spec.md
-AGENTS.md
+
skills-lock.json
bun.lock
.env.local
diff --git a/.pi/prompts/README.md b/.pi/prompts/README.md
new file mode 100644
index 0000000..6da7dd0
--- /dev/null
+++ b/.pi/prompts/README.md
@@ -0,0 +1,17 @@
+# jal-co/ui Prompts
+
+Repo-aware prompts for creating, reviewing, and ideating jalco ui registry content.
+
+## Prompts
+
+- `/component-create` — create a new component, block, or registry item through the standard workflow
+- `/component-review` — audit an existing component against the jalco ui quality bar
+- `ideate-jalco-components.md` — ideate new additions based on the current repo state
+
+## How they work
+
+Each prompt:
+- reads the repo first (AGENTS.md, registry.json, existing patterns)
+- consults local skills before generating output
+- acts as an implementation/review partner, not a generic text generator
+- follows Conventional Branch naming for feature branches
diff --git a/.pi/prompts/component-create.md b/.pi/prompts/component-create.md
new file mode 100644
index 0000000..57af655
--- /dev/null
+++ b/.pi/prompts/component-create.md
@@ -0,0 +1,50 @@
+# /component-create
+
+Build a new jalco ui component through the standard repository workflow.
+
+
+Use this prompt when the user wants to create a new component, block, registry item, or docs-facing UI artifact.
+
+
+
+
+1. Create a feature branch: `feat/`.
+2. Read `.pi/skills/jalco-component-builder/SKILL.md` first and treat it as the primary workflow.
+3. If the request is underspecified, use the `question` or `questionnaire` tool to clarify the component before coding.
+4. Use concise, Socratic questioning to determine:
+ - the core use case
+ - whether this is a primitive, composed component, or block
+ - whether it belongs in the public registry, docs site only, or both
+ - the intended default feel and strongest default state
+ - the minimum public API
+ - which variants are truly justified
+ - whether the component should stay in one file
+ - whether any dependency is genuinely needed
+5. SHOULD prefer a single-file implementation unless multiple files materially improve readability, runtime correctness, reuse, or installability.
+6. Use supporting references named in `jalco-component-builder` as needed, especially for shadcn ergonomics, Tailwind v4 patterns, composition, React/Next implementation quality, and accessibility.
+7. Reuse established Jalco and shadcn variant language when appropriate, but MUST NOT add variants mechanically.
+8. SHOULD prefer strong default styling, realistic preview content, and restrained visual treatment over decorative complexity.
+9. If this is a public component, MUST update the docs, preview/demo coverage, and any relevant registry metadata in the same change.
+10. MUST create a catalog card preview at `components/docs/previews/.tsx` showing key variants, and run `pnpm previews:generate`.
+11. MUST add the sidebar nav entry in `lib/docs.ts` with `badge: "New"` and `badgeAdded` set to today's ISO date.
+12. MUST generate screenshots via `/dev/screenshots` — save `-dark.png` and `-light.png` to `public/previews/`.
+13. MUST run `pnpm registry:build` and `pnpm build` to verify.
+14. MUST open a PR using the component template and attach dark/light screenshots.
+15. MUST keep comments compact and useful. Use Jalco-style file headers when appropriate. MUST NOT add decorative separator banners.
+
+
+
+
+
+## Output expectations
+
+Before implementing, briefly state:
+- the component's use case
+- the proposed API shape
+- the justified variants
+- the one-file vs multi-file decision
+- any dependency decision
+
+Then implement the component and related docs updates.
+
+
diff --git a/.pi/prompts/component-review.md b/.pi/prompts/component-review.md
new file mode 100644
index 0000000..a8f9665
--- /dev/null
+++ b/.pi/prompts/component-review.md
@@ -0,0 +1,46 @@
+# /component-review
+
+Audit a jalco ui component using the repository's public component quality bar.
+
+
+Use this prompt when the user wants feedback on an existing component, registry item, docs-facing component, preview, or public API.
+
+
+
+
+1. MUST read `.pi/skills/jalco-component-builder/SKILL.md` first and use it as the review rubric.
+2. MUST inspect the component source, related demos/previews, and relevant docs before judging quality.
+3. Evaluate the component for:
+ - clarity of use case
+ - quality of the default state
+ - visual hierarchy and restraint
+ - API size and semantic clarity
+ - variant discipline
+ - one-file vs multi-file appropriateness
+ - dependency justification
+ - accessibility and copy-paste ergonomics
+ - alignment across implementation, preview, docs, and registry metadata
+ - presence of a catalog card preview file in `components/docs/previews/`
+ - sidebar nav entry in `lib/docs.ts`
+4. MUST be direct and critical when needed. MUST NOT praise weak work just because it is technically valid.
+5. If recommending changes, prioritize:
+ - what SHOULD be removed or simplified
+ - which variants SHOULD be merged or cut
+ - whether the file structure SHOULD be collapsed
+ - whether dependencies SHOULD be avoided
+ - how the default example SHOULD be improved
+
+
+
+
+
+## Output structure
+
+1. What feels strong
+2. What feels off or generic
+3. API and variant issues
+4. File structure and dependency issues
+5. Recommended changes in priority order
+6. Whether the component is ready for jalco ui in its current form
+
+
diff --git a/.pi/prompts/ideate-jalco-components.md b/.pi/prompts/ideate-jalco-components.md
new file mode 100644
index 0000000..c7bba65
--- /dev/null
+++ b/.pi/prompts/ideate-jalco-components.md
@@ -0,0 +1,78 @@
+# /ideate-jalco-components
+
+Ideate new jalco ui additions based on repository context and gaps.
+
+
+
+Before ideating, MUST read these files:
+- `AGENTS.md`
+- `README.md`
+- `registry.json`
+- `app/page.tsx`
+- `.pi/skills/vercel-react-best-practices/SKILL.md`
+- `.pi/skills/vercel-composition-patterns/SKILL.md`
+- `.pi/skills/tailwind-design-system/SKILL.md`
+
+Then inspect the current registry items and identify what categories, use cases, or quality levels are missing.
+
+
+
+
+
+## Task
+
+Help ideate new jalco ui additions based on this context:
+
+{{IDEATION_CONTEXT}}
+
+## Ideation goals
+
+Suggested additions MUST be:
+- practical
+- installable
+- visually strong
+- differentiated from generic examples
+- documentation-friendly
+- aligned with jalco ui's brand and quality bar
+
+Consider whether each idea is best as a:
+- component
+- block
+- hook
+- pattern
+- docs concept
+
+## Required process
+
+1. MUST read the required files first.
+2. MUST inspect the current registry and surface obvious gaps.
+3. SHOULD propose ideas that balance usefulness, visual appeal, and implementation value.
+4. SHOULD prioritize ideas that would make jalco ui more distinctive.
+5. SHOULD call out quick wins versus longer-term standout additions.
+
+
+
+
+
+## Output format
+
+Return these sections:
+
+1. **Current gap summary**
+2. **Top 10 proposed additions**
+ - name
+ - type
+ - what it does
+ - why it belongs in jalco ui
+ - implementation complexity: low / medium / high
+ - docs/demo appeal: low / medium / high
+3. **Best 3 quick wins**
+4. **Best 3 standout additions**
+5. **Suggested build order**
+6. **Docs categories these ideas support**
+
+
+
+
+Optimize for additions that would make jalco ui feel curated, not bloated.
+
diff --git a/.pi/references/docs-component-format-spec.md b/.pi/references/docs-component-format-spec.md
new file mode 100644
index 0000000..1051d0c
--- /dev/null
+++ b/.pi/references/docs-component-format-spec.md
@@ -0,0 +1,125 @@
+# Component Docs Format Spec
+
+Canonical reference for the structure, section order, writing rules, and review checklist of jalco ui component documentation pages.
+
+## Page anatomy
+
+Every component docs page MUST use `ComponentDocsPage` from `components/docs/component-docs-page.tsx` and follow this section order:
+
+1. **Metadata** — `export const metadata: Metadata` with `title` and `description`
+2. **Header** — rendered by `ComponentDocsPage`: title, description, AiCopyButton, DependencyBadges
+3. **Preview** — live component inside `ComponentPreview` with source file tabs
+4. **Installation** — `InstallCommand` with registry name; `installNote` for bundled exports
+5. **Usage** — import snippet via `CodeLine`, minimal usage example, server/client rendering context
+6. **Children** (optional, order as needed):
+ - Playground
+ - Examples (variants, sizes, configurations, etc.)
+ - API Reference
+ - Notes
+
+## ComponentDocsPage props
+
+| Prop | Type | Required | Purpose |
+|---|---|---|---|
+| `title` | `string` | yes | Display name (e.g. "GitHub Stars Button") |
+| `description` | `string` | yes | One-sentence summary |
+| `registryName` | `string` | no | Registry item name; enables install block and badges |
+| `sourceFiles` | `(string \| { path, name?, language? })[]` | no | Source file paths for the code tab |
+| `preview` | `ReactNode` | no | Live component for the Preview section |
+| `installNote` | `ReactNode` | no | Note below install command (e.g. bundled-in explanation) |
+| `usage` | `ReactNode` | no | Usage section content |
+| `children` | `ReactNode` | no | Everything after Usage |
+
+## Writing rules
+
+### Descriptions
+
+- MUST be one sentence, capability-first
+- MUST NOT start with "A", "An", or "A React component for..."
+- MUST NOT contain implementation details, subjective adjectives, or unnecessary jargon
+- MUST match across: page `metadata.description`, `ComponentDocsPage` `description` prop, and `registry.json` description
+
+### Usage section
+
+- MUST include an import snippet via `CodeLine`
+- MUST include a minimal usage example via `CodeLine`
+- Server/client rendering context MUST be stated here (e.g. "Async server component")
+- The first example SHOULD be minimal — layer complexity in the Examples section
+
+### Examples section
+
+- MUST use `VariantGrid` with labeled items when showing multiple visual states
+- MUST group items by meaning: Variants, Sizes, Icon Styles, Configurations, etc.
+- MUST NOT label everything as a "variant" — use the most accurate grouping label
+- SHOULD use realistic, polished content over placeholder text
+
+### Playground section
+
+- MAY be included when the component has multiple interactive props worth exploring
+- SHOULD be a client component that lets users toggle props and see results
+
+### API Reference section
+
+- SHOULD be included when the component has a non-obvious public API
+- MUST use `ApiRefTable` from `registry/api-ref-table/api-ref-table`
+- SHOULD list all public props with name, type, required flag, and description
+
+### Notes section
+
+- MUST contain only caveats, limitations, and external service behavior
+- MUST NOT contain architecture decisions, feature highlights, or rendering context
+- SHOULD be brief — a short bulleted list
+
+### Bundled exports
+
+- When a component is bundled inside another registry item, MUST use `installNote` to explain
+- MUST set `bundledIn` on the nav item in `lib/docs.ts`
+
+## Section heading style
+
+All `
` headings inside `ComponentDocsPage` children MUST use:
+
+```tsx
+
Section Title
+```
+
+Sub-headings (`
`) inside example groups MUST use:
+
+```tsx
+
Group Label
+```
+
+## Naming alignment
+
+These MUST all refer to the same artifact using consistent naming:
+- page `metadata.title`
+- `ComponentDocsPage` `title` prop
+- `registry.json` item `title`
+- sidebar nav title in `lib/docs.ts`
+- preview file name in `components/docs/previews/`
+- component export name
+
+## File header and comment rules
+
+- Public Jalco-authored component source files SHOULD use the compact Jalco-style header
+- Headers MUST be compact and human-written in tone
+- Headers MUST NOT duplicate the docs page content
+- Decorative separator banners MUST NOT appear in source code
+- Inline comments MUST be minimal and useful
+- Comments MUST NOT narrate straightforward code
+
+## Review checklist
+
+Before shipping a component docs page, verify:
+
+- [ ] Page uses `ComponentDocsPage`
+- [ ] `metadata.description` matches `ComponentDocsPage` `description` and `registry.json`
+- [ ] Preview renders a realistic default state
+- [ ] Usage includes import, minimal example, and server/client context
+- [ ] Examples use `VariantGrid` with accurate group labels
+- [ ] Notes contains only caveats (no features, no architecture)
+- [ ] Sidebar entry in `lib/docs.ts` is correct (title, order, badge, bundledIn)
+- [ ] Card preview exists at `components/docs/previews/.tsx`
+- [ ] Screenshots exist at `public/previews/-dark.png` and `-light.png`
+- [ ] `pnpm previews:generate` has been run
+- [ ] `pnpm registry:build` and `pnpm build` pass
diff --git a/.pi/skills/frontend-design/LICENSE.txt b/.pi/skills/frontend-design/LICENSE.txt
new file mode 100644
index 0000000..f433b1a
--- /dev/null
+++ b/.pi/skills/frontend-design/LICENSE.txt
@@ -0,0 +1,177 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/.pi/skills/frontend-design/SKILL.md b/.pi/skills/frontend-design/SKILL.md
new file mode 100644
index 0000000..172751b
--- /dev/null
+++ b/.pi/skills/frontend-design/SKILL.md
@@ -0,0 +1,62 @@
+---
+name: frontend-design
+description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.
+license: Complete terms in LICENSE.txt
+---
+
+
+Guide creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices.
+
+The user provides frontend requirements: a component, page, application, or interface to build. They MAY include context about the purpose, audience, or technical constraints.
+
+
+
+
+## Design Thinking
+
+Before coding, understand the context and commit to a bold aesthetic direction:
+
+- **Purpose**: What problem does this interface solve? Who uses it?
+- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. Use these for inspiration but design one that is true to the aesthetic direction.
+- **Constraints**: Technical requirements (framework, performance, accessibility).
+- **Differentiation**: What makes this unforgettable? What's the one thing someone will remember?
+
+The agent MUST choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work — the key is intentionality, not intensity.
+
+Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is:
+- Production-grade and functional
+- Visually striking and memorable
+- Cohesive with a clear aesthetic point-of-view
+- Meticulously refined in every detail
+
+
+
+
+
+## Frontend Aesthetics
+
+- **Typography**: MUST choose fonts that are beautiful, unique, and interesting. MUST NOT default to generic fonts like Arial and Inter. Pair a distinctive display font with a refined body font.
+- **Color & Theme**: MUST commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes.
+- **Motion**: SHOULD use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals creates more delight than scattered micro-interactions.
+- **Spatial Composition**: SHOULD use unexpected layouts — asymmetry, overlap, diagonal flow, grid-breaking elements, generous negative space or controlled density.
+- **Backgrounds & Visual Details**: SHOULD create atmosphere and depth rather than defaulting to solid colors. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays.
+
+
+
+
+
+## Anti-Patterns
+
+MUST NOT use generic AI-generated aesthetics:
+- Overused font families (Inter, Roboto, Arial, system fonts)
+- Cliched color schemes (particularly purple gradients on white backgrounds)
+- Predictable layouts and component patterns
+- Cookie-cutter design that lacks context-specific character
+
+MUST NOT converge on common choices (e.g. Space Grotesk) across generations. Each design MUST be distinct — vary between light and dark themes, different fonts, different aesthetics.
+
+## Complexity Matching
+
+Implementation complexity MUST match the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well.
+
+
diff --git a/.pi/skills/jalco-component-builder/SKILL.md b/.pi/skills/jalco-component-builder/SKILL.md
new file mode 100644
index 0000000..b940034
--- /dev/null
+++ b/.pi/skills/jalco-component-builder/SKILL.md
@@ -0,0 +1,315 @@
+---
+name: jalco-component-builder
+description: "Build jalco ui components through a deliberate workflow: clarify requirements, judge scope and file boundaries, prefer strong default states and restrained variants, implement with shadcn-style ergonomics, and ship aligned docs. Use when the user asks to create a component, build a component, make a new UI component, add a registry component, create a docs component, add variants, refactor a component, or review public components, demos, or docs-facing UI."
+---
+
+
+
+# jal-co/ui Component Builder
+
+Primary workflow skill for creating, refining, or reviewing a jalco ui component, block, demo, or docs-facing UI.
+
+Common triggers include requests like:
+- create a component
+- build a component
+- make a new UI component
+- add a registry component
+- create a docs component
+- add variants to this component
+- refactor this component
+- review this component
+
+This skill guides the sequence of decisions before implementation, while treating other skills as supporting references rather than equal peers.
+
+
+
+
+
+## Required reading before changes
+
+Before implementing a public component, the agent MUST read:
+- `AGENTS.md`
+- `.pi/references/docs-component-format-spec.md`
+- `.pi/skills/jalco-shadcn-registry/SKILL.md` for registry-backed work
+- `.pi/skills/jalco-writing-component-docs/SKILL.md` for docs work
+
+The agent MUST also inspect:
+- similar components already in the repo
+- related demo or preview files
+- related docs pages
+- `app/page.tsx` when adding homepage-style showcases
+
+## Supporting references
+
+Use these as references during implementation, not as separate workflow owners:
+- `shadcn-ui` for baseline shadcn component ergonomics, accessibility patterns, and common primitive composition
+- `.pi/skills/tailwind-design-system/SKILL.md` for semantic tokens, Tailwind v4 patterns, and variant consistency
+- `.pi/skills/vercel-composition-patterns/SKILL.md` for variant discipline, composition, and avoiding boolean-prop-heavy APIs
+- `.pi/skills/vercel-react-best-practices/SKILL.md` for React and Next.js implementation quality
+- `component-engineering` as a reference for semantics, accessibility, and prop/API discipline when needed
+
+## Core goal
+
+Build components that feel intentional, production-ready, readable, and easy to adapt.
+
+jalco ui components MUST NOT merely be valid. They MUST:
+- have a clear reason to exist
+- look strong in their default state
+- use restrained, consistent styling
+- prefer one strong layout idea over decorative layering
+- be easy to scan, copy, and modify
+- ship with aligned docs, preview, and registry metadata when public
+
+
+
+
+
+## Preferred workflow
+
+### 1. Clarify before coding
+
+The agent MUST NOT jump straight into implementation when the request is underspecified.
+
+Use the `question` or `questionnaire` tool to clarify what should be built when needed.
+
+Key questions to answer:
+- What problem does this component solve?
+- Is this a primitive, composed component, or a block?
+- Is it meant for the public registry, docs site only, or both?
+- What should the default state optimize for?
+- What surrounding UI context should the preview suggest?
+- Which variants are truly meaningful?
+- Should icons be muted, colored, or omitted?
+- Does motion materially improve the component or is static styling enough?
+- Should this stay in one file?
+- Is a new dependency truly justified?
+
+Use concise, Socratic questioning. Narrow the problem. SHOULD NOT ask endless open-ended questions if a small number of targeted choices will do.
+
+### 2. Define the component before implementation
+
+Before writing code, the agent MUST be able to state:
+1. the core use case in one sentence
+2. the primary visual idea
+3. the minimum public API
+4. the justified variants, if any
+5. whether it should be one file or multi-file
+6. whether any dependency is required
+7. what the default preview should demonstrate
+
+If those decisions are fuzzy, the agent MUST NOT start coding yet.
+
+### 3. Prefer one file by default
+
+For public jalco ui components, the agent SHOULD prefer a single file unless multiple files materially improve:
+- readability
+- runtime correctness
+- reuse across multiple items
+- installability
+- registry packaging clarity
+
+Keep local helpers, CVA variants, and small subcomponents inline when they are only meaningful inside the component.
+
+Use multiple files only when:
+- runtime boundaries differ (`use client`, server-only logic, dynamic loading)
+- a hook or utility is genuinely reused outside the component
+- the item is a true multi-part block
+- a single file becomes harder to understand than the separated version
+
+MUST NOT create unnecessary files like:
+- `types.ts` for one local interface
+- `constants.ts` for tiny local data
+- `utils.ts` for one component-local helper
+- internal file splitting that makes copy-paste adoption worse
+
+### 4. Prefer stronger defaults over more variants
+
+A component MUST be compelling in its default state.
+
+Variants MUST earn their existence.
+
+Use public variants only when they represent real differences in:
+- use case
+- semantics
+- structure
+- emphasis
+- layout behavior
+
+MUST NOT include decorative-only variants or tiny visual permutations.
+
+If a component needs substantially different structure across modes, prefer:
+- explicit exports
+- compound composition
+- separate components
+
+rather than one overloaded variant API.
+
+### 5. Keep styling restrained and product-like
+
+SHOULD prefer:
+- strong spacing and hierarchy
+- clear typography
+- semantic color usage
+- realistic layout rhythm
+- calm defaults
+
+MUST NOT:
+- layer border + tint + shadow + glow + gradient without purpose
+- add icons just to make a demo look more interesting
+- overuse nested rounded containers
+- create generic card wrappers with no clear opinion
+- ship demos that only work because they are over-decorated
+
+If the component only looks good in its fanciest state, the base design is too weak.
+
+### 6. Judge dependencies explicitly
+
+The agent MUST NOT add a dependency casually.
+
+Before adding one, evaluate:
+- Can this be done with existing repo dependencies?
+- Can this be done with CSS, Radix, or browser APIs?
+- Does the dependency materially improve the public component?
+- Does it make the registry item heavier or harder to adopt?
+- Would consumers reasonably expect this dependency?
+
+Default to no new dependency. Add one only when the benefit is clear.
+
+### 7. Implement with jalco ui conventions
+
+Implementation MUST:
+- match existing naming and styling conventions
+- use semantic tokens and repo utility patterns
+- avoid boolean-prop-heavy APIs
+- favor readable component code over architectural indirection
+- preserve accessibility and copy-paste ergonomics
+
+For public entry files:
+- SHOULD use the Jalco-style compact file header when appropriate
+- MUST NOT add decorative separator comments
+- MUST keep comments minimal and useful
+
+### 8. Ship docs and catalog preview as part of the component
+
+Public component work is not done until docs and the catalog card preview are updated.
+
+When applicable, the agent MUST update or create:
+- component docs page
+- preview/demo source
+- install instructions
+- usage examples
+- relevant homepage/showcase examples
+- registry metadata
+- sidebar nav entry in `lib/docs.ts`
+- catalog card preview at `components/docs/previews/.tsx`
+
+After creating or modifying a card preview file, `pnpm previews:generate` MUST be run to regenerate the import map. The codegen also runs automatically on `pnpm dev` and `pnpm build`.
+
+Card preview files:
+- MUST default-export an async server component
+- MUST render a miniature version of the component with realistic sample data
+- SHOULD show key variants, sizes, or layout exports when the component has them
+- MUST NOT be part of the installable registry item
+- live in `components/docs/previews/`, not inside `registry/`
+- also appear on the `/dev/screenshots` utility page for PNG export
+
+Descriptions, names, and preview coverage MUST stay aligned across all surfaces.
+
+
+
+
+
+## File boundary checklist
+
+Before splitting a component into multiple files, ask:
+1. Does the user benefit from opening more than one file?
+2. Are these parts reused outside this component family today?
+3. Do runtime boundaries require the split?
+4. Does the split improve installability or registry clarity?
+5. Would a single file still be easier to scan and adapt?
+6. Am I splitting because the design truly needs it, or because it feels more architectural?
+
+If most answers are no, keep it in one file.
+
+## Dependency checklist
+
+Before adding a new package, ask:
+1. Is there an existing repo dependency that already solves this?
+2. Can native CSS, Tailwind, or browser APIs handle it?
+3. Does this make the component meaningfully better for users?
+4. Will this complicate registry install or public adoption?
+5. Would I still choose this dependency if the component were being copied into a production app today?
+
+If the answer is uncertain, MUST NOT add it.
+
+## Component quality checklist
+
+Before shipping a public component, verify:
+1. The default example looks production-ready.
+2. The use case is clear and specific.
+3. The component is visually coherent without decorative extras.
+4. The public API is smaller and more semantic than the first draft.
+5. Variants map to real use cases.
+6. The file structure is simpler than the first draft.
+7. The preview content feels believable.
+8. The component is distinct enough to justify public inclusion.
+9. Docs, preview, and registry copy all describe the same artifact.
+10. A user could realistically copy the default version into a real app with minimal cleanup.
+11. A card preview file exists at `components/docs/previews/.tsx`.
+12. The sidebar nav entry exists in `lib/docs.ts`.
+
+
+
+
+
+## Recommended questioning patterns
+
+When requirements are underspecified, prefer questions like:
+- Which of these is closest: primitive, composed component, or block?
+- Should the default feel neutral, branded, dense, or editorial?
+- Is the main value layout, interaction, or presentation?
+- Do you want one strong default, or a small set of meaningful variants?
+- Should this optimize for docs-site display, public reuse, or both?
+- Would you expect this to install as a single file?
+
+SHOULD prefer multiple-choice clarification when possible.
+
+
+
+
+
+## Anti-patterns
+
+MUST NOT:
+- jump to code before clarifying the use case
+- split modest components into many files
+- create variants for completeness rather than usefulness
+- use icons, badges, or gradients to hide weak structure
+- over-abstract local helpers
+- add dependencies without a clear payoff
+- ship public components without aligned docs
+- treat preview coverage as separate from design quality
+
+
+
+
+
+## Recommended workflow summary
+
+1. Create a feature branch: `feat/`.
+2. Clarify the request.
+3. Inspect related repo patterns.
+4. Define use case, API, variants, file structure, and dependency needs.
+5. Implement the component with a one-file bias.
+6. Create or update previews and demos with realistic content.
+7. Create a catalog card preview at `components/docs/previews/.tsx` with key variants.
+8. Add the sidebar nav entry in `lib/docs.ts` with `badge: "New"` and `badgeAdded` set to today's ISO date.
+9. Update docs and registry metadata when public.
+10. Run `pnpm previews:generate` to update the import map.
+11. Generate screenshots via `/dev/screenshots` — save both dark and light PNGs to `public/previews/`.
+12. Run `pnpm registry:build` and `pnpm build` to verify.
+13. Open a PR using the component template (`.github/PULL_REQUEST_TEMPLATE/component.md`).
+14. Attach dark and light screenshots to the PR body.
+15. Review against the quality, file-boundary, and dependency checklists.
+
+
diff --git a/.pi/skills/jalco-shadcn-registry/README.md b/.pi/skills/jalco-shadcn-registry/README.md
new file mode 100644
index 0000000..72c21bd
--- /dev/null
+++ b/.pi/skills/jalco-shadcn-registry/README.md
@@ -0,0 +1,31 @@
+# jalco-shadcn-registry
+
+Repo-local skill for building and maintaining the jalco ui shadcn-compatible registry.
+
+## Use this skill for
+
+- registry item creation
+- registry.json maintenance
+- item type selection
+- namespace planning
+- authentication planning
+- MCP compatibility checks
+- Open in v0 compatibility checks
+- registry review workflows
+
+## Primary references
+
+- `AGENTS.md`
+- `registry.json`
+- `package.json`
+- shadcn registry docs
+- local jalco ui component/design-system skills
+
+## Notes
+
+This skill is tailored to jalco ui's use of the shadcn registry system and emphasizes:
+- installability
+- high-quality metadata
+- public/open-source quality
+- future namespace support
+- MCP-friendly registry structure
diff --git a/.pi/skills/jalco-shadcn-registry/SKILL.md b/.pi/skills/jalco-shadcn-registry/SKILL.md
new file mode 100644
index 0000000..c170cdd
--- /dev/null
+++ b/.pi/skills/jalco-shadcn-registry/SKILL.md
@@ -0,0 +1,252 @@
+---
+name: jalco-shadcn-registry
+description: Build and maintain the jalco ui shadcn-compatible registry. Use when creating or reviewing registry items, editing registry.json, choosing registry item types, configuring namespaced registries, planning authentication, adding docs metadata, or ensuring MCP/open-in-v0 compatibility.
+---
+
+
+
+# jal-co/ui shadcn Registry Skill
+
+Use this skill when working on jalco ui registry infrastructure, registry items, or registry-related docs.
+
+
+
+
+
+## Required reading before changes
+
+Before implementing registry work, the agent MUST read:
+- `AGENTS.md`
+- `registry.json`
+- `package.json`
+- `.pi/skills/vercel-react-best-practices/SKILL.md`
+- `.pi/skills/vercel-composition-patterns/SKILL.md`
+- `.pi/skills/tailwind-design-system/SKILL.md`
+
+When needed, the agent SHOULD also inspect:
+- `components.json`
+- `public/r`
+- `registry/`
+- `components/open-in-v0-button.tsx`
+- `app/page.tsx`
+
+## What this skill covers
+
+- creating new registry items
+- choosing the correct registry item type
+- updating `registry.json`
+- validating `files`, `target`, `dependencies`, and `registryDependencies`
+- organizing items under `registry/[style]/...`
+- planning namespaced registries
+- preparing for MCP compatibility
+- planning Open in v0 compatibility
+- documenting installation and usage
+- evaluating item types: `registry:component`, `registry:block`, `registry:ui`, `registry:lib`, `registry:hook`, `registry:style`, `registry:theme`, `registry:base`, or `registry:item`
+
+
+
+
+
+## Core rules from shadcn registry docs
+
+### Registry basics
+
+- The registry MUST expose a root `registry.json` payload.
+- `registry.json` MUST validate against `https://ui.shadcn.com/schema/registry.json`.
+- Registry items MUST conform to `https://ui.shadcn.com/schema/registry-item.json`.
+- The `shadcn build` command generates item payloads under `public/r` by default.
+- The registry index SHOULD maintain useful titles and descriptions.
+
+### File organization
+
+- Source files SHOULD be placed under `registry/[style]/[item-name]/...`.
+- For grouped items, internal folders like `components/`, `hooks/`, and `lib/` SHOULD be used.
+- Imports inside registry source MUST use the `@/registry/...` path when referencing registry-local files.
+- File structure MUST be intentional and installable.
+
+### Choosing item types
+
+The agent MUST use the smallest correct type:
+- `registry:component` for simple components
+- `registry:ui` for reusable UI primitives and single-file primitives
+- `registry:block` for multi-file installable blocks and richer examples
+- `registry:hook` for hooks
+- `registry:lib` for utilities and non-component code
+- `registry:page` for route/page files
+- `registry:file` for miscellaneous targeted files
+- `registry:theme` for theme tokens
+- `registry:style` for styles
+- `registry:base` for full design-system base configuration
+- `registry:item` for universal or framework-agnostic items
+
+### files and targets
+
+- Every file entry MUST include `path` and `type`.
+- `target` is REQUIRED for `registry:page` and `registry:file`.
+- Explicit targets SHOULD be used for universal items.
+- Target paths MUST be clear, intentional, and safe.
+
+### Dependencies
+
+- `dependencies` MUST be used for npm packages.
+- `devDependencies` MUST only be used for development-only packages.
+- `registryDependencies` MUST be used for shadcn items, namespaced items, or remote registry item URLs.
+- Dependencies MUST be complete and accurate.
+- Dependency sets SHOULD be minimal.
+
+### Metadata quality
+
+- `title` and `description` MUST have useful values.
+- Meaningful `categories` and `meta` SHOULD be provided when they improve discoverability.
+- `docs` SHOULD be used to show extra installation/setup guidance when needed.
+- Descriptions SHOULD help both humans and MCP/AI systems understand the item quickly.
+
+
+
+
+
+## Namespaces
+
+Namespace support SHOULD be planned early.
+
+### Namespace rules
+
+- Namespace names MUST start with `@`.
+- Format MUST be `@namespace/resource-name`.
+- Namespace config belongs in `components.json` under `registries`.
+- `{name}` in registry URLs MUST be supported.
+- `{style}` SHOULD be supported when serving style-specific variants.
+
+### Suggested jalco ui approach
+
+Start simple, then expand.
+
+Good initial public namespace options:
+- `@jalco` for primary public items
+- `@jalco-blocks` for blocks if separation becomes useful
+- `@jalco-experimental` for unstable items later
+
+Default recommendation:
+- keep the source registry simple first
+- design item naming and docs so a namespace strategy can be layered on cleanly later
+
+## Authentication
+
+For private registries or future premium/internal variants:
+- MUST use HTTPS
+- SHOULD use environment-variable-backed credentials
+- SHOULD support Bearer token or API key auth for CLI consumers
+- MAY use query parameter auth when needed for Open in v0 compatibility
+- MUST NOT commit tokens or real credentials
+
+### Open in v0 limitation
+
+Open in v0 does not support:
+- namespaced registries
+- cssVars
+- css
+- envVars
+- advanced header-based authentication
+
+If Open in v0 support is required, prefer a public item URL or query-parameter-based auth.
+
+## MCP compatibility
+
+The shadcn MCP server works with shadcn-compatible registries without special custom server work.
+
+To stay MCP-friendly:
+- `registry.json` MUST be valid and discoverable
+- Item names MUST be consistent and kebab-case
+- Descriptions SHOULD be informative
+- Dependencies MUST be declared accurately
+- `registryDependencies` MUST preserve clear relationships
+- A registry index item MUST be available at the expected root registry endpoint
+
+## Open-source registry index
+
+If jalco ui is submitted to the shadcn open-source registry index later:
+- the registry MUST be publicly accessible
+- the registry SHOULD be flat at the public endpoint
+- item payloads MUST be root-addressable
+- MUST NOT rely on embedded `content` in the public registry index listing
+- the final hosted shape MUST be validated against shadcn requirements before submission
+
+
+
+
+
+## jal-co/ui standards for registry work
+
+Every registry item MUST be:
+- installable
+- readable
+- accessible
+- polished
+- documentation-ready
+- consistent with jalco ui naming and design standards
+
+SHOULD prefer:
+- strong preview value
+- practical examples
+- accurate install guidance
+- minimal surprises for consumers
+
+MUST NOT include:
+- vague descriptions
+- bloated dependency lists
+- unclear file targets
+- overly clever item structures
+- inconsistent item types
+- undocumented environment variable requirements
+
+
+
+
+
+## Recommended workflow
+
+1. Create a feature branch: `feat/`.
+2. Read `AGENTS.md` and relevant local skills.
+3. Inspect similar registry items already in the repo.
+4. Choose the correct item type.
+5. Create files under the correct `registry/[style]/...` location.
+6. Update `registry.json` with accurate metadata.
+7. Verify dependencies and registry dependencies.
+8. Create a catalog card preview at `components/docs/previews/.tsx` with key variants.
+9. Add the sidebar nav entry in `lib/docs.ts` with `badge: "New"` and `badgeAdded` set to today's ISO date.
+10. Run `pnpm previews:generate` to update the catalog import map.
+11. Generate screenshots via `/dev/screenshots` — save dark and light PNGs to `public/previews/`.
+12. Run `pnpm registry:build`.
+13. Run `pnpm build` to verify full compilation.
+14. Test the local endpoint in `public/r` or via the dev server.
+15. Confirm docs/install copy is accurate.
+16. Open a PR using the component template (`.github/PULL_REQUEST_TEMPLATE/component.md`).
+17. If relevant, verify MCP and Open in v0 implications.
+
+## Useful commands
+
+```bash
+pnpm install
+pnpm dev
+pnpm registry:build
+pnpm dlx shadcn@latest view http://localhost:3000/r/.json
+pnpm dlx shadcn@latest add http://localhost:3000/r/.json
+```
+
+
+
+
+
+## When reviewing registry work
+
+Check for:
+- valid item type selection
+- correct `files` and `target` usage
+- complete dependency declarations
+- good descriptions and categories
+- installability
+- consistent registry paths
+- realistic docs guidance
+- namespace/auth/MCP/open-in-v0 implications when relevant
+
+
diff --git a/.pi/skills/jalco-writing-component-docs/SKILL.md b/.pi/skills/jalco-writing-component-docs/SKILL.md
new file mode 100644
index 0000000..d4340b2
--- /dev/null
+++ b/.pi/skills/jalco-writing-component-docs/SKILL.md
@@ -0,0 +1,119 @@
+---
+name: jalco-writing-component-docs
+description: Write and review jalco ui component documentation with consistent structure, concise descriptions, realistic examples, and registry-aligned metadata. Use when creating new component docs, updating existing docs, reviewing doc quality, or syncing registry-backed component copy.
+---
+
+
+
+# jal-co/ui Component Docs Skill
+
+Use this skill when creating, editing, or reviewing component documentation in jalco ui.
+
+## Canonical reference
+
+The single source of truth for docs page structure, section order, and formatting rules is:
+
+**`.pi/references/docs-component-format-spec.md`**
+
+The agent MUST read it before writing or updating any component docs. This skill provides workflow guidance and review steps, not a parallel format definition.
+
+
+
+
+
+## Required reading before changes
+
+1. `.pi/references/docs-component-format-spec.md` — page anatomy, section order, writing rules
+2. `AGENTS.md` — project conventions, quality bar, comment style
+3. `.pi/skills/jalco-shadcn-registry/SKILL.md` — for registry-backed items
+
+The agent MUST also inspect:
+- similar component docs already in the repo
+- the source component and its example/demo files
+- any related registry metadata
+
+## What this skill covers
+
+- writing new component docs
+- revising existing component docs
+- reviewing docs for clarity and consistency
+- writing or refining descriptions
+- keeping registry-backed descriptions in sync
+
+
+
+
+
+## Workflow
+
+1. Read `.pi/references/docs-component-format-spec.md` and this skill.
+2. Inspect similar docs pages in `app/docs/components/`.
+3. Review the component source, public API, and demo files.
+4. Create or update the page using `ComponentDocsPage` from `components/docs/component-docs-page.tsx`.
+5. Supply: `title`, `description`, `registryName`, `sourceFiles`, `preview`, `usage`.
+6. Add Examples, API Reference, Notes, or When to use sections as children — only when justified.
+7. Sync description and naming with `registry.json` and `lib/docs.ts`.
+8. Ensure a catalog card preview exists at `components/docs/previews/.tsx` with key variants.
+9. Ensure the sidebar nav entry exists in `lib/docs.ts` with `badge: "New"` and `badgeAdded` set for new components.
+10. Run `pnpm previews:generate` if the card preview file was created or renamed.
+11. Ensure screenshots exist at `public/previews/-dark.png` and `-light.png`.
+12. Review using the checklist in `.pi/references/docs-component-format-spec.md`.
+
+
+
+
+
+## Quick rules
+
+These are the rules most frequently needed during docs work. For full details, see the format spec.
+
+### Descriptions
+
+- MUST be one sentence, capability-first
+- MUST NOT start with "A", "An", or "A React component for..."
+- MUST NOT contain subjective adjectives
+- MUST match across: page metadata, ComponentDocsPage props, registry.json
+
+### Usage section
+
+- MUST include import and minimal usage snippets via `CodeLine`
+- Server/client rendering context MUST go here, not in Notes
+- The first example SHOULD be minimal — layer complexity in Examples
+
+### Examples
+
+- MUST use `VariantGrid` with labeled items
+- MUST group by meaning: Variants, Sizes, Languages, etc.
+- MUST NOT call everything a variant
+- SHOULD use realistic content
+
+### Notes
+
+- MUST contain only caveats, limitations, and external service behavior
+- MUST NOT include architecture decisions, feature highlights, or rendering context
+- SHOULD be brief
+
+### Bundled exports
+
+- MUST use `installNote` to explain the relationship
+- MUST set `bundledIn` on the nav item in `lib/docs.ts`
+
+
+
+
+
+## Review checklist
+
+Use the checklist in `.pi/references/docs-component-format-spec.md` before shipping any docs page.
+
+Key things to verify:
+1. Page uses `ComponentDocsPage`
+2. Description matches across all surfaces
+3. Preview is realistic
+4. Usage includes runtime context
+5. Examples are labeled correctly
+6. Notes contains only caveats
+7. Sidebar entry is correct (title, order, bundledIn)
+8. Catalog card preview exists at `components/docs/previews/.tsx`
+
+
diff --git a/.pi/skills/tailwind-design-system/SKILL.md b/.pi/skills/tailwind-design-system/SKILL.md
new file mode 100644
index 0000000..1848e5b
--- /dev/null
+++ b/.pi/skills/tailwind-design-system/SKILL.md
@@ -0,0 +1,894 @@
+---
+name: tailwind-design-system
+description: Build scalable design systems with Tailwind CSS v4, design tokens, component libraries, and responsive patterns. Use when creating component libraries, implementing design systems, or standardizing UI patterns.
+---
+
+
+
+# Tailwind Design System (v4)
+
+Build production-ready design systems with Tailwind CSS v4, including CSS-first configuration, design tokens, component variants, responsive patterns, and accessibility.
+
+> **Note**: This skill targets Tailwind CSS v4 (2024+). For v3 projects, refer to the [upgrade guide](https://tailwindcss.com/docs/upgrade-guide).
+
+
+
+
+
+## When to Use This Skill
+
+- Creating a component library with Tailwind v4
+- Implementing design tokens and theming with CSS-first configuration
+- Building responsive and accessible components
+- Standardizing UI patterns across a codebase
+- Migrating from Tailwind v3 to v4
+- Setting up dark mode with native CSS features
+
+## Key v4 Changes
+
+| v3 Pattern | v4 Pattern |
+| ------------------------------------- | --------------------------------------------------------------------- |
+| `tailwind.config.ts` | `@theme` in CSS |
+| `@tailwind base/components/utilities` | `@import "tailwindcss"` |
+| `darkMode: "class"` | `@custom-variant dark (&:where(.dark, .dark *))` |
+| `theme.extend.colors` | `@theme { --color-*: value }` |
+| `require("tailwindcss-animate")` | CSS `@keyframes` in `@theme` + `@starting-style` for entry animations |
+
+
+
+
+
+## Quick Start
+
+```css
+/* app.css - Tailwind v4 CSS-first configuration */
+@import "tailwindcss";
+
+/* Define your theme with @theme */
+@theme {
+ /* Semantic color tokens using OKLCH for better color perception */
+ --color-background: oklch(100% 0 0);
+ --color-foreground: oklch(14.5% 0.025 264);
+
+ --color-primary: oklch(14.5% 0.025 264);
+ --color-primary-foreground: oklch(98% 0.01 264);
+
+ --color-secondary: oklch(96% 0.01 264);
+ --color-secondary-foreground: oklch(14.5% 0.025 264);
+
+ --color-muted: oklch(96% 0.01 264);
+ --color-muted-foreground: oklch(46% 0.02 264);
+
+ --color-accent: oklch(96% 0.01 264);
+ --color-accent-foreground: oklch(14.5% 0.025 264);
+
+ --color-destructive: oklch(53% 0.22 27);
+ --color-destructive-foreground: oklch(98% 0.01 264);
+
+ --color-border: oklch(91% 0.01 264);
+ --color-ring: oklch(14.5% 0.025 264);
+
+ --color-card: oklch(100% 0 0);
+ --color-card-foreground: oklch(14.5% 0.025 264);
+
+ /* Ring offset for focus states */
+ --color-ring-offset: oklch(100% 0 0);
+
+ /* Radius tokens */
+ --radius-sm: 0.25rem;
+ --radius-md: 0.375rem;
+ --radius-lg: 0.5rem;
+ --radius-xl: 0.75rem;
+
+ /* Animation tokens - keyframes inside @theme are output when referenced by --animate-* variables */
+ --animate-fade-in: fade-in 0.2s ease-out;
+ --animate-fade-out: fade-out 0.2s ease-in;
+ --animate-slide-in: slide-in 0.3s ease-out;
+ --animate-slide-out: slide-out 0.3s ease-in;
+
+ @keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+ }
+
+ @keyframes fade-out {
+ from {
+ opacity: 1;
+ }
+ to {
+ opacity: 0;
+ }
+ }
+
+ @keyframes slide-in {
+ from {
+ transform: translateY(-0.5rem);
+ opacity: 0;
+ }
+ to {
+ transform: translateY(0);
+ opacity: 1;
+ }
+ }
+
+ @keyframes slide-out {
+ from {
+ transform: translateY(0);
+ opacity: 1;
+ }
+ to {
+ transform: translateY(-0.5rem);
+ opacity: 0;
+ }
+ }
+}
+
+/* Dark mode variant - use @custom-variant for class-based dark mode */
+@custom-variant dark (&:where(.dark, .dark *));
+
+/* Dark mode theme overrides */
+.dark {
+ --color-background: oklch(14.5% 0.025 264);
+ --color-foreground: oklch(98% 0.01 264);
+
+ --color-primary: oklch(98% 0.01 264);
+ --color-primary-foreground: oklch(14.5% 0.025 264);
+
+ --color-secondary: oklch(22% 0.02 264);
+ --color-secondary-foreground: oklch(98% 0.01 264);
+
+ --color-muted: oklch(22% 0.02 264);
+ --color-muted-foreground: oklch(65% 0.02 264);
+
+ --color-accent: oklch(22% 0.02 264);
+ --color-accent-foreground: oklch(98% 0.01 264);
+
+ --color-destructive: oklch(42% 0.15 27);
+ --color-destructive-foreground: oklch(98% 0.01 264);
+
+ --color-border: oklch(22% 0.02 264);
+ --color-ring: oklch(83% 0.02 264);
+
+ --color-card: oklch(14.5% 0.025 264);
+ --color-card-foreground: oklch(98% 0.01 264);
+
+ --color-ring-offset: oklch(14.5% 0.025 264);
+}
+
+/* Base styles */
+@layer base {
+ * {
+ @apply border-border;
+ }
+
+ body {
+ @apply bg-background text-foreground antialiased;
+ }
+}
+```
+
+
+
+
+
+## Core Concepts
+
+### 1. Design Token Hierarchy
+
+```
+Brand Tokens (abstract)
+ └── Semantic Tokens (purpose)
+ └── Component Tokens (specific)
+
+Example:
+ oklch(45% 0.2 260) → --color-primary → bg-primary
+```
+
+### 2. Component Architecture
+
+```
+Base styles → Variants → Sizes → States → Overrides
+```
+
+## Patterns
+
+### Pattern 1: CVA (Class Variance Authority) Components
+
+```typescript
+// components/ui/button.tsx
+import { Slot } from '@radix-ui/react-slot'
+import { cva, type VariantProps } from 'class-variance-authority'
+import { cn } from '@/lib/utils'
+
+const buttonVariants = cva(
+ // Base styles - v4 uses native CSS variables
+ 'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
+ {
+ variants: {
+ variant: {
+ default: 'bg-primary text-primary-foreground hover:bg-primary/90',
+ destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
+ outline: 'border border-border bg-background hover:bg-accent hover:text-accent-foreground',
+ secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
+ ghost: 'hover:bg-accent hover:text-accent-foreground',
+ link: 'text-primary underline-offset-4 hover:underline',
+ },
+ size: {
+ default: 'h-10 px-4 py-2',
+ sm: 'h-9 rounded-md px-3',
+ lg: 'h-11 rounded-md px-8',
+ icon: 'size-10',
+ },
+ },
+ defaultVariants: {
+ variant: 'default',
+ size: 'default',
+ },
+ }
+)
+
+export interface ButtonProps
+ extends React.ButtonHTMLAttributes,
+ VariantProps {
+ asChild?: boolean
+}
+
+// React 19: No forwardRef needed
+export function Button({
+ className,
+ variant,
+ size,
+ asChild = false,
+ ref,
+ ...props
+}: ButtonProps & { ref?: React.Ref }) {
+ const Comp = asChild ? Slot : 'button'
+ return (
+
+ )
+}
+
+// Usage
+
+
+
+```
+
+### Pattern 2: Compound Components (React 19)
+
+```typescript
+// components/ui/card.tsx
+import { cn } from '@/lib/utils'
+
+// React 19: ref is a regular prop, no forwardRef
+export function Card({
+ className,
+ ref,
+ ...props
+}: React.HTMLAttributes & { ref?: React.Ref }) {
+ return (
+
+ )
+}
+
+export function CardHeader({
+ className,
+ ref,
+ ...props
+}: React.HTMLAttributes & { ref?: React.Ref }) {
+ return (
+
+ )
+}
+
+export function CardTitle({
+ className,
+ ref,
+ ...props
+}: React.HTMLAttributes & { ref?: React.Ref }) {
+ return (
+
+ )
+}
+
+export function CardDescription({
+ className,
+ ref,
+ ...props
+}: React.HTMLAttributes & { ref?: React.Ref }) {
+ return (
+
+ )
+}
+
+export function CardContent({
+ className,
+ ref,
+ ...props
+}: React.HTMLAttributes & { ref?: React.Ref }) {
+ return (
+
+ )
+}
+
+export function CardFooter({
+ className,
+ ref,
+ ...props
+}: React.HTMLAttributes & { ref?: React.Ref }) {
+ return (
+
+ )
+}
+
+// Usage
+
+
+ Account
+ Manage your account settings
+
+
+
+
+
+
+
+
+```
+
+### Pattern 3: Form Components
+
+```typescript
+// components/ui/input.tsx
+import { cn } from '@/lib/utils'
+
+export interface InputProps extends React.InputHTMLAttributes {
+ error?: string
+ ref?: React.Ref
+}
+
+export function Input({ className, type, error, ref, ...props }: InputProps) {
+ return (
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+ )
+}
+
+// components/ui/label.tsx
+import { cva, type VariantProps } from 'class-variance-authority'
+
+const labelVariants = cva(
+ 'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
+)
+
+export function Label({
+ className,
+ ref,
+ ...props
+}: React.LabelHTMLAttributes & { ref?: React.Ref }) {
+ return (
+
+ )
+}
+
+// Usage with React Hook Form + Zod
+import { useForm } from 'react-hook-form'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { z } from 'zod'
+
+const schema = z.object({
+ email: z.string().email('Invalid email address'),
+ password: z.string().min(8, 'Password must be at least 8 characters'),
+})
+
+function LoginForm() {
+ const { register, handleSubmit, formState: { errors } } = useForm({
+ resolver: zodResolver(schema),
+ })
+
+ return (
+
+ )
+}
+```
+
+### Pattern 4: Responsive Grid System
+
+```typescript
+// components/ui/grid.tsx
+import { cn } from '@/lib/utils'
+import { cva, type VariantProps } from 'class-variance-authority'
+
+const gridVariants = cva('grid', {
+ variants: {
+ cols: {
+ 1: 'grid-cols-1',
+ 2: 'grid-cols-1 sm:grid-cols-2',
+ 3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3',
+ 4: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4',
+ 5: 'grid-cols-2 sm:grid-cols-3 lg:grid-cols-5',
+ 6: 'grid-cols-2 sm:grid-cols-3 lg:grid-cols-6',
+ },
+ gap: {
+ none: 'gap-0',
+ sm: 'gap-2',
+ md: 'gap-4',
+ lg: 'gap-6',
+ xl: 'gap-8',
+ },
+ },
+ defaultVariants: {
+ cols: 3,
+ gap: 'md',
+ },
+})
+
+interface GridProps
+ extends React.HTMLAttributes,
+ VariantProps {}
+
+export function Grid({ className, cols, gap, ...props }: GridProps) {
+ return (
+
+ )
+}
+
+// Container component
+const containerVariants = cva('mx-auto w-full px-4 sm:px-6 lg:px-8', {
+ variants: {
+ size: {
+ sm: 'max-w-screen-sm',
+ md: 'max-w-screen-md',
+ lg: 'max-w-screen-lg',
+ xl: 'max-w-screen-xl',
+ '2xl': 'max-w-screen-2xl',
+ full: 'max-w-full',
+ },
+ },
+ defaultVariants: {
+ size: 'xl',
+ },
+})
+
+interface ContainerProps
+ extends React.HTMLAttributes,
+ VariantProps {}
+
+export function Container({ className, size, ...props }: ContainerProps) {
+ return (
+
+ )
+}
+
+// Usage
+
+
+ {products.map((product) => (
+
+ ))}
+
+
+```
+
+### Pattern 5: Native CSS Animations (v4)
+
+```css
+/* In your CSS file - native @starting-style for entry animations */
+@theme {
+ --animate-dialog-in: dialog-fade-in 0.2s ease-out;
+ --animate-dialog-out: dialog-fade-out 0.15s ease-in;
+}
+
+@keyframes dialog-fade-in {
+ from {
+ opacity: 0;
+ transform: scale(0.95) translateY(-0.5rem);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+ }
+}
+
+@keyframes dialog-fade-out {
+ from {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+ }
+ to {
+ opacity: 0;
+ transform: scale(0.95) translateY(-0.5rem);
+ }
+}
+
+/* Native popover animations using @starting-style */
+[popover] {
+ transition:
+ opacity 0.2s,
+ transform 0.2s,
+ display 0.2s allow-discrete;
+ opacity: 0;
+ transform: scale(0.95);
+}
+
+[popover]:popover-open {
+ opacity: 1;
+ transform: scale(1);
+}
+
+@starting-style {
+ [popover]:popover-open {
+ opacity: 0;
+ transform: scale(0.95);
+ }
+}
+```
+
+```typescript
+// components/ui/dialog.tsx - Using native popover API
+import * as DialogPrimitive from '@radix-ui/react-dialog'
+import { cn } from '@/lib/utils'
+
+const DialogPortal = DialogPrimitive.Portal
+
+export function DialogOverlay({
+ className,
+ ref,
+ ...props
+}: React.ComponentPropsWithoutRef & {
+ ref?: React.Ref
+}) {
+ return (
+
+ )
+}
+
+export function DialogContent({
+ className,
+ children,
+ ref,
+ ...props
+}: React.ComponentPropsWithoutRef & {
+ ref?: React.Ref
+}) {
+ return (
+
+
+
+ {children}
+
+
+ )
+}
+```
+
+### Pattern 6: Dark Mode with CSS (v4)
+
+```typescript
+// providers/ThemeProvider.tsx - Simplified for v4
+'use client'
+
+import { createContext, useContext, useEffect, useState } from 'react'
+
+type Theme = 'dark' | 'light' | 'system'
+
+interface ThemeContextType {
+ theme: Theme
+ setTheme: (theme: Theme) => void
+ resolvedTheme: 'dark' | 'light'
+}
+
+const ThemeContext = createContext(undefined)
+
+export function ThemeProvider({
+ children,
+ defaultTheme = 'system',
+ storageKey = 'theme',
+}: {
+ children: React.ReactNode
+ defaultTheme?: Theme
+ storageKey?: string
+}) {
+ const [theme, setTheme] = useState(defaultTheme)
+ const [resolvedTheme, setResolvedTheme] = useState<'dark' | 'light'>('light')
+
+ useEffect(() => {
+ const stored = localStorage.getItem(storageKey) as Theme | null
+ if (stored) setTheme(stored)
+ }, [storageKey])
+
+ useEffect(() => {
+ const root = document.documentElement
+ root.classList.remove('light', 'dark')
+
+ const resolved = theme === 'system'
+ ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
+ : theme
+
+ root.classList.add(resolved)
+ setResolvedTheme(resolved)
+
+ // Update meta theme-color for mobile browsers
+ const metaThemeColor = document.querySelector('meta[name="theme-color"]')
+ if (metaThemeColor) {
+ metaThemeColor.setAttribute('content', resolved === 'dark' ? '#09090b' : '#ffffff')
+ }
+ }, [theme])
+
+ return (
+ {
+ localStorage.setItem(storageKey, newTheme)
+ setTheme(newTheme)
+ },
+ resolvedTheme,
+ }}>
+ {children}
+
+ )
+}
+
+export const useTheme = () => {
+ const context = useContext(ThemeContext)
+ if (!context) throw new Error('useTheme must be used within ThemeProvider')
+ return context
+}
+
+// components/ThemeToggle.tsx
+import { Moon, Sun } from 'lucide-react'
+import { useTheme } from '@/providers/ThemeProvider'
+
+export function ThemeToggle() {
+ const { resolvedTheme, setTheme } = useTheme()
+
+ return (
+
+ )
+}
+```
+
+## Utility Functions
+
+```typescript
+// lib/utils.ts
+import { type ClassValue, clsx } from "clsx";
+import { twMerge } from "tailwind-merge";
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs));
+}
+
+// Focus ring utility
+export const focusRing = cn(
+ "focus-visible:outline-none focus-visible:ring-2",
+ "focus-visible:ring-ring focus-visible:ring-offset-2",
+);
+
+// Disabled utility
+export const disabled = "disabled:pointer-events-none disabled:opacity-50";
+```
+
+
+
+
+
+## Advanced v4 Patterns
+
+### Custom Utilities with `@utility`
+
+Define reusable custom utilities:
+
+```css
+/* Custom utility for decorative lines */
+@utility line-t {
+ @apply relative before:absolute before:top-0 before:-left-[100vw] before:h-px before:w-[200vw] before:bg-gray-950/5 dark:before:bg-white/10;
+}
+
+/* Custom utility for text gradients */
+@utility text-gradient {
+ @apply bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent;
+}
+```
+
+### Theme Modifiers
+
+```css
+/* Use @theme inline when referencing other CSS variables */
+@theme inline {
+ --font-sans: var(--font-inter), system-ui;
+}
+
+/* Use @theme static to always generate CSS variables (even when unused) */
+@theme static {
+ --color-brand: oklch(65% 0.15 240);
+}
+
+/* Import with theme options */
+@import "tailwindcss" theme(static);
+```
+
+### Namespace Overrides
+
+```css
+@theme {
+ /* Clear all default colors and define your own */
+ --color-*: initial;
+ --color-white: #fff;
+ --color-black: #000;
+ --color-primary: oklch(45% 0.2 260);
+ --color-secondary: oklch(65% 0.15 200);
+
+ /* Clear ALL defaults for a minimal setup */
+ /* --*: initial; */
+}
+```
+
+### Semi-transparent Color Variants
+
+```css
+@theme {
+ /* Use color-mix() for alpha variants */
+ --color-primary-50: color-mix(in oklab, var(--color-primary) 5%, transparent);
+ --color-primary-100: color-mix(
+ in oklab,
+ var(--color-primary) 10%,
+ transparent
+ );
+ --color-primary-200: color-mix(
+ in oklab,
+ var(--color-primary) 20%,
+ transparent
+ );
+}
+```
+
+### Container Queries
+
+```css
+@theme {
+ --container-xs: 20rem;
+ --container-sm: 24rem;
+ --container-md: 28rem;
+ --container-lg: 32rem;
+}
+```
+
+
+
+
+
+## v3 to v4 Migration Checklist
+
+- [ ] Replace `tailwind.config.ts` with CSS `@theme` block
+- [ ] Change `@tailwind base/components/utilities` to `@import "tailwindcss"`
+- [ ] Move color definitions to `@theme { --color-*: value }`
+- [ ] Replace `darkMode: "class"` with `@custom-variant dark`
+- [ ] Move `@keyframes` inside `@theme` blocks (ensures keyframes output with theme)
+- [ ] Replace `require("tailwindcss-animate")` with native CSS animations
+- [ ] Update `h-10 w-10` to `size-10` (new utility)
+- [ ] Remove `forwardRef` (React 19 passes ref as prop)
+- [ ] Consider OKLCH colors for better color perception
+- [ ] Replace custom plugins with `@utility` directives
+
+
+
+
+
+## Best Practices
+
+### Do's
+
+- MUST use `@theme` blocks — CSS-first configuration is v4's core pattern
+- SHOULD use OKLCH colors — better perceptual uniformity than HSL
+- SHOULD compose with CVA — type-safe variants
+- MUST use semantic tokens — `bg-primary` not `bg-blue-500`
+- SHOULD use `size-*` — new shorthand for `w-* h-*`
+- MUST include accessibility — ARIA attributes, focus states
+
+### Don'ts
+
+- MUST NOT use `tailwind.config.ts` — use CSS `@theme` instead
+- MUST NOT use `@tailwind` directives — use `@import "tailwindcss"`
+- MUST NOT use `forwardRef` — React 19 passes ref as prop
+- SHOULD NOT use arbitrary values — extend `@theme` instead
+- MUST NOT hardcode colors — use semantic tokens
+- MUST NOT skip dark mode — test both themes
+
+
diff --git a/.pi/skills/vercel-composition-patterns/AGENTS.md b/.pi/skills/vercel-composition-patterns/AGENTS.md
new file mode 100644
index 0000000..558bf9a
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/AGENTS.md
@@ -0,0 +1,946 @@
+# React Composition Patterns
+
+**Version 1.0.0**
+Engineering
+January 2026
+
+> **Note:**
+> This document is mainly for agents and LLMs to follow when maintaining,
+> generating, or refactoring React codebases using composition. Humans
+> may also find it useful, but guidance here is optimized for automation
+> and consistency by AI-assisted workflows.
+
+---
+
+## Abstract
+
+Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.
+
+---
+
+## Table of Contents
+
+1. [Component Architecture](#1-component-architecture) — **HIGH**
+ - 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation)
+ - 1.2 [Use Compound Components](#12-use-compound-components)
+2. [State Management](#2-state-management) — **MEDIUM**
+ - 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui)
+ - 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection)
+ - 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)
+3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM**
+ - 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants)
+ - 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)
+4. [React 19 APIs](#4-react-19-apis) — **MEDIUM**
+ - 4.1 [React 19 API Changes](#41-react-19-api-changes)
+
+---
+
+## 1. Component Architecture
+
+**Impact: HIGH**
+
+Fundamental patterns for structuring components to avoid prop
+proliferation and enable flexible composition.
+
+### 1.1 Avoid Boolean Prop Proliferation
+
+**Impact: CRITICAL (prevents unmaintainable component variants)**
+
+Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
+
+component behavior. Each boolean doubles possible states and creates
+
+unmaintainable conditional logic. Use composition instead.
+
+**Incorrect: boolean props create exponential complexity**
+
+```tsx
+function Composer({
+ onSubmit,
+ isThread,
+ channelId,
+ isDMThread,
+ dmId,
+ isEditing,
+ isForwarding,
+}: Props) {
+ return (
+
+ )
+}
+```
+
+**Correct: composition eliminates conditionals**
+
+```tsx
+// Channel composer
+function ChannelComposer() {
+ return (
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+// Thread composer - adds "also send to channel" field
+function ThreadComposer({ channelId }: { channelId: string }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+// Edit composer - different footer actions
+function EditComposer() {
+ return (
+
+
+
+
+
+
+
+
+
+ )
+}
+```
+
+Each variant is explicit about what it renders. We can share internals without
+
+sharing a single monolithic parent.
+
+### 1.2 Use Compound Components
+
+**Impact: HIGH (enables flexible composition without prop drilling)**
+
+Structure complex components as compound components with a shared context. Each
+
+subcomponent accesses shared state via context, not props. Consumers compose the
+
+pieces they need.
+
+**Incorrect: monolithic component with render props**
+
+```tsx
+function Composer({
+ renderHeader,
+ renderFooter,
+ renderActions,
+ showAttachments,
+ showFormatting,
+ showEmojis,
+}: Props) {
+ return (
+
+ )
+}
+```
+
+**Correct: compound components with shared context**
+
+```tsx
+const ComposerContext = createContext(null)
+
+function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
+ return (
+
+ {children}
+
+ )
+}
+
+function ComposerFrame({ children }: { children: React.ReactNode }) {
+ return
+}
+
+function ComposerInput() {
+ const {
+ state,
+ actions: { update },
+ meta: { inputRef },
+ } = use(ComposerContext)
+ return (
+ update((s) => ({ ...s, input: text }))}
+ />
+ )
+}
+
+function ComposerSubmit() {
+ const {
+ actions: { submit },
+ } = use(ComposerContext)
+ return
+}
+
+// Export as compound component
+const Composer = {
+ Provider: ComposerProvider,
+ Frame: ComposerFrame,
+ Input: ComposerInput,
+ Submit: ComposerSubmit,
+ Header: ComposerHeader,
+ Footer: ComposerFooter,
+ Attachments: ComposerAttachments,
+ Formatting: ComposerFormatting,
+ Emojis: ComposerEmojis,
+}
+```
+
+**Usage:**
+
+```tsx
+
+
+
+
+
+
+
+
+
+
+```
+
+Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
+
+---
+
+## 2. State Management
+
+**Impact: MEDIUM**
+
+Patterns for lifting state and managing shared context across
+composed components.
+
+### 2.1 Decouple State Management from UI
+
+**Impact: MEDIUM (enables swapping state implementations without changing UI)**
+
+The provider component should be the only place that knows how state is managed.
+
+UI components consume the context interface—they don't know if state comes from
+
+useState, Zustand, or a server sync.
+
+**Incorrect: UI coupled to state implementation**
+
+```tsx
+function ChannelComposer({ channelId }: { channelId: string }) {
+ // UI component knows about global state implementation
+ const state = useGlobalChannelState(channelId)
+ const { submit, updateInput } = useChannelSync(channelId)
+
+ return (
+
+ sync.updateInput(text)}
+ />
+ sync.submit()} />
+
+ )
+}
+```
+
+**Correct: state management isolated in provider**
+
+```tsx
+// Provider handles all state management details
+function ChannelProvider({
+ channelId,
+ children,
+}: {
+ channelId: string
+ children: React.ReactNode
+}) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+ const inputRef = useRef(null)
+
+ return (
+
+ {children}
+
+ )
+}
+
+// UI component only knows about the context interface
+function ChannelComposer() {
+ return (
+
+
+
+
+
+
+
+ )
+}
+
+// Usage
+function Channel({ channelId }: { channelId: string }) {
+ return (
+
+
+
+ )
+}
+```
+
+**Different providers, same UI:**
+
+```tsx
+// Local state for ephemeral forms
+function ForwardMessageProvider({ children }) {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+
+ return (
+
+ {children}
+
+ )
+}
+
+// Global synced state for channels
+function ChannelProvider({ channelId, children }) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+
+ return (
+
+ {children}
+
+ )
+}
+```
+
+The same `Composer.Input` component works with both providers because it only
+
+depends on the context interface, not the implementation.
+
+### 2.2 Define Generic Context Interfaces for Dependency Injection
+
+**Impact: HIGH (enables dependency-injectable state across use-cases)**
+
+Define a **generic interface** for your component context with three parts:
+
+`state`, `actions`, and `meta`. This interface is a contract that any provider
+
+can implement—enabling the same UI components to work with completely different
+
+state implementations.
+
+**Core principle:** Lift state, compose internals, make state
+
+dependency-injectable.
+
+**Incorrect: UI coupled to specific state implementation**
+
+```tsx
+function ComposerInput() {
+ // Tightly coupled to a specific hook
+ const { input, setInput } = useChannelComposerState()
+ return
+}
+```
+
+**Correct: generic interface enables dependency injection**
+
+```tsx
+// Define a GENERIC interface that any provider can implement
+interface ComposerState {
+ input: string
+ attachments: Attachment[]
+ isSubmitting: boolean
+}
+
+interface ComposerActions {
+ update: (updater: (state: ComposerState) => ComposerState) => void
+ submit: () => void
+}
+
+interface ComposerMeta {
+ inputRef: React.RefObject
+}
+
+interface ComposerContextValue {
+ state: ComposerState
+ actions: ComposerActions
+ meta: ComposerMeta
+}
+
+const ComposerContext = createContext(null)
+```
+
+**UI components consume the interface, not the implementation:**
+
+```tsx
+function ComposerInput() {
+ const {
+ state,
+ actions: { update },
+ meta,
+ } = use(ComposerContext)
+
+ // This component works with ANY provider that implements the interface
+ return (
+ update((s) => ({ ...s, input: text }))}
+ />
+ )
+}
+```
+
+**Different providers implement the same interface:**
+
+```tsx
+// Provider A: Local state for ephemeral forms
+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
+ const [state, setState] = useState(initialState)
+ const inputRef = useRef(null)
+ const submit = useForwardMessage()
+
+ return (
+
+ {children}
+
+ )
+}
+
+// Provider B: Global synced state for channels
+function ChannelProvider({ channelId, children }: Props) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+ const inputRef = useRef(null)
+
+ return (
+
+ {children}
+
+ )
+}
+```
+
+**The same composed UI works with both:**
+
+```tsx
+// Works with ForwardMessageProvider (local state)
+
+
+
+
+
+
+
+// Works with ChannelProvider (global synced state)
+
+
+
+
+
+
+```
+
+**Custom UI outside the component can access state and actions:**
+
+```tsx
+function ForwardMessageDialog() {
+ return (
+
+
+
+ )
+}
+
+// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
+function ForwardButton() {
+ const {
+ actions: { submit },
+ } = use(ComposerContext)
+ return
+}
+
+// This preview lives OUTSIDE Composer.Frame but can read composer's state!
+function MessagePreview() {
+ const { state } = use(ComposerContext)
+ return
+}
+```
+
+The provider boundary is what matters—not the visual nesting. Components that
+
+need shared state don't have to be inside the `Composer.Frame`. They just need
+
+to be within the provider.
+
+The `ForwardButton` and `MessagePreview` are not visually inside the composer
+
+box, but they can still access its state and actions. This is the power of
+
+lifting state into providers.
+
+The UI is reusable bits you compose together. The state is dependency-injected
+
+by the provider. Swap the provider, keep the UI.
+
+### 2.3 Lift State into Provider Components
+
+**Impact: HIGH (enables state sharing outside component boundaries)**
+
+Move state management into dedicated provider components. This allows sibling
+
+components outside the main UI to access and modify state without prop drilling
+
+or awkward refs.
+
+**Incorrect: state trapped inside component**
+
+```tsx
+function ForwardMessageComposer() {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+
+ return (
+
+
+
+
+ )
+}
+
+// Problem: How does this button access composer state?
+function ForwardMessageDialog() {
+ return (
+
+ )
+}
+```
+
+**Incorrect: useEffect to sync state up**
+
+```tsx
+function ForwardMessageDialog() {
+ const [input, setInput] = useState('')
+ return (
+
+ )
+}
+
+function ForwardMessageComposer({ onInputChange }) {
+ const [state, setState] = useState(initialState)
+ useEffect(() => {
+ onInputChange(state.input) // Sync on every change 😬
+ }, [state.input])
+}
+```
+
+**Incorrect: reading state from ref on submit**
+
+```tsx
+function ForwardMessageDialog() {
+ const stateRef = useRef(null)
+ return (
+
+ )
+}
+```
+
+**Correct: state lifted to provider**
+
+```tsx
+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+ const inputRef = useRef(null)
+
+ return (
+
+ {children}
+
+ )
+}
+
+function ForwardMessageDialog() {
+ return (
+
+
+
+ )
+}
+
+function ForwardButton() {
+ const { actions } = use(Composer.Context)
+ return
+}
+```
+
+The ForwardButton lives outside the Composer.Frame but still has access to the
+
+submit action because it's within the provider. Even though it's a one-off
+
+component, it can still access the composer's state and actions from outside the
+
+UI itself.
+
+**Key insight:** Components that need shared state don't have to be visually
+
+nested inside each other—they just need to be within the same provider.
+
+---
+
+## 3. Implementation Patterns
+
+**Impact: MEDIUM**
+
+Specific techniques for implementing compound components and
+context providers.
+
+### 3.1 Create Explicit Component Variants
+
+**Impact: MEDIUM (self-documenting code, no hidden conditionals)**
+
+Instead of one component with many boolean props, create explicit variant
+
+components. Each variant composes the pieces it needs. The code documents
+
+itself.
+
+**Incorrect: one component, many modes**
+
+```tsx
+// What does this component actually render?
+
+```
+
+**Correct: explicit variants**
+
+```tsx
+// Immediately clear what this renders
+
+
+// Or
+
+
+// Or
+
+```
+
+Each implementation is unique, explicit and self-contained. Yet they can each
+
+use shared parts.
+
+**Implementation:**
+
+```tsx
+function ThreadComposer({ channelId }: { channelId: string }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+function EditMessageComposer({ messageId }: { messageId: string }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+function ForwardMessageComposer({ messageId }: { messageId: string }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+ )
+}
+```
+
+Each variant is explicit about:
+
+- What provider/state it uses
+
+- What UI elements it includes
+
+- What actions are available
+
+No boolean prop combinations to reason about. No impossible states.
+
+### 3.2 Prefer Composing Children Over Render Props
+
+**Impact: MEDIUM (cleaner composition, better readability)**
+
+Use `children` for composition instead of `renderX` props. Children are more
+
+readable, compose naturally, and don't require understanding callback
+
+signatures.
+
+**Incorrect: render props**
+
+```tsx
+function Composer({
+ renderHeader,
+ renderFooter,
+ renderActions,
+}: {
+ renderHeader?: () => React.ReactNode
+ renderFooter?: () => React.ReactNode
+ renderActions?: () => React.ReactNode
+}) {
+ return (
+
+ )
+}
+
+// Usage is awkward and inflexible
+return (
+ }
+ renderFooter={() => (
+ <>
+
+
+ >
+ )}
+ renderActions={() => }
+ />
+)
+```
+
+**Correct: compound components with children**
+
+```tsx
+function ComposerFrame({ children }: { children: React.ReactNode }) {
+ return
+}
+
+function ComposerFooter({ children }: { children: React.ReactNode }) {
+ return
+}
+
+// Usage is flexible
+return (
+
+
+
+
+
+
+
+
+
+)
+```
+
+**When render props are appropriate:**
+
+```tsx
+// Render props work well when you need to pass data back
+}
+/>
+```
+
+Use render props when the parent needs to provide data or state to the child.
+
+Use children when composing static structure.
+
+---
+
+## 4. React 19 APIs
+
+**Impact: MEDIUM**
+
+React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
+
+### 4.1 React 19 API Changes
+
+**Impact: MEDIUM (cleaner component definitions and context usage)**
+
+> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
+
+In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
+
+**Incorrect: forwardRef in React 19**
+
+```tsx
+const ComposerInput = forwardRef((props, ref) => {
+ return
+})
+```
+
+**Correct: ref as a regular prop**
+
+```tsx
+function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref }) {
+ return
+}
+```
+
+**Incorrect: useContext in React 19**
+
+```tsx
+const value = useContext(MyContext)
+```
+
+**Correct: use instead of useContext**
+
+```tsx
+const value = use(MyContext)
+```
+
+`use()` can also be called conditionally, unlike `useContext()`.
+
+---
+
+## References
+
+1. [https://react.dev](https://react.dev)
+2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)
+3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)
diff --git a/.pi/skills/vercel-composition-patterns/README.md b/.pi/skills/vercel-composition-patterns/README.md
new file mode 100644
index 0000000..01f359b
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/README.md
@@ -0,0 +1,60 @@
+# React Composition Patterns
+
+A structured repository for React composition patterns that scale. These
+patterns help avoid boolean prop proliferation by using compound components,
+lifting state, and composing internals.
+
+## Structure
+
+- `rules/` - Individual rule files (one per rule)
+ - `_sections.md` - Section metadata (titles, impacts, descriptions)
+ - `_template.md` - Template for creating new rules
+ - `area-description.md` - Individual rule files
+- `metadata.json` - Document metadata (version, organization, abstract)
+- **`AGENTS.md`** - Compiled output (generated)
+
+## Rules
+
+### Component Architecture (CRITICAL)
+
+- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize
+ behavior
+- `architecture-compound-components.md` - Structure as compound components with
+ shared context
+
+### State Management (HIGH)
+
+- `state-lift-state.md` - Lift state into provider components
+- `state-context-interface.md` - Define clear context interfaces
+ (state/actions/meta)
+- `state-decouple-implementation.md` - Decouple state management from UI
+
+### Implementation Patterns (MEDIUM)
+
+- `patterns-children-over-render-props.md` - Prefer children over renderX props
+- `patterns-explicit-variants.md` - Create explicit component variants
+
+## Core Principles
+
+1. **Composition over configuration** — Instead of adding props, let consumers
+ compose
+2. **Lift your state** — State in providers, not trapped in components
+3. **Compose your internals** — Subcomponents access context, not props
+4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer
+ with isThread
+
+## Creating a New Rule
+
+1. Copy `rules/_template.md` to `rules/area-description.md`
+2. Choose the appropriate area prefix:
+ - `architecture-` for Component Architecture
+ - `state-` for State Management
+ - `patterns-` for Implementation Patterns
+3. Fill in the frontmatter and content
+4. Ensure you have clear examples with explanations
+
+## Impact Levels
+
+- `CRITICAL` - Foundational patterns, prevents unmaintainable code
+- `HIGH` - Significant maintainability improvements
+- `MEDIUM` - Good practices for cleaner code
diff --git a/.pi/skills/vercel-composition-patterns/SKILL.md b/.pi/skills/vercel-composition-patterns/SKILL.md
new file mode 100644
index 0000000..d101aad
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/SKILL.md
@@ -0,0 +1,97 @@
+---
+name: vercel-composition-patterns
+description:
+ React composition patterns that scale. Use when refactoring components with
+ boolean prop proliferation, building flexible component libraries, or
+ designing reusable APIs. Triggers on tasks involving compound components,
+ render props, context providers, or component architecture. Includes React 19
+ API changes.
+license: MIT
+metadata:
+ author: vercel
+ version: '1.0.0'
+---
+
+
+
+# React Composition Patterns
+
+Composition patterns for building flexible, maintainable React components. Avoid
+boolean prop proliferation by using compound components, lifting state, and
+composing internals. These patterns make codebases easier for both humans and AI
+agents to work with as they scale.
+
+
+
+
+
+## When to Apply
+
+Reference these guidelines when:
+- Refactoring components with many boolean props
+- Building reusable component libraries
+- Designing flexible component APIs
+- Reviewing component architecture
+- Working with compound components or context providers
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+| -------- | ----------------------- | ------ | --------------- |
+| 1 | Component Architecture | HIGH | `architecture-` |
+| 2 | State Management | MEDIUM | `state-` |
+| 3 | Implementation Patterns | MEDIUM | `patterns-` |
+| 4 | React 19 APIs | MEDIUM | `react19-` |
+
+
+
+
+
+## Quick Reference
+
+### 1. Component Architecture (HIGH)
+
+- `architecture-avoid-boolean-props` — MUST NOT add boolean props to customize behavior; use composition
+- `architecture-compound-components` — SHOULD structure complex components with shared context
+
+### 2. State Management (MEDIUM)
+
+- `state-decouple-implementation` — Provider MUST be the only place that knows how state is managed
+- `state-context-interface` — SHOULD define generic interface with state, actions, meta for dependency injection
+- `state-lift-state` — SHOULD move state into provider components for sibling access
+
+### 3. Implementation Patterns (MEDIUM)
+
+- `patterns-explicit-variants` — SHOULD create explicit variant components instead of boolean modes
+- `patterns-children-over-render-props` — SHOULD use children for composition instead of renderX props
+
+### 4. React 19 APIs (MEDIUM)
+
+> **⚠️ React 19+ only.** Skip this section if using React 18 or earlier.
+
+- `react19-no-forwardref` — MUST NOT use `forwardRef`; use `use()` instead of `useContext()`
+
+
+
+
+
+## How to Use
+
+Read individual rule files for detailed explanations and code examples:
+
+```
+rules/architecture-avoid-boolean-props.md
+rules/state-context-interface.md
+```
+
+Each rule file contains:
+- Brief explanation of why it matters
+- Incorrect code example with explanation
+- Correct code example with explanation
+- Additional context and references
+
+## Full Compiled Document
+
+For the complete guide with all rules expanded: `AGENTS.md`
+
+
diff --git a/.pi/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md b/.pi/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md
new file mode 100644
index 0000000..ccee19c
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md
@@ -0,0 +1,100 @@
+---
+title: Avoid Boolean Prop Proliferation
+impact: CRITICAL
+impactDescription: prevents unmaintainable component variants
+tags: composition, props, architecture
+---
+
+## Avoid Boolean Prop Proliferation
+
+Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
+component behavior. Each boolean doubles possible states and creates
+unmaintainable conditional logic. Use composition instead.
+
+**Incorrect (boolean props create exponential complexity):**
+
+```tsx
+function Composer({
+ onSubmit,
+ isThread,
+ channelId,
+ isDMThread,
+ dmId,
+ isEditing,
+ isForwarding,
+}: Props) {
+ return (
+
+ )
+}
+```
+
+**Correct (composition eliminates conditionals):**
+
+```tsx
+// Channel composer
+function ChannelComposer() {
+ return (
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+// Thread composer - adds "also send to channel" field
+function ThreadComposer({ channelId }: { channelId: string }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+// Edit composer - different footer actions
+function EditComposer() {
+ return (
+
+
+
+
+
+
+
+
+
+ )
+}
+```
+
+Each variant is explicit about what it renders. We can share internals without
+sharing a single monolithic parent.
diff --git a/.pi/skills/vercel-composition-patterns/rules/architecture-compound-components.md b/.pi/skills/vercel-composition-patterns/rules/architecture-compound-components.md
new file mode 100644
index 0000000..e5e3043
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/rules/architecture-compound-components.md
@@ -0,0 +1,112 @@
+---
+title: Use Compound Components
+impact: HIGH
+impactDescription: enables flexible composition without prop drilling
+tags: composition, compound-components, architecture
+---
+
+## Use Compound Components
+
+Structure complex components as compound components with a shared context. Each
+subcomponent accesses shared state via context, not props. Consumers compose the
+pieces they need.
+
+**Incorrect (monolithic component with render props):**
+
+```tsx
+function Composer({
+ renderHeader,
+ renderFooter,
+ renderActions,
+ showAttachments,
+ showFormatting,
+ showEmojis,
+}: Props) {
+ return (
+
+ )
+}
+```
+
+**Correct (compound components with shared context):**
+
+```tsx
+const ComposerContext = createContext(null)
+
+function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
+ return (
+
+ {children}
+
+ )
+}
+
+function ComposerFrame({ children }: { children: React.ReactNode }) {
+ return
+}
+
+function ComposerInput() {
+ const {
+ state,
+ actions: { update },
+ meta: { inputRef },
+ } = use(ComposerContext)
+ return (
+ update((s) => ({ ...s, input: text }))}
+ />
+ )
+}
+
+function ComposerSubmit() {
+ const {
+ actions: { submit },
+ } = use(ComposerContext)
+ return
+}
+
+// Export as compound component
+const Composer = {
+ Provider: ComposerProvider,
+ Frame: ComposerFrame,
+ Input: ComposerInput,
+ Submit: ComposerSubmit,
+ Header: ComposerHeader,
+ Footer: ComposerFooter,
+ Attachments: ComposerAttachments,
+ Formatting: ComposerFormatting,
+ Emojis: ComposerEmojis,
+}
+```
+
+**Usage:**
+
+```tsx
+
+
+
+
+
+
+
+
+
+
+```
+
+Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
diff --git a/.pi/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md b/.pi/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md
new file mode 100644
index 0000000..d4345ee
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md
@@ -0,0 +1,87 @@
+---
+title: Prefer Composing Children Over Render Props
+impact: MEDIUM
+impactDescription: cleaner composition, better readability
+tags: composition, children, render-props
+---
+
+## Prefer Children Over Render Props
+
+Use `children` for composition instead of `renderX` props. Children are more
+readable, compose naturally, and don't require understanding callback
+signatures.
+
+**Incorrect (render props):**
+
+```tsx
+function Composer({
+ renderHeader,
+ renderFooter,
+ renderActions,
+}: {
+ renderHeader?: () => React.ReactNode
+ renderFooter?: () => React.ReactNode
+ renderActions?: () => React.ReactNode
+}) {
+ return (
+
+ )
+}
+
+// Usage is awkward and inflexible
+return (
+ }
+ renderFooter={() => (
+ <>
+
+
+ >
+ )}
+ renderActions={() => }
+ />
+)
+```
+
+**Correct (compound components with children):**
+
+```tsx
+function ComposerFrame({ children }: { children: React.ReactNode }) {
+ return
+}
+
+function ComposerFooter({ children }: { children: React.ReactNode }) {
+ return
+}
+
+// Usage is flexible
+return (
+
+
+
+
+
+
+
+
+
+)
+```
+
+**When render props are appropriate:**
+
+```tsx
+// Render props work well when you need to pass data back
+}
+/>
+```
+
+Use render props when the parent needs to provide data or state to the child.
+Use children when composing static structure.
diff --git a/.pi/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md b/.pi/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md
new file mode 100644
index 0000000..56e32e8
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md
@@ -0,0 +1,100 @@
+---
+title: Create Explicit Component Variants
+impact: MEDIUM
+impactDescription: self-documenting code, no hidden conditionals
+tags: composition, variants, architecture
+---
+
+## Create Explicit Component Variants
+
+Instead of one component with many boolean props, create explicit variant
+components. Each variant composes the pieces it needs. The code documents
+itself.
+
+**Incorrect (one component, many modes):**
+
+```tsx
+// What does this component actually render?
+
+```
+
+**Correct (explicit variants):**
+
+```tsx
+// Immediately clear what this renders
+
+
+// Or
+
+
+// Or
+
+```
+
+Each implementation is unique, explicit and self-contained. Yet they can each
+use shared parts.
+
+**Implementation:**
+
+```tsx
+function ThreadComposer({ channelId }: { channelId: string }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+function EditMessageComposer({ messageId }: { messageId: string }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
+
+function ForwardMessageComposer({ messageId }: { messageId: string }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+ )
+}
+```
+
+Each variant is explicit about:
+
+- What provider/state it uses
+- What UI elements it includes
+- What actions are available
+
+No boolean prop combinations to reason about. No impossible states.
diff --git a/.pi/skills/vercel-composition-patterns/rules/react19-no-forwardref.md b/.pi/skills/vercel-composition-patterns/rules/react19-no-forwardref.md
new file mode 100644
index 0000000..e0d8f8a
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/rules/react19-no-forwardref.md
@@ -0,0 +1,42 @@
+---
+title: React 19 API Changes
+impact: MEDIUM
+impactDescription: cleaner component definitions and context usage
+tags: react19, refs, context, hooks
+---
+
+## React 19 API Changes
+
+> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
+
+In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
+
+**Incorrect (forwardRef in React 19):**
+
+```tsx
+const ComposerInput = forwardRef((props, ref) => {
+ return
+})
+```
+
+**Correct (ref as a regular prop):**
+
+```tsx
+function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref }) {
+ return
+}
+```
+
+**Incorrect (useContext in React 19):**
+
+```tsx
+const value = useContext(MyContext)
+```
+
+**Correct (use instead of useContext):**
+
+```tsx
+const value = use(MyContext)
+```
+
+`use()` can also be called conditionally, unlike `useContext()`.
diff --git a/.pi/skills/vercel-composition-patterns/rules/state-context-interface.md b/.pi/skills/vercel-composition-patterns/rules/state-context-interface.md
new file mode 100644
index 0000000..d961bed
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/rules/state-context-interface.md
@@ -0,0 +1,191 @@
+---
+title: Define Generic Context Interfaces for Dependency Injection
+impact: HIGH
+impactDescription: enables dependency-injectable state across use-cases
+tags: composition, context, state, typescript, dependency-injection
+---
+
+## Define Generic Context Interfaces for Dependency Injection
+
+Define a **generic interface** for your component context with three parts:
+`state`, `actions`, and `meta`. This interface is a contract that any provider
+can implement—enabling the same UI components to work with completely different
+state implementations.
+
+**Core principle:** Lift state, compose internals, make state
+dependency-injectable.
+
+**Incorrect (UI coupled to specific state implementation):**
+
+```tsx
+function ComposerInput() {
+ // Tightly coupled to a specific hook
+ const { input, setInput } = useChannelComposerState()
+ return
+}
+```
+
+**Correct (generic interface enables dependency injection):**
+
+```tsx
+// Define a GENERIC interface that any provider can implement
+interface ComposerState {
+ input: string
+ attachments: Attachment[]
+ isSubmitting: boolean
+}
+
+interface ComposerActions {
+ update: (updater: (state: ComposerState) => ComposerState) => void
+ submit: () => void
+}
+
+interface ComposerMeta {
+ inputRef: React.RefObject
+}
+
+interface ComposerContextValue {
+ state: ComposerState
+ actions: ComposerActions
+ meta: ComposerMeta
+}
+
+const ComposerContext = createContext(null)
+```
+
+**UI components consume the interface, not the implementation:**
+
+```tsx
+function ComposerInput() {
+ const {
+ state,
+ actions: { update },
+ meta,
+ } = use(ComposerContext)
+
+ // This component works with ANY provider that implements the interface
+ return (
+ update((s) => ({ ...s, input: text }))}
+ />
+ )
+}
+```
+
+**Different providers implement the same interface:**
+
+```tsx
+// Provider A: Local state for ephemeral forms
+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
+ const [state, setState] = useState(initialState)
+ const inputRef = useRef(null)
+ const submit = useForwardMessage()
+
+ return (
+
+ {children}
+
+ )
+}
+
+// Provider B: Global synced state for channels
+function ChannelProvider({ channelId, children }: Props) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+ const inputRef = useRef(null)
+
+ return (
+
+ {children}
+
+ )
+}
+```
+
+**The same composed UI works with both:**
+
+```tsx
+// Works with ForwardMessageProvider (local state)
+
+
+
+
+
+
+
+// Works with ChannelProvider (global synced state)
+
+
+
+
+
+
+```
+
+**Custom UI outside the component can access state and actions:**
+
+The provider boundary is what matters—not the visual nesting. Components that
+need shared state don't have to be inside the `Composer.Frame`. They just need
+to be within the provider.
+
+```tsx
+function ForwardMessageDialog() {
+ return (
+
+
+
+ )
+}
+
+// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
+function ForwardButton() {
+ const {
+ actions: { submit },
+ } = use(ComposerContext)
+ return
+}
+
+// This preview lives OUTSIDE Composer.Frame but can read composer's state!
+function MessagePreview() {
+ const { state } = use(ComposerContext)
+ return
+}
+```
+
+The `ForwardButton` and `MessagePreview` are not visually inside the composer
+box, but they can still access its state and actions. This is the power of
+lifting state into providers.
+
+The UI is reusable bits you compose together. The state is dependency-injected
+by the provider. Swap the provider, keep the UI.
diff --git a/.pi/skills/vercel-composition-patterns/rules/state-decouple-implementation.md b/.pi/skills/vercel-composition-patterns/rules/state-decouple-implementation.md
new file mode 100644
index 0000000..71a5afa
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/rules/state-decouple-implementation.md
@@ -0,0 +1,113 @@
+---
+title: Decouple State Management from UI
+impact: MEDIUM
+impactDescription: enables swapping state implementations without changing UI
+tags: composition, state, architecture
+---
+
+## Decouple State Management from UI
+
+The provider component should be the only place that knows how state is managed.
+UI components consume the context interface—they don't know if state comes from
+useState, Zustand, or a server sync.
+
+**Incorrect (UI coupled to state implementation):**
+
+```tsx
+function ChannelComposer({ channelId }: { channelId: string }) {
+ // UI component knows about global state implementation
+ const state = useGlobalChannelState(channelId)
+ const { submit, updateInput } = useChannelSync(channelId)
+
+ return (
+
+ sync.updateInput(text)}
+ />
+ sync.submit()} />
+
+ )
+}
+```
+
+**Correct (state management isolated in provider):**
+
+```tsx
+// Provider handles all state management details
+function ChannelProvider({
+ channelId,
+ children,
+}: {
+ channelId: string
+ children: React.ReactNode
+}) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+ const inputRef = useRef(null)
+
+ return (
+
+ {children}
+
+ )
+}
+
+// UI component only knows about the context interface
+function ChannelComposer() {
+ return (
+
+
+
+
+
+
+
+ )
+}
+
+// Usage
+function Channel({ channelId }: { channelId: string }) {
+ return (
+
+
+
+ )
+}
+```
+
+**Different providers, same UI:**
+
+```tsx
+// Local state for ephemeral forms
+function ForwardMessageProvider({ children }) {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+
+ return (
+
+ {children}
+
+ )
+}
+
+// Global synced state for channels
+function ChannelProvider({ channelId, children }) {
+ const { state, update, submit } = useGlobalChannel(channelId)
+
+ return (
+
+ {children}
+
+ )
+}
+```
+
+The same `Composer.Input` component works with both providers because it only
+depends on the context interface, not the implementation.
diff --git a/.pi/skills/vercel-composition-patterns/rules/state-lift-state.md b/.pi/skills/vercel-composition-patterns/rules/state-lift-state.md
new file mode 100644
index 0000000..d7fe27b
--- /dev/null
+++ b/.pi/skills/vercel-composition-patterns/rules/state-lift-state.md
@@ -0,0 +1,125 @@
+---
+title: Lift State into Provider Components
+impact: HIGH
+impactDescription: enables state sharing outside component boundaries
+tags: composition, state, context, providers
+---
+
+## Lift State into Provider Components
+
+Move state management into dedicated provider components. This allows sibling
+components outside the main UI to access and modify state without prop drilling
+or awkward refs.
+
+**Incorrect (state trapped inside component):**
+
+```tsx
+function ForwardMessageComposer() {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+
+ return (
+
+
+
+
+ )
+}
+
+// Problem: How does this button access composer state?
+function ForwardMessageDialog() {
+ return (
+
+ )
+}
+```
+
+**Incorrect (useEffect to sync state up):**
+
+```tsx
+function ForwardMessageDialog() {
+ const [input, setInput] = useState('')
+ return (
+
+ )
+}
+
+function ForwardMessageComposer({ onInputChange }) {
+ const [state, setState] = useState(initialState)
+ useEffect(() => {
+ onInputChange(state.input) // Sync on every change 😬
+ }, [state.input])
+}
+```
+
+**Incorrect (reading state from ref on submit):**
+
+```tsx
+function ForwardMessageDialog() {
+ const stateRef = useRef(null)
+ return (
+
+ )
+}
+```
+
+**Correct (state lifted to provider):**
+
+```tsx
+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
+ const [state, setState] = useState(initialState)
+ const forwardMessage = useForwardMessage()
+ const inputRef = useRef(null)
+
+ return (
+
+ {children}
+
+ )
+}
+
+function ForwardMessageDialog() {
+ return (
+
+
+
+ )
+}
+
+function ForwardButton() {
+ const { actions } = use(Composer.Context)
+ return
+}
+```
+
+The ForwardButton lives outside the Composer.Frame but still has access to the
+submit action because it's within the provider. Even though it's a one-off
+component, it can still access the composer's state and actions from outside the
+UI itself.
+
+**Key insight:** Components that need shared state don't have to be visually
+nested inside each other—they just need to be within the same provider.
diff --git a/.pi/skills/vercel-react-best-practices/AGENTS.md b/.pi/skills/vercel-react-best-practices/AGENTS.md
new file mode 100644
index 0000000..94c3c84
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/AGENTS.md
@@ -0,0 +1,2975 @@
+# React Best Practices
+
+**Version 1.0.0**
+Vercel Engineering
+January 2026
+
+> **Note:**
+> This document is mainly for agents and LLMs to follow when maintaining,
+> generating, or refactoring React and Next.js codebases. Humans
+> may also find it useful, but guidance here is optimized for automation
+> and consistency by AI-assisted workflows.
+
+---
+
+## Abstract
+
+Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.
+
+---
+
+## Table of Contents
+
+1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**
+ - 1.1 [Defer Await Until Needed](#11-defer-await-until-needed)
+ - 1.2 [Dependency-Based Parallelization](#12-dependency-based-parallelization)
+ - 1.3 [Prevent Waterfall Chains in API Routes](#13-prevent-waterfall-chains-in-api-routes)
+ - 1.4 [Promise.all() for Independent Operations](#14-promiseall-for-independent-operations)
+ - 1.5 [Strategic Suspense Boundaries](#15-strategic-suspense-boundaries)
+2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**
+ - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports)
+ - 2.2 [Conditional Module Loading](#22-conditional-module-loading)
+ - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries)
+ - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components)
+ - 2.5 [Preload Based on User Intent](#25-preload-based-on-user-intent)
+3. [Server-Side Performance](#3-server-side-performance) — **HIGH**
+ - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes)
+ - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props)
+ - 3.3 [Cross-Request LRU Caching](#33-cross-request-lru-caching)
+ - 3.4 [Hoist Static I/O to Module Level](#34-hoist-static-io-to-module-level)
+ - 3.5 [Minimize Serialization at RSC Boundaries](#35-minimize-serialization-at-rsc-boundaries)
+ - 3.6 [Parallel Data Fetching with Component Composition](#36-parallel-data-fetching-with-component-composition)
+ - 3.7 [Per-Request Deduplication with React.cache()](#37-per-request-deduplication-with-reactcache)
+ - 3.8 [Use after() for Non-Blocking Operations](#38-use-after-for-non-blocking-operations)
+4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**
+ - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners)
+ - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance)
+ - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication)
+ - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data)
+5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM**
+ - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering)
+ - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point)
+ - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo)
+ - 5.4 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#54-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant)
+ - 5.5 [Extract to Memoized Components](#55-extract-to-memoized-components)
+ - 5.6 [Narrow Effect Dependencies](#56-narrow-effect-dependencies)
+ - 5.7 [Put Interaction Logic in Event Handlers](#57-put-interaction-logic-in-event-handlers)
+ - 5.8 [Subscribe to Derived State](#58-subscribe-to-derived-state)
+ - 5.9 [Use Functional setState Updates](#59-use-functional-setstate-updates)
+ - 5.10 [Use Lazy State Initialization](#510-use-lazy-state-initialization)
+ - 5.11 [Use Transitions for Non-Urgent Updates](#511-use-transitions-for-non-urgent-updates)
+ - 5.12 [Use useRef for Transient Values](#512-use-useref-for-transient-values)
+6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**
+ - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element)
+ - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists)
+ - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements)
+ - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision)
+ - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering)
+ - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches)
+ - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide)
+ - 6.8 [Use Explicit Conditional Rendering](#68-use-explicit-conditional-rendering)
+ - 6.9 [Use useTransition Over Manual Loading States](#69-use-usetransition-over-manual-loading-states)
+7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**
+ - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing)
+ - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups)
+ - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops)
+ - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls)
+ - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls)
+ - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations)
+ - 7.7 [Early Length Check for Array Comparisons](#77-early-length-check-for-array-comparisons)
+ - 7.8 [Early Return from Functions](#78-early-return-from-functions)
+ - 7.9 [Hoist RegExp Creation](#79-hoist-regexp-creation)
+ - 7.10 [Use Loop for Min/Max Instead of Sort](#710-use-loop-for-minmax-instead-of-sort)
+ - 7.11 [Use Set/Map for O(1) Lookups](#711-use-setmap-for-o1-lookups)
+ - 7.12 [Use toSorted() Instead of sort() for Immutability](#712-use-tosorted-instead-of-sort-for-immutability)
+8. [Advanced Patterns](#8-advanced-patterns) — **LOW**
+ - 8.1 [Initialize App Once, Not Per Mount](#81-initialize-app-once-not-per-mount)
+ - 8.2 [Store Event Handlers in Refs](#82-store-event-handlers-in-refs)
+ - 8.3 [useEffectEvent for Stable Callback Refs](#83-useeffectevent-for-stable-callback-refs)
+
+---
+
+## 1. Eliminating Waterfalls
+
+**Impact: CRITICAL**
+
+Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
+
+### 1.1 Defer Await Until Needed
+
+**Impact: HIGH (avoids blocking unused code paths)**
+
+Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
+
+**Incorrect: blocks both branches**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ const userData = await fetchUserData(userId)
+
+ if (skipProcessing) {
+ // Returns immediately but still waited for userData
+ return { skipped: true }
+ }
+
+ // Only this branch uses userData
+ return processUserData(userData)
+}
+```
+
+**Correct: only blocks when needed**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ if (skipProcessing) {
+ // Returns immediately without waiting
+ return { skipped: true }
+ }
+
+ // Fetch only when needed
+ const userData = await fetchUserData(userId)
+ return processUserData(userData)
+}
+```
+
+**Another example: early return optimization**
+
+```typescript
+// Incorrect: always fetches permissions
+async function updateResource(resourceId: string, userId: string) {
+ const permissions = await fetchPermissions(userId)
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+
+// Correct: fetches only when needed
+async function updateResource(resourceId: string, userId: string) {
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ const permissions = await fetchPermissions(userId)
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+```
+
+This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
+
+### 1.2 Dependency-Based Parallelization
+
+**Impact: CRITICAL (2-10× improvement)**
+
+For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
+
+**Incorrect: profile waits for config unnecessarily**
+
+```typescript
+const [user, config] = await Promise.all([
+ fetchUser(),
+ fetchConfig()
+])
+const profile = await fetchProfile(user.id)
+```
+
+**Correct: config and profile run in parallel**
+
+```typescript
+import { all } from 'better-all'
+
+const { user, config, profile } = await all({
+ async user() { return fetchUser() },
+ async config() { return fetchConfig() },
+ async profile() {
+ return fetchProfile((await this.$.user).id)
+ }
+})
+```
+
+**Alternative without extra dependencies:**
+
+```typescript
+const userPromise = fetchUser()
+const profilePromise = userPromise.then(user => fetchProfile(user.id))
+
+const [user, config, profile] = await Promise.all([
+ userPromise,
+ fetchConfig(),
+ profilePromise
+])
+```
+
+We can also create all the promises first, and do `Promise.all()` at the end.
+
+Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
+
+### 1.3 Prevent Waterfall Chains in API Routes
+
+**Impact: CRITICAL (2-10× improvement)**
+
+In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
+
+**Incorrect: config waits for auth, data waits for both**
+
+```typescript
+export async function GET(request: Request) {
+ const session = await auth()
+ const config = await fetchConfig()
+ const data = await fetchData(session.user.id)
+ return Response.json({ data, config })
+}
+```
+
+**Correct: auth and config start immediately**
+
+```typescript
+export async function GET(request: Request) {
+ const sessionPromise = auth()
+ const configPromise = fetchConfig()
+ const session = await sessionPromise
+ const [config, data] = await Promise.all([
+ configPromise,
+ fetchData(session.user.id)
+ ])
+ return Response.json({ data, config })
+}
+```
+
+For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
+
+### 1.4 Promise.all() for Independent Operations
+
+**Impact: CRITICAL (2-10× improvement)**
+
+When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
+
+**Incorrect: sequential execution, 3 round trips**
+
+```typescript
+const user = await fetchUser()
+const posts = await fetchPosts()
+const comments = await fetchComments()
+```
+
+**Correct: parallel execution, 1 round trip**
+
+```typescript
+const [user, posts, comments] = await Promise.all([
+ fetchUser(),
+ fetchPosts(),
+ fetchComments()
+])
+```
+
+### 1.5 Strategic Suspense Boundaries
+
+**Impact: HIGH (faster initial paint)**
+
+Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
+
+**Incorrect: wrapper blocked by data fetching**
+
+```tsx
+async function Page() {
+ const data = await fetchData() // Blocks entire page
+
+ return (
+
+
Sidebar
+
Header
+
+
+
+
Footer
+
+ )
+}
+```
+
+The entire layout waits for data even though only the middle section needs it.
+
+**Correct: wrapper shows immediately, data streams in**
+
+```tsx
+function Page() {
+ return (
+
+
Sidebar
+
Header
+
+ }>
+
+
+
+
Footer
+
+ )
+}
+
+async function DataDisplay() {
+ const data = await fetchData() // Only blocks this component
+ return
{data.content}
+}
+```
+
+Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
+
+**Alternative: share promise across components**
+
+```tsx
+function Page() {
+ // Start fetch immediately, but don't await
+ const dataPromise = fetchData()
+
+ return (
+
+}
+
+function DataSummary({ dataPromise }: { dataPromise: Promise }) {
+ const data = use(dataPromise) // Reuses the same promise
+ return
{data.summary}
+}
+```
+
+Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
+
+**When NOT to use this pattern:**
+
+- Critical data needed for layout decisions (affects positioning)
+
+- SEO-critical content above the fold
+
+- Small, fast queries where suspense overhead isn't worth it
+
+- When you want to avoid layout shift (loading → content jump)
+
+**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
+
+---
+
+## 2. Bundle Size Optimization
+
+**Impact: CRITICAL**
+
+Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
+
+### 2.1 Avoid Barrel File Imports
+
+**Impact: CRITICAL (200-800ms import cost, slow builds)**
+
+Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
+
+Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
+
+**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
+
+**Incorrect: imports entire library**
+
+```tsx
+import { Check, X, Menu } from 'lucide-react'
+// Loads 1,583 modules, takes ~2.8s extra in dev
+// Runtime cost: 200-800ms on every cold start
+
+import { Button, TextField } from '@mui/material'
+// Loads 2,225 modules, takes ~4.2s extra in dev
+```
+
+**Correct: imports only what you need**
+
+```tsx
+import Check from 'lucide-react/dist/esm/icons/check'
+import X from 'lucide-react/dist/esm/icons/x'
+import Menu from 'lucide-react/dist/esm/icons/menu'
+// Loads only 3 modules (~2KB vs ~1MB)
+
+import Button from '@mui/material/Button'
+import TextField from '@mui/material/TextField'
+// Loads only what you use
+```
+
+**Alternative: Next.js 13.5+**
+
+```js
+// next.config.js - use optimizePackageImports
+module.exports = {
+ experimental: {
+ optimizePackageImports: ['lucide-react', '@mui/material']
+ }
+}
+
+// Then you can keep the ergonomic barrel imports:
+import { Check, X, Menu } from 'lucide-react'
+// Automatically transformed to direct imports at build time
+```
+
+Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
+
+Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
+
+Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
+
+### 2.2 Conditional Module Loading
+
+**Impact: HIGH (loads large data only when needed)**
+
+Load large data or modules only when a feature is activated.
+
+**Example: lazy-load animation frames**
+
+```tsx
+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch> }) {
+ const [frames, setFrames] = useState(null)
+
+ useEffect(() => {
+ if (enabled && !frames && typeof window !== 'undefined') {
+ import('./animation-frames.js')
+ .then(mod => setFrames(mod.frames))
+ .catch(() => setEnabled(false))
+ }
+ }, [enabled, frames, setEnabled])
+
+ if (!frames) return
+ return
+}
+```
+
+The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
+
+### 2.3 Defer Non-Critical Third-Party Libraries
+
+**Impact: MEDIUM (loads after hydration)**
+
+Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
+
+**Incorrect: blocks initial bundle**
+
+```tsx
+import { Analytics } from '@vercel/analytics/react'
+
+export default function RootLayout({ children }) {
+ return (
+
+
+ {children}
+
+
+
+ )
+}
+```
+
+**Correct: loads after hydration**
+
+```tsx
+import dynamic from 'next/dynamic'
+
+const Analytics = dynamic(
+ () => import('@vercel/analytics/react').then(m => m.Analytics),
+ { ssr: false }
+)
+
+export default function RootLayout({ children }) {
+ return (
+
+
+ {children}
+
+
+
+ )
+}
+```
+
+### 2.4 Dynamic Imports for Heavy Components
+
+**Impact: CRITICAL (directly affects TTI and LCP)**
+
+Use `next/dynamic` to lazy-load large components not needed on initial render.
+
+**Incorrect: Monaco bundles with main chunk ~300KB**
+
+```tsx
+import { MonacoEditor } from './monaco-editor'
+
+function CodePanel({ code }: { code: string }) {
+ return
+}
+```
+
+**Correct: Monaco loads on demand**
+
+```tsx
+import dynamic from 'next/dynamic'
+
+const MonacoEditor = dynamic(
+ () => import('./monaco-editor').then(m => m.MonacoEditor),
+ { ssr: false }
+)
+
+function CodePanel({ code }: { code: string }) {
+ return
+}
+```
+
+### 2.5 Preload Based on User Intent
+
+**Impact: MEDIUM (reduces perceived latency)**
+
+Preload heavy bundles before they're needed to reduce perceived latency.
+
+**Example: preload on hover/focus**
+
+```tsx
+function EditorButton({ onClick }: { onClick: () => void }) {
+ const preload = () => {
+ if (typeof window !== 'undefined') {
+ void import('./monaco-editor')
+ }
+ }
+
+ return (
+
+ )
+}
+```
+
+**Example: preload when feature flag is enabled**
+
+```tsx
+function FlagsProvider({ children, flags }: Props) {
+ useEffect(() => {
+ if (flags.editorEnabled && typeof window !== 'undefined') {
+ void import('./monaco-editor').then(mod => mod.init())
+ }
+ }, [flags.editorEnabled])
+
+ return
+ {children}
+
+}
+```
+
+The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
+
+---
+
+## 3. Server-Side Performance
+
+**Impact: HIGH**
+
+Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
+
+### 3.1 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)
+
+### 3.2 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:**
+
+```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)
+```
+
+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
+
+**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.
+
+### 3.3 Cross-Request LRU Caching
+
+**Impact: HIGH (caches across requests)**
+
+`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)
+
+### 3.4 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**
+
+**Correct: loads once at module initialization**
+
+**Alternative: synchronous file reads with Node.js fs**
+
+**General Node.js example: loading config or templates**
+
+**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.
+
+### 3.5 Minimize Serialization at RSC Boundaries
+
+**Impact: HIGH (reduces data transfer size)**
+
+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}
+}
+```
+
+### 3.6 Parallel Data Fetching with Component Composition
+
+**Impact: CRITICAL (eliminates server-side waterfalls)**
+
+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 (
+
+
{header}
+
+
+ )
+}
+
+async function Sidebar() {
+ const items = await fetchSidebarItems()
+ return
+}
+```
+
+**Correct: both fetch simultaneously**
+
+```tsx
+async function Header() {
+ const data = await fetchHeader()
+ return
+}
+```
+
+Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect)
+
+### 5.2 Defer State Reads to Usage Point
+
+**Impact: MEDIUM (avoids unnecessary subscriptions)**
+
+Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
+
+**Incorrect: subscribes to all searchParams changes**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const searchParams = useSearchParams()
+
+ const handleShare = () => {
+ const ref = searchParams.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return
+}
+```
+
+**Correct: reads on demand, no subscription**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const handleShare = () => {
+ const params = new URLSearchParams(window.location.search)
+ const ref = params.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return
+}
+```
+
+### 5.3 Do not wrap a simple expression with a primitive result type in useMemo
+
+**Impact: LOW-MEDIUM (wasted computation on every render)**
+
+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
+}
+```
+
+### 5.4 Extract Default Non-primitive Parameter Value from Memoized Component to Constant
+
+**Impact: MEDIUM (restores memoization by using a constant for default value)**
+
+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
+
+```
+
+### 5.5 Extract to Memoized Components
+
+**Impact: MEDIUM (enables early returns)**
+
+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.
+
+### 5.6 Narrow Effect Dependencies
+
+**Impact: LOW (minimizes effect re-runs)**
+
+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])
+```
+
+### 5.7 Put Interaction Logic in Event Handlers
+
+**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)**
+
+If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
+
+**Incorrect: event modeled as state + effect**
+
+```tsx
+function Form() {
+ const [submitted, setSubmitted] = useState(false)
+ const theme = useContext(ThemeContext)
+
+ useEffect(() => {
+ if (submitted) {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+ }, [submitted, theme])
+
+ return
+}
+```
+
+**Correct: do it in the handler**
+
+```tsx
+function Form() {
+ const theme = useContext(ThemeContext)
+
+ function handleSubmit() {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+
+ return
+}
+```
+
+Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
+
+### 5.8 Subscribe to Derived State
+
+**Impact: MEDIUM (reduces re-render frequency)**
+
+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
+}
+```
+
+### 5.9 Use Functional setState Updates
+
+**Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)**
+
+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.
+
+### 5.10 Use Lazy State Initialization
+
+**Impact: MEDIUM (wasted computation on every render)**
+
+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.
+
+### 5.11 Use Transitions for Non-Urgent Updates
+
+**Impact: MEDIUM (maintains UI responsiveness)**
+
+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)
+ }, [])
+}
+```
+
+### 5.12 Use useRef for Transient Values
+
+**Impact: MEDIUM (avoids unnecessary re-renders on frequent updates)**
+
+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 (
+
+ )
+}
+```
+
+---
+
+## 6. Rendering Performance
+
+**Impact: MEDIUM**
+
+Optimizing the rendering process reduces the work the browser needs to do.
+
+### 6.1 Animate SVG Wrapper Instead of SVG Element
+
+**Impact: LOW (enables hardware acceleration)**
+
+Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `
+ )
+}
+```
+
+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.
+
+### 6.4 Optimize SVG Precision
+
+**Impact: LOW (reduces file size)**
+
+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
+```
+
+### 6.5 Prevent Hydration Mismatch Without Flickering
+
+**Impact: MEDIUM (avoids visual flicker and hydration errors)**
+
+When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
+
+**Incorrect: breaks SSR**
+
+```tsx
+function ThemeWrapper({ children }: { children: ReactNode }) {
+ // localStorage is not available on server - throws error
+ const theme = localStorage.getItem('theme') || 'light'
+
+ return (
+
+ )
+}
+```
+
+Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
+
+**Correct: no flicker, 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.
+
+### 6.6 Suppress Expected Hydration Mismatches
+
+**Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)**
+
+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()}
+
+ )
+}
+```
+
+### 6.7 Use Activity Component for Show/Hide
+
+**Impact: MEDIUM (preserves state/DOM)**
+
+Use React's `` to preserve state/DOM for expensive components that frequently toggle visibility.
+
+**Usage:**
+
+```tsx
+import { Activity } from 'react'
+
+function Dropdown({ isOpen }: Props) {
+ return (
+
+
+
+ )
+}
+```
+
+Avoids expensive re-renders and state loss.
+
+### 6.8 Use Explicit Conditional Rendering
+
+**Impact: LOW (prevents rendering 0 or NaN)**
+
+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
+```
+
+### 6.9 Use useTransition Over Manual Loading States
+
+**Impact: LOW (reduces re-renders and improves code clarity)**
+
+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: [https://react.dev/reference/react/useTransition](https://react.dev/reference/react/useTransition)
+
+---
+
+## 7. JavaScript Performance
+
+**Impact: LOW-MEDIUM**
+
+Micro-optimizations for hot paths can add up to meaningful improvements.
+
+### 7.1 Avoid Layout Thrashing
+
+**Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)**
+
+Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
+
+**This is OK: browser batches style changes**
+
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ // Each line invalidates style, but browser batches the recalculation
+ element.style.width = '100px'
+ element.style.height = '200px'
+ element.style.backgroundColor = 'blue'
+ element.style.border = '1px solid black'
+}
+```
+
+**Incorrect: interleaved reads and writes force reflows**
+
+```typescript
+function layoutThrashing(element: HTMLElement) {
+ element.style.width = '100px'
+ const width = element.offsetWidth // Forces reflow
+ element.style.height = '200px'
+ const height = element.offsetHeight // Forces another reflow
+}
+```
+
+**Correct: batch writes, then read once**
+
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ // Batch all writes together
+ element.style.width = '100px'
+ element.style.height = '200px'
+ element.style.backgroundColor = 'blue'
+ element.style.border = '1px solid black'
+
+ // Read after all writes are done (single reflow)
+ const { width, height } = element.getBoundingClientRect()
+}
+```
+
+**Correct: batch reads, then writes**
+
+```typescript
+function updateElementStyles(element: HTMLElement) {
+ element.classList.add('highlighted-box')
+
+ const { width, height } = element.getBoundingClientRect()
+}
+```
+
+**Better: use CSS classes**
+
+**React example:**
+
+```tsx
+// Incorrect: interleaving style changes with layout queries
+function Box({ isHighlighted }: { isHighlighted: boolean }) {
+ const ref = useRef(null)
+
+ useEffect(() => {
+ if (ref.current && isHighlighted) {
+ ref.current.style.width = '100px'
+ const width = ref.current.offsetWidth // Forces layout
+ ref.current.style.height = '200px'
+ }
+ }, [isHighlighted])
+
+ return
+}
+```
+
+**Why this matters in React:**
+
+1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
+
+2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
+
+**Browser support: fallback for older browsers**
+
+```typescript
+// Fallback for older browsers
+const sorted = [...items].sort((a, b) => a.value - b.value)
+```
+
+`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
+
+**Other immutable array methods:**
+
+- `.toSorted()` - immutable sort
+
+- `.toReversed()` - immutable reverse
+
+- `.toSpliced()` - immutable splice
+
+- `.with()` - immutable element replacement
+
+---
+
+## 8. Advanced Patterns
+
+**Impact: LOW**
+
+Advanced patterns for specific cases that require careful implementation.
+
+### 8.1 Initialize App Once, Not Per Mount
+
+**Impact: LOW-MEDIUM (avoids duplicate init in development)**
+
+Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
+
+**Incorrect: runs twice in dev, re-runs on remount**
+
+```tsx
+function Comp() {
+ useEffect(() => {
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+**Correct: once per app load**
+
+```tsx
+let didInit = false
+
+function Comp() {
+ useEffect(() => {
+ if (didInit) return
+ didInit = true
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+Reference: [https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
+
+### 8.2 Store Event Handlers in Refs
+
+**Impact: LOW (stable subscriptions)**
+
+Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
+
+**Incorrect: re-subscribes on every render**
+
+```tsx
+function useWindowEvent(event: string, handler: (e) => void) {
+ useEffect(() => {
+ window.addEventListener(event, handler)
+ return () => window.removeEventListener(event, handler)
+ }, [event, handler])
+}
+```
+
+**Correct: stable subscription**
+
+```tsx
+import { useEffectEvent } from 'react'
+
+function useWindowEvent(event: string, handler: (e) => void) {
+ const onEvent = useEffectEvent(handler)
+
+ useEffect(() => {
+ window.addEventListener(event, onEvent)
+ return () => window.removeEventListener(event, onEvent)
+ }, [event])
+}
+```
+
+**Alternative: use `useEffectEvent` if you're on latest React:**
+
+`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
+
+### 8.3 useEffectEvent for Stable Callback Refs
+
+**Impact: LOW (prevents effect re-runs)**
+
+Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
+
+**Incorrect: effect re-runs on every callback change**
+
+```tsx
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearch(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query, onSearch])
+}
+```
+
+**Correct: using React's useEffectEvent**
+
+```tsx
+import { useEffectEvent } from 'react';
+
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+ const onSearchEvent = useEffectEvent(onSearch)
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearchEvent(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query])
+}
+```
+
+---
+
+## References
+
+1. [https://react.dev](https://react.dev)
+2. [https://nextjs.org](https://nextjs.org)
+3. [https://swr.vercel.app](https://swr.vercel.app)
+4. [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
+5. [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
+6. [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
+7. [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
diff --git a/.pi/skills/vercel-react-best-practices/README.md b/.pi/skills/vercel-react-best-practices/README.md
new file mode 100644
index 0000000..f283e1c
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/README.md
@@ -0,0 +1,123 @@
+# React Best Practices
+
+A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
+
+## Structure
+
+- `rules/` - Individual rule files (one per rule)
+ - `_sections.md` - Section metadata (titles, impacts, descriptions)
+ - `_template.md` - Template for creating new rules
+ - `area-description.md` - Individual rule files
+- `src/` - Build scripts and utilities
+- `metadata.json` - Document metadata (version, organization, abstract)
+- __`AGENTS.md`__ - Compiled output (generated)
+- __`test-cases.json`__ - Test cases for LLM evaluation (generated)
+
+## Getting Started
+
+1. Install dependencies:
+ ```bash
+ pnpm install
+ ```
+
+2. Build AGENTS.md from rules:
+ ```bash
+ pnpm build
+ ```
+
+3. Validate rule files:
+ ```bash
+ pnpm validate
+ ```
+
+4. Extract test cases:
+ ```bash
+ pnpm extract-tests
+ ```
+
+## Creating a New Rule
+
+1. Copy `rules/_template.md` to `rules/area-description.md`
+2. Choose the appropriate area prefix:
+ - `async-` for Eliminating Waterfalls (Section 1)
+ - `bundle-` for Bundle Size Optimization (Section 2)
+ - `server-` for Server-Side Performance (Section 3)
+ - `client-` for Client-Side Data Fetching (Section 4)
+ - `rerender-` for Re-render Optimization (Section 5)
+ - `rendering-` for Rendering Performance (Section 6)
+ - `js-` for JavaScript Performance (Section 7)
+ - `advanced-` for Advanced Patterns (Section 8)
+3. Fill in the frontmatter and content
+4. Ensure you have clear examples with explanations
+5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
+
+## Rule File Structure
+
+Each rule file should follow this structure:
+
+```markdown
+---
+title: Rule Title Here
+impact: MEDIUM
+impactDescription: Optional description
+tags: tag1, tag2, tag3
+---
+
+## Rule Title Here
+
+Brief explanation of the rule and why it matters.
+
+**Incorrect (description of what's wrong):**
+
+```typescript
+// Bad code example
+```
+
+**Correct (description of what's right):**
+
+```typescript
+// Good code example
+```
+
+Optional explanatory text after examples.
+
+Reference: [Link](https://example.com)
+
+## File Naming Convention
+
+- Files starting with `_` are special (excluded from build)
+- Rule files: `area-description.md` (e.g., `async-parallel.md`)
+- Section is automatically inferred from filename prefix
+- Rules are sorted alphabetically by title within each section
+- IDs (e.g., 1.1, 1.2) are auto-generated during build
+
+## Impact Levels
+
+- `CRITICAL` - Highest priority, major performance gains
+- `HIGH` - Significant performance improvements
+- `MEDIUM-HIGH` - Moderate-high gains
+- `MEDIUM` - Moderate performance improvements
+- `LOW-MEDIUM` - Low-medium gains
+- `LOW` - Incremental improvements
+
+## Scripts
+
+- `pnpm build` - Compile rules into AGENTS.md
+- `pnpm validate` - Validate all rule files
+- `pnpm extract-tests` - Extract test cases for LLM evaluation
+- `pnpm dev` - Build and validate
+
+## Contributing
+
+When adding or modifying rules:
+
+1. Use the correct filename prefix for your section
+2. Follow the `_template.md` structure
+3. Include clear bad/good examples with explanations
+4. Add appropriate tags
+5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
+6. Rules are automatically sorted by title - no need to manage numbers!
+
+## Acknowledgments
+
+Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
diff --git a/.pi/skills/vercel-react-best-practices/SKILL.md b/.pi/skills/vercel-react-best-practices/SKILL.md
new file mode 100644
index 0000000..aa1be95
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/SKILL.md
@@ -0,0 +1,153 @@
+---
+name: vercel-react-best-practices
+description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
+license: MIT
+metadata:
+ author: vercel
+ version: "1.0.0"
+---
+
+
+
+# Vercel React Best Practices
+
+Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 58 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
+
+
+
+
+
+## When to Apply
+
+Reference these guidelines when:
+- Writing new React components or Next.js pages
+- Implementing data fetching (client or server-side)
+- Reviewing code for performance issues
+- Refactoring existing React/Next.js code
+- Optimizing bundle size or load times
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
+| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
+| 3 | Server-Side Performance | HIGH | `server-` |
+| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
+| 5 | Re-render Optimization | MEDIUM | `rerender-` |
+| 6 | Rendering Performance | MEDIUM | `rendering-` |
+| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
+| 8 | Advanced Patterns | LOW | `advanced-` |
+
+
+
+
+
+## Quick Reference
+
+### 1. Eliminating Waterfalls (CRITICAL)
+
+- `async-defer-await` — MUST move await into branches where actually used
+- `async-parallel` — MUST use Promise.all() for independent operations
+- `async-dependencies` — SHOULD use better-all for partial dependencies
+- `async-api-routes` — MUST start promises early, await late in API routes
+- `async-suspense-boundaries` — SHOULD use Suspense to stream content
+
+### 2. Bundle Size Optimization (CRITICAL)
+
+- `bundle-barrel-imports` — MUST import directly, avoid barrel files
+- `bundle-dynamic-imports` — SHOULD use next/dynamic for heavy components
+- `bundle-defer-third-party` — SHOULD load analytics/logging after hydration
+- `bundle-conditional` — SHOULD load modules only when feature is activated
+- `bundle-preload` — MAY preload on hover/focus for perceived speed
+
+### 3. Server-Side Performance (HIGH)
+
+- `server-auth-actions` — MUST authenticate server actions like API routes
+- `server-cache-react` — SHOULD use React.cache() for per-request deduplication
+- `server-cache-lru` — MAY use LRU cache for cross-request caching
+- `server-dedup-props` — SHOULD avoid duplicate serialization in RSC props
+- `server-hoist-static-io` — SHOULD hoist static I/O (fonts, logos) to module level
+- `server-serialization` — SHOULD minimize data passed to client components
+- `server-parallel-fetching` — SHOULD restructure components to parallelize fetches
+- `server-after-nonblocking` — MAY use after() for non-blocking operations
+
+### 4. Client-Side Data Fetching (MEDIUM-HIGH)
+
+- `client-swr-dedup` — SHOULD use SWR for automatic request deduplication
+- `client-event-listeners` — SHOULD deduplicate global event listeners
+- `client-passive-event-listeners` — SHOULD use passive listeners for scroll
+- `client-localstorage-schema` — SHOULD version and minimize localStorage data
+
+### 5. Re-render Optimization (MEDIUM)
+
+- `rerender-defer-reads` — SHOULD NOT subscribe to state only used in callbacks
+- `rerender-memo` — SHOULD extract expensive work into memoized components
+- `rerender-memo-with-default-value` — SHOULD hoist default non-primitive props
+- `rerender-dependencies` — SHOULD use primitive dependencies in effects
+- `rerender-derived-state` — SHOULD subscribe to derived booleans, not raw values
+- `rerender-derived-state-no-effect` — MUST derive state during render, not effects
+- `rerender-functional-setstate` — SHOULD use functional setState for stable callbacks
+- `rerender-lazy-state-init` — SHOULD pass function to useState for expensive values
+- `rerender-simple-expression-in-memo` — SHOULD NOT use memo for simple primitives
+- `rerender-move-effect-to-event` — SHOULD put interaction logic in event handlers
+- `rerender-transitions` — MAY use startTransition for non-urgent updates
+- `rerender-use-ref-transient-values` — SHOULD use refs for transient frequent values
+
+### 6. Rendering Performance (MEDIUM)
+
+- `rendering-animate-svg-wrapper` — SHOULD animate div wrapper, not SVG element
+- `rendering-content-visibility` — MAY use content-visibility for long lists
+- `rendering-hoist-jsx` — SHOULD extract static JSX outside components
+- `rendering-svg-precision` — SHOULD reduce SVG coordinate precision
+- `rendering-hydration-no-flicker` — SHOULD use inline script for client-only data
+- `rendering-hydration-suppress-warning` — MAY suppress expected mismatches
+- `rendering-activity` — MAY use Activity component for show/hide
+- `rendering-conditional-render` — MUST use ternary, not && for conditionals
+- `rendering-usetransition-loading` — SHOULD prefer useTransition for loading state
+
+### 7. JavaScript Performance (LOW-MEDIUM)
+
+- `js-batch-dom-css` — SHOULD group CSS changes via classes or cssText
+- `js-index-maps` — SHOULD build Map for repeated lookups
+- `js-cache-property-access` — SHOULD cache object properties in loops
+- `js-cache-function-results` — MAY cache function results in module-level Map
+- `js-cache-storage` — SHOULD cache localStorage/sessionStorage reads
+- `js-combine-iterations` — SHOULD combine multiple filter/map into one loop
+- `js-length-check-first` — SHOULD check array length before expensive comparison
+- `js-early-exit` — SHOULD return early from functions
+- `js-hoist-regexp` — SHOULD hoist RegExp creation outside loops
+- `js-min-max-loop` — MAY use loop for min/max instead of sort
+- `js-set-map-lookups` — SHOULD use Set/Map for O(1) lookups
+- `js-tosorted-immutable` — SHOULD use toSorted() for immutability
+
+### 8. Advanced Patterns (LOW)
+
+- `advanced-event-handler-refs` — MAY store event handlers in refs
+- `advanced-init-once` — SHOULD initialize app once per app load
+- `advanced-use-latest` — MAY use useLatest for stable callback refs
+
+
+
+
+
+## How to Use
+
+Read individual rule files for detailed explanations and code examples:
+
+```
+rules/async-parallel.md
+rules/bundle-barrel-imports.md
+```
+
+Each rule file contains:
+- Brief explanation of why it matters
+- Incorrect code example with explanation
+- Correct code example with explanation
+- Additional context and references
+
+## Full Compiled Document
+
+For the complete guide with all rules expanded: `AGENTS.md`
+
+
diff --git a/.pi/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md b/.pi/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md
new file mode 100644
index 0000000..97e7ade
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md
@@ -0,0 +1,55 @@
+---
+title: Store Event Handlers in Refs
+impact: LOW
+impactDescription: stable subscriptions
+tags: advanced, hooks, refs, event-handlers, optimization
+---
+
+## Store Event Handlers in Refs
+
+Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
+
+**Incorrect (re-subscribes on every render):**
+
+```tsx
+function useWindowEvent(event: string, handler: (e) => void) {
+ useEffect(() => {
+ window.addEventListener(event, handler)
+ return () => window.removeEventListener(event, handler)
+ }, [event, handler])
+}
+```
+
+**Correct (stable subscription):**
+
+```tsx
+function useWindowEvent(event: string, handler: (e) => void) {
+ const handlerRef = useRef(handler)
+ useEffect(() => {
+ handlerRef.current = handler
+ }, [handler])
+
+ useEffect(() => {
+ const listener = (e) => handlerRef.current(e)
+ window.addEventListener(event, listener)
+ return () => window.removeEventListener(event, listener)
+ }, [event])
+}
+```
+
+**Alternative: use `useEffectEvent` if you're on latest React:**
+
+```tsx
+import { useEffectEvent } from 'react'
+
+function useWindowEvent(event: string, handler: (e) => void) {
+ const onEvent = useEffectEvent(handler)
+
+ useEffect(() => {
+ window.addEventListener(event, onEvent)
+ return () => window.removeEventListener(event, onEvent)
+ }, [event])
+}
+```
+
+`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
diff --git a/.pi/skills/vercel-react-best-practices/rules/advanced-init-once.md b/.pi/skills/vercel-react-best-practices/rules/advanced-init-once.md
new file mode 100644
index 0000000..73ee38e
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/advanced-init-once.md
@@ -0,0 +1,42 @@
+---
+title: Initialize App Once, Not Per Mount
+impact: LOW-MEDIUM
+impactDescription: avoids duplicate init in development
+tags: initialization, useEffect, app-startup, side-effects
+---
+
+## Initialize App Once, Not Per Mount
+
+Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
+
+**Incorrect (runs twice in dev, re-runs on remount):**
+
+```tsx
+function Comp() {
+ useEffect(() => {
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+**Correct (once per app load):**
+
+```tsx
+let didInit = false
+
+function Comp() {
+ useEffect(() => {
+ if (didInit) return
+ didInit = true
+ loadFromStorage()
+ checkAuthToken()
+ }, [])
+
+ // ...
+}
+```
+
+Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
diff --git a/.pi/skills/vercel-react-best-practices/rules/advanced-use-latest.md b/.pi/skills/vercel-react-best-practices/rules/advanced-use-latest.md
new file mode 100644
index 0000000..9c7cb50
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/advanced-use-latest.md
@@ -0,0 +1,39 @@
+---
+title: useEffectEvent for Stable Callback Refs
+impact: LOW
+impactDescription: prevents effect re-runs
+tags: advanced, hooks, useEffectEvent, refs, optimization
+---
+
+## useEffectEvent for Stable Callback Refs
+
+Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
+
+**Incorrect (effect re-runs on every callback change):**
+
+```tsx
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearch(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query, onSearch])
+}
+```
+
+**Correct (using React's useEffectEvent):**
+
+```tsx
+import { useEffectEvent } from 'react';
+
+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
+ const [query, setQuery] = useState('')
+ const onSearchEvent = useEffectEvent(onSearch)
+
+ useEffect(() => {
+ const timeout = setTimeout(() => onSearchEvent(query), 300)
+ return () => clearTimeout(timeout)
+ }, [query])
+}
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/async-api-routes.md b/.pi/skills/vercel-react-best-practices/rules/async-api-routes.md
new file mode 100644
index 0000000..6feda1e
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/async-api-routes.md
@@ -0,0 +1,38 @@
+---
+title: Prevent Waterfall Chains in API Routes
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: api-routes, server-actions, waterfalls, parallelization
+---
+
+## Prevent Waterfall Chains in API Routes
+
+In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
+
+**Incorrect (config waits for auth, data waits for both):**
+
+```typescript
+export async function GET(request: Request) {
+ const session = await auth()
+ const config = await fetchConfig()
+ const data = await fetchData(session.user.id)
+ return Response.json({ data, config })
+}
+```
+
+**Correct (auth and config start immediately):**
+
+```typescript
+export async function GET(request: Request) {
+ const sessionPromise = auth()
+ const configPromise = fetchConfig()
+ const session = await sessionPromise
+ const [config, data] = await Promise.all([
+ configPromise,
+ fetchData(session.user.id)
+ ])
+ return Response.json({ data, config })
+}
+```
+
+For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
diff --git a/.pi/skills/vercel-react-best-practices/rules/async-defer-await.md b/.pi/skills/vercel-react-best-practices/rules/async-defer-await.md
new file mode 100644
index 0000000..ea7082a
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/async-defer-await.md
@@ -0,0 +1,80 @@
+---
+title: Defer Await Until Needed
+impact: HIGH
+impactDescription: avoids blocking unused code paths
+tags: async, await, conditional, optimization
+---
+
+## Defer Await Until Needed
+
+Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
+
+**Incorrect (blocks both branches):**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ const userData = await fetchUserData(userId)
+
+ if (skipProcessing) {
+ // Returns immediately but still waited for userData
+ return { skipped: true }
+ }
+
+ // Only this branch uses userData
+ return processUserData(userData)
+}
+```
+
+**Correct (only blocks when needed):**
+
+```typescript
+async function handleRequest(userId: string, skipProcessing: boolean) {
+ if (skipProcessing) {
+ // Returns immediately without waiting
+ return { skipped: true }
+ }
+
+ // Fetch only when needed
+ const userData = await fetchUserData(userId)
+ return processUserData(userData)
+}
+```
+
+**Another example (early return optimization):**
+
+```typescript
+// Incorrect: always fetches permissions
+async function updateResource(resourceId: string, userId: string) {
+ const permissions = await fetchPermissions(userId)
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+
+// Correct: fetches only when needed
+async function updateResource(resourceId: string, userId: string) {
+ const resource = await getResource(resourceId)
+
+ if (!resource) {
+ return { error: 'Not found' }
+ }
+
+ const permissions = await fetchPermissions(userId)
+
+ if (!permissions.canEdit) {
+ return { error: 'Forbidden' }
+ }
+
+ return await updateResourceData(resource, permissions)
+}
+```
+
+This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
diff --git a/.pi/skills/vercel-react-best-practices/rules/async-dependencies.md b/.pi/skills/vercel-react-best-practices/rules/async-dependencies.md
new file mode 100644
index 0000000..0484eba
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/async-dependencies.md
@@ -0,0 +1,51 @@
+---
+title: Dependency-Based Parallelization
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: async, parallelization, dependencies, better-all
+---
+
+## Dependency-Based Parallelization
+
+For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
+
+**Incorrect (profile waits for config unnecessarily):**
+
+```typescript
+const [user, config] = await Promise.all([
+ fetchUser(),
+ fetchConfig()
+])
+const profile = await fetchProfile(user.id)
+```
+
+**Correct (config and profile run in parallel):**
+
+```typescript
+import { all } from 'better-all'
+
+const { user, config, profile } = await all({
+ async user() { return fetchUser() },
+ async config() { return fetchConfig() },
+ async profile() {
+ return fetchProfile((await this.$.user).id)
+ }
+})
+```
+
+**Alternative without extra dependencies:**
+
+We can also create all the promises first, and do `Promise.all()` at the end.
+
+```typescript
+const userPromise = fetchUser()
+const profilePromise = userPromise.then(user => fetchProfile(user.id))
+
+const [user, config, profile] = await Promise.all([
+ userPromise,
+ fetchConfig(),
+ profilePromise
+])
+```
+
+Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
diff --git a/.pi/skills/vercel-react-best-practices/rules/async-parallel.md b/.pi/skills/vercel-react-best-practices/rules/async-parallel.md
new file mode 100644
index 0000000..64133f6
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/async-parallel.md
@@ -0,0 +1,28 @@
+---
+title: Promise.all() for Independent Operations
+impact: CRITICAL
+impactDescription: 2-10× improvement
+tags: async, parallelization, promises, waterfalls
+---
+
+## Promise.all() for Independent Operations
+
+When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
+
+**Incorrect (sequential execution, 3 round trips):**
+
+```typescript
+const user = await fetchUser()
+const posts = await fetchPosts()
+const comments = await fetchComments()
+```
+
+**Correct (parallel execution, 1 round trip):**
+
+```typescript
+const [user, posts, comments] = await Promise.all([
+ fetchUser(),
+ fetchPosts(),
+ fetchComments()
+])
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.pi/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md
new file mode 100644
index 0000000..1fbc05b
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md
@@ -0,0 +1,99 @@
+---
+title: Strategic Suspense Boundaries
+impact: HIGH
+impactDescription: faster initial paint
+tags: async, suspense, streaming, layout-shift
+---
+
+## Strategic Suspense Boundaries
+
+Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
+
+**Incorrect (wrapper blocked by data fetching):**
+
+```tsx
+async function Page() {
+ const data = await fetchData() // Blocks entire page
+
+ return (
+
+
Sidebar
+
Header
+
+
+
+
Footer
+
+ )
+}
+```
+
+The entire layout waits for data even though only the middle section needs it.
+
+**Correct (wrapper shows immediately, data streams in):**
+
+```tsx
+function Page() {
+ return (
+
+
Sidebar
+
Header
+
+ }>
+
+
+
+
Footer
+
+ )
+}
+
+async function DataDisplay() {
+ const data = await fetchData() // Only blocks this component
+ return
{data.content}
+}
+```
+
+Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
+
+**Alternative (share promise across components):**
+
+```tsx
+function Page() {
+ // Start fetch immediately, but don't await
+ const dataPromise = fetchData()
+
+ return (
+
+ )
+}
+```
+
+Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
+
+See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
diff --git a/.pi/skills/vercel-react-best-practices/rules/js-cache-function-results.md b/.pi/skills/vercel-react-best-practices/rules/js-cache-function-results.md
new file mode 100644
index 0000000..180f8ac
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/js-cache-function-results.md
@@ -0,0 +1,80 @@
+---
+title: Cache Repeated Function Calls
+impact: MEDIUM
+impactDescription: avoid redundant computation
+tags: javascript, cache, memoization, performance
+---
+
+## Cache Repeated Function Calls
+
+Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
+
+**Incorrect (redundant computation):**
+
+```typescript
+function ProjectList({ projects }: { projects: Project[] }) {
+ return (
+
+ {projects.map(project => {
+ // slugify() called 100+ times for same project names
+ const slug = slugify(project.name)
+
+ return
+ })}
+
+ )
+}
+```
+
+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/.pi/skills/vercel-react-best-practices/rules/rendering-conditional-render.md b/.pi/skills/vercel-react-best-practices/rules/rendering-conditional-render.md
new file mode 100644
index 0000000..7e866f5
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rendering-conditional-render.md
@@ -0,0 +1,40 @@
+---
+title: Use Explicit Conditional Rendering
+impact: LOW
+impactDescription: prevents rendering 0 or NaN
+tags: rendering, conditional, jsx, falsy-values
+---
+
+## Use Explicit Conditional Rendering
+
+Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
+
+**Incorrect (renders "0" when count is 0):**
+
+```tsx
+function Badge({ count }: { count: number }) {
+ return (
+
+ {count && {count}}
+
+ )
+}
+
+// When count = 0, renders:
0
+// When count = 5, renders:
5
+```
+
+**Correct (renders nothing when count is 0):**
+
+```tsx
+function Badge({ count }: { count: number }) {
+ return (
+
+ {count > 0 ? {count} : null}
+
+ )
+}
+
+// When count = 0, renders:
+// When count = 5, renders:
+ )
+}
+```
+
+This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
diff --git a/.pi/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md b/.pi/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md
new file mode 100644
index 0000000..5cf0e79
--- /dev/null
+++ b/.pi/skills/vercel-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 (
+
+ )
+}
+```
+
+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/.pi/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md b/.pi/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md
new file mode 100644
index 0000000..24ba251
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md
@@ -0,0 +1,30 @@
+---
+title: Suppress Expected Hydration Mismatches
+impact: LOW-MEDIUM
+impactDescription: avoids noisy hydration warnings for known differences
+tags: rendering, hydration, ssr, nextjs
+---
+
+## Suppress Expected Hydration Mismatches
+
+In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
+
+**Incorrect (known mismatch warnings):**
+
+```tsx
+function Timestamp() {
+ return {new Date().toLocaleString()}
+}
+```
+
+**Correct (suppress expected mismatch only):**
+
+```tsx
+function Timestamp() {
+ return (
+
+ {new Date().toLocaleString()}
+
+ )
+}
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/rendering-svg-precision.md b/.pi/skills/vercel-react-best-practices/rules/rendering-svg-precision.md
new file mode 100644
index 0000000..6d77128
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rendering-svg-precision.md
@@ -0,0 +1,28 @@
+---
+title: Optimize SVG Precision
+impact: LOW
+impactDescription: reduces file size
+tags: rendering, svg, optimization, svgo
+---
+
+## Optimize SVG Precision
+
+Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
+
+**Incorrect (excessive precision):**
+
+```svg
+
+```
+
+**Correct (1 decimal place):**
+
+```svg
+
+```
+
+**Automate with SVGO:**
+
+```bash
+npx svgo --precision=1 --multipass icon.svg
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md b/.pi/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md
new file mode 100644
index 0000000..0c1b0b9
--- /dev/null
+++ b/.pi/skills/vercel-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/.pi/skills/vercel-react-best-practices/rules/rerender-defer-reads.md b/.pi/skills/vercel-react-best-practices/rules/rerender-defer-reads.md
new file mode 100644
index 0000000..e867c95
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-defer-reads.md
@@ -0,0 +1,39 @@
+---
+title: Defer State Reads to Usage Point
+impact: MEDIUM
+impactDescription: avoids unnecessary subscriptions
+tags: rerender, searchParams, localStorage, optimization
+---
+
+## Defer State Reads to Usage Point
+
+Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
+
+**Incorrect (subscribes to all searchParams changes):**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const searchParams = useSearchParams()
+
+ const handleShare = () => {
+ const ref = searchParams.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return
+}
+```
+
+**Correct (reads on demand, no subscription):**
+
+```tsx
+function ShareButton({ chatId }: { chatId: string }) {
+ const handleShare = () => {
+ const params = new URLSearchParams(window.location.search)
+ const ref = params.get('ref')
+ shareChat(chatId, { ref })
+ }
+
+ return
+}
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-dependencies.md b/.pi/skills/vercel-react-best-practices/rules/rerender-dependencies.md
new file mode 100644
index 0000000..47a4d92
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-dependencies.md
@@ -0,0 +1,45 @@
+---
+title: Narrow Effect Dependencies
+impact: LOW
+impactDescription: minimizes effect re-runs
+tags: rerender, useEffect, dependencies, optimization
+---
+
+## Narrow Effect Dependencies
+
+Specify primitive dependencies instead of objects to minimize effect re-runs.
+
+**Incorrect (re-runs on any user field change):**
+
+```tsx
+useEffect(() => {
+ console.log(user.id)
+}, [user])
+```
+
+**Correct (re-runs only when id changes):**
+
+```tsx
+useEffect(() => {
+ console.log(user.id)
+}, [user.id])
+```
+
+**For derived state, compute outside effect:**
+
+```tsx
+// Incorrect: runs on width=767, 766, 765...
+useEffect(() => {
+ if (width < 768) {
+ enableMobileMode()
+ }
+}, [width])
+
+// Correct: runs only on boolean transition
+const isMobile = width < 768
+useEffect(() => {
+ if (isMobile) {
+ enableMobileMode()
+ }
+}, [isMobile])
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md b/.pi/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md
new file mode 100644
index 0000000..3d9fe40
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md
@@ -0,0 +1,40 @@
+---
+title: Calculate Derived State During Rendering
+impact: MEDIUM
+impactDescription: avoids redundant renders and state drift
+tags: rerender, derived-state, useEffect, state
+---
+
+## Calculate Derived State During Rendering
+
+If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
+
+**Incorrect (redundant state and effect):**
+
+```tsx
+function Form() {
+ const [firstName, setFirstName] = useState('First')
+ const [lastName, setLastName] = useState('Last')
+ const [fullName, setFullName] = useState('')
+
+ useEffect(() => {
+ setFullName(firstName + ' ' + lastName)
+ }, [firstName, lastName])
+
+ return
+}
+```
+
+References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-derived-state.md b/.pi/skills/vercel-react-best-practices/rules/rerender-derived-state.md
new file mode 100644
index 0000000..e5c899f
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-derived-state.md
@@ -0,0 +1,29 @@
+---
+title: Subscribe to Derived State
+impact: MEDIUM
+impactDescription: reduces re-render frequency
+tags: rerender, derived-state, media-query, optimization
+---
+
+## Subscribe to Derived State
+
+Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
+
+**Incorrect (re-renders on every pixel change):**
+
+```tsx
+function Sidebar() {
+ const width = useWindowWidth() // updates continuously
+ const isMobile = width < 768
+ return
+}
+```
+
+**Correct (re-renders only when boolean changes):**
+
+```tsx
+function Sidebar() {
+ const isMobile = useMediaQuery('(max-width: 767px)')
+ return
+}
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md b/.pi/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md
new file mode 100644
index 0000000..b004ef4
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md
@@ -0,0 +1,74 @@
+---
+title: Use Functional setState Updates
+impact: MEDIUM
+impactDescription: prevents stale closures and unnecessary callback recreations
+tags: react, hooks, useState, useCallback, callbacks, closures
+---
+
+## Use Functional setState Updates
+
+When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
+
+**Incorrect (requires state as dependency):**
+
+```tsx
+function TodoList() {
+ const [items, setItems] = useState(initialItems)
+
+ // Callback must depend on items, recreated on every items change
+ const addItems = useCallback((newItems: Item[]) => {
+ setItems([...items, ...newItems])
+ }, [items]) // ❌ items dependency causes recreations
+
+ // Risk of stale closure if dependency is forgotten
+ const removeItem = useCallback((id: string) => {
+ setItems(items.filter(item => item.id !== id))
+ }, []) // ❌ Missing items dependency - will use stale items!
+
+ return
+}
+```
+
+The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
+
+**Correct (stable callbacks, no stale closures):**
+
+```tsx
+function TodoList() {
+ const [items, setItems] = useState(initialItems)
+
+ // Stable callback, never recreated
+ const addItems = useCallback((newItems: Item[]) => {
+ setItems(curr => [...curr, ...newItems])
+ }, []) // ✅ No dependencies needed
+
+ // Always uses latest state, no stale closure risk
+ const removeItem = useCallback((id: string) => {
+ setItems(curr => curr.filter(item => item.id !== id))
+ }, []) // ✅ Safe and stable
+
+ return
+}
+```
+
+**Benefits:**
+
+1. **Stable callback references** - Callbacks don't need to be recreated when state changes
+2. **No stale closures** - Always operates on the latest state value
+3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
+4. **Prevents bugs** - Eliminates the most common source of React closure bugs
+
+**When to use functional updates:**
+
+- Any setState that depends on the current state value
+- Inside useCallback/useMemo when state is needed
+- Event handlers that reference state
+- Async operations that update state
+
+**When direct updates are fine:**
+
+- Setting state to a static value: `setCount(0)`
+- Setting state from props/arguments only: `setName(newName)`
+- State doesn't depend on previous value
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md b/.pi/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md
new file mode 100644
index 0000000..4ecb350
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md
@@ -0,0 +1,58 @@
+---
+title: Use Lazy State Initialization
+impact: MEDIUM
+impactDescription: wasted computation on every render
+tags: react, hooks, useState, performance, initialization
+---
+
+## Use Lazy State Initialization
+
+Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
+
+**Incorrect (runs on every render):**
+
+```tsx
+function FilteredList({ items }: { items: Item[] }) {
+ // buildSearchIndex() runs on EVERY render, even after initialization
+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
+ const [query, setQuery] = useState('')
+
+ // When query changes, buildSearchIndex runs again unnecessarily
+ return
+}
+
+function UserProfile() {
+ // JSON.parse runs on every render
+ const [settings, setSettings] = useState(
+ JSON.parse(localStorage.getItem('settings') || '{}')
+ )
+
+ return
+}
+```
+
+**Correct (runs only once):**
+
+```tsx
+function FilteredList({ items }: { items: Item[] }) {
+ // buildSearchIndex() runs ONLY on initial render
+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
+ const [query, setQuery] = useState('')
+
+ return
+}
+
+function UserProfile() {
+ // JSON.parse runs only on initial render
+ const [settings, setSettings] = useState(() => {
+ const stored = localStorage.getItem('settings')
+ return stored ? JSON.parse(stored) : {}
+ })
+
+ return
+}
+```
+
+Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
+
+For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md b/.pi/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md
new file mode 100644
index 0000000..6357049
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md
@@ -0,0 +1,38 @@
+---
+
+title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
+impact: MEDIUM
+impactDescription: restores memoization by using a constant for default value
+tags: rerender, memo, optimization
+
+---
+
+## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
+
+When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
+
+To address this issue, extract the default value into a constant.
+
+**Incorrect (`onClick` has different values on every rerender):**
+
+```tsx
+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
+ // ...
+})
+
+// Used without optional onClick
+
+```
+
+**Correct (stable default value):**
+
+```tsx
+const NOOP = () => {};
+
+const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
+ // ...
+})
+
+// Used without optional onClick
+
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-memo.md b/.pi/skills/vercel-react-best-practices/rules/rerender-memo.md
new file mode 100644
index 0000000..f8982ab
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-memo.md
@@ -0,0 +1,44 @@
+---
+title: Extract to Memoized Components
+impact: MEDIUM
+impactDescription: enables early returns
+tags: rerender, memo, useMemo, optimization
+---
+
+## Extract to Memoized Components
+
+Extract expensive work into memoized components to enable early returns before computation.
+
+**Incorrect (computes avatar even when loading):**
+
+```tsx
+function Profile({ user, loading }: Props) {
+ const avatar = useMemo(() => {
+ const id = computeAvatarId(user)
+ return
+ }, [user])
+
+ if (loading) return
+ return
{avatar}
+}
+```
+
+**Correct (skips computation when loading):**
+
+```tsx
+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
+ const id = useMemo(() => computeAvatarId(user), [user])
+ return
+})
+
+function Profile({ user, loading }: Props) {
+ if (loading) return
+ return (
+
+
+
+ )
+}
+```
+
+**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md b/.pi/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md
new file mode 100644
index 0000000..dd58a1a
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md
@@ -0,0 +1,45 @@
+---
+title: Put Interaction Logic in Event Handlers
+impact: MEDIUM
+impactDescription: avoids effect re-runs and duplicate side effects
+tags: rerender, useEffect, events, side-effects, dependencies
+---
+
+## Put Interaction Logic in Event Handlers
+
+If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
+
+**Incorrect (event modeled as state + effect):**
+
+```tsx
+function Form() {
+ const [submitted, setSubmitted] = useState(false)
+ const theme = useContext(ThemeContext)
+
+ useEffect(() => {
+ if (submitted) {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+ }, [submitted, theme])
+
+ return
+}
+```
+
+**Correct (do it in the handler):**
+
+```tsx
+function Form() {
+ const theme = useContext(ThemeContext)
+
+ function handleSubmit() {
+ post('/api/register')
+ showToast('Registered', theme)
+ }
+
+ return
+}
+```
+
+Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md b/.pi/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md
new file mode 100644
index 0000000..59dfab0
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md
@@ -0,0 +1,35 @@
+---
+title: Do not wrap a simple expression with a primitive result type in useMemo
+impact: LOW-MEDIUM
+impactDescription: wasted computation on every render
+tags: rerender, useMemo, optimization
+---
+
+## Do not wrap a simple expression with a primitive result type in useMemo
+
+When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
+Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
+
+**Incorrect:**
+
+```tsx
+function Header({ user, notifications }: Props) {
+ const isLoading = useMemo(() => {
+ return user.isLoading || notifications.isLoading
+ }, [user.isLoading, notifications.isLoading])
+
+ if (isLoading) return
+ // return some markup
+}
+```
+
+**Correct:**
+
+```tsx
+function Header({ user, notifications }: Props) {
+ const isLoading = user.isLoading || notifications.isLoading
+
+ if (isLoading) return
+ // return some markup
+}
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-transitions.md b/.pi/skills/vercel-react-best-practices/rules/rerender-transitions.md
new file mode 100644
index 0000000..d99f43f
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-transitions.md
@@ -0,0 +1,40 @@
+---
+title: Use Transitions for Non-Urgent Updates
+impact: MEDIUM
+impactDescription: maintains UI responsiveness
+tags: rerender, transitions, startTransition, performance
+---
+
+## Use Transitions for Non-Urgent Updates
+
+Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
+
+**Incorrect (blocks UI on every scroll):**
+
+```tsx
+function ScrollTracker() {
+ const [scrollY, setScrollY] = useState(0)
+ useEffect(() => {
+ const handler = () => setScrollY(window.scrollY)
+ window.addEventListener('scroll', handler, { passive: true })
+ return () => window.removeEventListener('scroll', handler)
+ }, [])
+}
+```
+
+**Correct (non-blocking updates):**
+
+```tsx
+import { startTransition } from 'react'
+
+function ScrollTracker() {
+ const [scrollY, setScrollY] = useState(0)
+ useEffect(() => {
+ const handler = () => {
+ startTransition(() => setScrollY(window.scrollY))
+ }
+ window.addEventListener('scroll', handler, { passive: true })
+ return () => window.removeEventListener('scroll', handler)
+ }, [])
+}
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md b/.pi/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md
new file mode 100644
index 0000000..cf04b81
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md
@@ -0,0 +1,73 @@
+---
+title: Use useRef for Transient Values
+impact: MEDIUM
+impactDescription: avoids unnecessary re-renders on frequent updates
+tags: rerender, useref, state, performance
+---
+
+## Use useRef for Transient Values
+
+When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
+
+**Incorrect (renders every update):**
+
+```tsx
+function Tracker() {
+ const [lastX, setLastX] = useState(0)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => setLastX(e.clientX)
+ window.addEventListener('mousemove', onMove)
+ return () => window.removeEventListener('mousemove', onMove)
+ }, [])
+
+ return (
+
+ )
+}
+```
+
+**Correct (no re-render for tracking):**
+
+```tsx
+function Tracker() {
+ const lastXRef = useRef(0)
+ const dotRef = useRef(null)
+
+ useEffect(() => {
+ const onMove = (e: MouseEvent) => {
+ lastXRef.current = e.clientX
+ const node = dotRef.current
+ if (node) {
+ node.style.transform = `translateX(${e.clientX}px)`
+ }
+ }
+ window.addEventListener('mousemove', onMove)
+ return () => window.removeEventListener('mousemove', onMove)
+ }, [])
+
+ return (
+
+ )
+}
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/server-after-nonblocking.md b/.pi/skills/vercel-react-best-practices/rules/server-after-nonblocking.md
new file mode 100644
index 0000000..e8f5b26
--- /dev/null
+++ b/.pi/skills/vercel-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/.pi/skills/vercel-react-best-practices/rules/server-auth-actions.md b/.pi/skills/vercel-react-best-practices/rules/server-auth-actions.md
new file mode 100644
index 0000000..ee82c04
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/server-auth-actions.md
@@ -0,0 +1,96 @@
+---
+title: Authenticate Server Actions Like API Routes
+impact: CRITICAL
+impactDescription: prevents unauthorized access to server mutations
+tags: server, server-actions, authentication, security, authorization
+---
+
+## Authenticate Server Actions Like API Routes
+
+**Impact: CRITICAL (prevents unauthorized access to server mutations)**
+
+Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
+
+Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
+
+**Incorrect (no authentication check):**
+
+```typescript
+'use server'
+
+export async function deleteUser(userId: string) {
+ // Anyone can call this! No auth check
+ await db.user.delete({ where: { id: userId } })
+ return { success: true }
+}
+```
+
+**Correct (authentication inside the action):**
+
+```typescript
+'use server'
+
+import { verifySession } from '@/lib/auth'
+import { unauthorized } from '@/lib/errors'
+
+export async function deleteUser(userId: string) {
+ // Always check auth inside the action
+ const session = await verifySession()
+
+ if (!session) {
+ throw unauthorized('Must be logged in')
+ }
+
+ // Check authorization too
+ if (session.user.role !== 'admin' && session.user.id !== userId) {
+ throw unauthorized('Cannot delete other users')
+ }
+
+ await db.user.delete({ where: { id: userId } })
+ return { success: true }
+}
+```
+
+**With input validation:**
+
+```typescript
+'use server'
+
+import { verifySession } from '@/lib/auth'
+import { z } from 'zod'
+
+const updateProfileSchema = z.object({
+ userId: z.string().uuid(),
+ name: z.string().min(1).max(100),
+ email: z.string().email()
+})
+
+export async function updateProfile(data: unknown) {
+ // Validate input first
+ const validated = updateProfileSchema.parse(data)
+
+ // Then authenticate
+ const session = await verifySession()
+ if (!session) {
+ throw new Error('Unauthorized')
+ }
+
+ // Then authorize
+ if (session.user.id !== validated.userId) {
+ throw new Error('Can only update own profile')
+ }
+
+ // Finally perform the mutation
+ await db.user.update({
+ where: { id: validated.userId },
+ data: {
+ name: validated.name,
+ email: validated.email
+ }
+ })
+
+ return { success: true }
+}
+```
+
+Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
diff --git a/.pi/skills/vercel-react-best-practices/rules/server-cache-lru.md b/.pi/skills/vercel-react-best-practices/rules/server-cache-lru.md
new file mode 100644
index 0000000..ef6938a
--- /dev/null
+++ b/.pi/skills/vercel-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/.pi/skills/vercel-react-best-practices/rules/server-cache-react.md b/.pi/skills/vercel-react-best-practices/rules/server-cache-react.md
new file mode 100644
index 0000000..87c9ca3
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/server-cache-react.md
@@ -0,0 +1,76 @@
+---
+title: Per-Request Deduplication with React.cache()
+impact: MEDIUM
+impactDescription: deduplicates within request
+tags: server, cache, react-cache, deduplication
+---
+
+## Per-Request Deduplication with React.cache()
+
+Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
+
+**Usage:**
+
+```typescript
+import { cache } from 'react'
+
+export const getCurrentUser = cache(async () => {
+ const session = await auth()
+ if (!session?.user?.id) return null
+ return await db.user.findUnique({
+ where: { id: session.user.id }
+ })
+})
+```
+
+Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
+
+**Avoid inline objects as arguments:**
+
+`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
+
+**Incorrect (always cache miss):**
+
+```typescript
+const getUser = cache(async (params: { uid: number }) => {
+ return await db.user.findUnique({ where: { id: params.uid } })
+})
+
+// Each call creates new object, never hits cache
+getUser({ uid: 1 })
+getUser({ uid: 1 }) // Cache miss, runs query again
+```
+
+**Correct (cache hit):**
+
+```typescript
+const getUser = cache(async (uid: number) => {
+ return await db.user.findUnique({ where: { id: uid } })
+})
+
+// Primitive args use value equality
+getUser(1)
+getUser(1) // Cache hit, returns cached result
+```
+
+If you must pass objects, pass the same reference:
+
+```typescript
+const params = { uid: 1 }
+getUser(params) // Query runs
+getUser(params) // Cache hit (same reference)
+```
+
+**Next.js-Specific Note:**
+
+In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
+
+- Database queries (Prisma, Drizzle, etc.)
+- Heavy computations
+- Authentication checks
+- File system operations
+- Any non-fetch async work
+
+Use `React.cache()` to deduplicate these operations across your component tree.
+
+Reference: [React.cache documentation](https://react.dev/reference/react/cache)
diff --git a/.pi/skills/vercel-react-best-practices/rules/server-dedup-props.md b/.pi/skills/vercel-react-best-practices/rules/server-dedup-props.md
new file mode 100644
index 0000000..fb24a25
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/server-dedup-props.md
@@ -0,0 +1,65 @@
+---
+title: Avoid Duplicate Serialization in RSC Props
+impact: LOW
+impactDescription: reduces network payload by avoiding duplicate serialization
+tags: server, rsc, serialization, props, client-components
+---
+
+## Avoid Duplicate Serialization in RSC Props
+
+**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
+
+RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
+
+**Incorrect (duplicates array):**
+
+```tsx
+// RSC: sends 6 strings (2 arrays × 3 items)
+
+```
+
+**Correct (sends 3 strings):**
+
+```tsx
+// RSC: send once
+
+
+// Client: transform there
+'use client'
+const sorted = useMemo(() => [...usernames].sort(), [usernames])
+```
+
+**Nested deduplication behavior:**
+
+Deduplication works recursively. Impact varies by data type:
+
+- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
+- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
+
+```tsx
+// string[] - duplicates everything
+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
+
+// object[] - duplicates array structure only
+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
+```
+
+**Operations breaking deduplication (create new references):**
+
+- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
+- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
+
+**More examples:**
+
+```tsx
+// ❌ Bad
+ u.active)} />
+
+
+// ✅ Good
+
+
+// Do filtering/destructuring in client
+```
+
+**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
diff --git a/.pi/skills/vercel-react-best-practices/rules/server-hoist-static-io.md b/.pi/skills/vercel-react-best-practices/rules/server-hoist-static-io.md
new file mode 100644
index 0000000..5b642b6
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/server-hoist-static-io.md
@@ -0,0 +1,142 @@
+---
+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 }] }
+ )
+}
+```
+
+**Alternative: synchronous file reads with Node.js fs**
+
+```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 }] }
+ )
+}
+```
+
+**General Node.js example: loading config or templates**
+
+```typescript
+// Incorrect: reads config on every call
+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: loads once at module level
+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/.pi/skills/vercel-react-best-practices/rules/server-parallel-fetching.md b/.pi/skills/vercel-react-best-practices/rules/server-parallel-fetching.md
new file mode 100644
index 0000000..1affc83
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/server-parallel-fetching.md
@@ -0,0 +1,83 @@
+---
+title: Parallel Data Fetching with Component Composition
+impact: CRITICAL
+impactDescription: eliminates server-side waterfalls
+tags: server, rsc, parallel-fetching, composition
+---
+
+## Parallel Data Fetching with Component Composition
+
+React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
+
+**Incorrect (Sidebar waits for Page's fetch to complete):**
+
+```tsx
+export default async function Page() {
+ const header = await fetchHeader()
+ return (
+
+ )
+}
+
+export default function Page() {
+ return (
+
+
+
+ )
+}
+```
diff --git a/.pi/skills/vercel-react-best-practices/rules/server-serialization.md b/.pi/skills/vercel-react-best-practices/rules/server-serialization.md
new file mode 100644
index 0000000..39c5c41
--- /dev/null
+++ b/.pi/skills/vercel-react-best-practices/rules/server-serialization.md
@@ -0,0 +1,38 @@
+---
+title: Minimize Serialization at RSC Boundaries
+impact: HIGH
+impactDescription: reduces data transfer size
+tags: server, rsc, serialization, props
+---
+
+## Minimize Serialization at RSC Boundaries
+
+The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
+
+**Incorrect (serializes all 50 fields):**
+
+```tsx
+async function Page() {
+ const user = await fetchUser() // 50 fields
+ return
+}
+
+'use client'
+function Profile({ user }: { user: User }) {
+ return
{user.name}
// uses 1 field
+}
+```
+
+**Correct (serializes only 1 field):**
+
+```tsx
+async function Page() {
+ const user = await fetchUser()
+ return
+}
+
+'use client'
+function Profile({ name }: { name: string }) {
+ return
{name}
+}
+```
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..8626abe
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,387 @@
+# AGENTS.md
+
+Guidance for humans and AI agents working in `jalco-ui`.
+
+The key words "MUST", "MUST NOT", "SHOULD", "SHOULD NOT", and "MAY" in this document are to be interpreted as described in [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119).
+
+## Project intent
+
+jalco ui is a React component library by Justin Levine. It ships polished, composable components for React and Next.js projects, distributed via a shadcn-compatible registry so users can install with a single command or copy the source directly.
+
+Goals:
+- Keep the codebase polished, readable, and consistent.
+- Optimize for public/open-source maintainability.
+- Prefer simple, composable patterns over clever abstractions.
+- Make examples, docs, and components production-quality.
+- Use shadcn registry infrastructure for distribution, not as an identity constraint.
+
+## Core principles
+
+- Favor clarity over novelty.
+- Keep diffs focused and reviewable.
+- Match existing patterns before introducing new ones.
+- Make documentation part of the feature, not an afterthought.
+- Build for accessibility, composability, and copy-paste ergonomics.
+- Avoid unnecessary dependencies.
+
+## Repository standards
+
+### General
+
+- All files MUST use consistent naming across files, exports, components, and docs.
+- Folder structure SHOULD be predictable and shallow where possible.
+- Small helpers SHOULD be colocated with the feature that uses them.
+- TypeScript MUST be used for all source files.
+- Committed code MUST NOT contain dead code, commented-out code, or placeholder implementations.
+
+### Components
+
+- Components SHOULD be small and composable.
+- Accessible primitives and interactions MUST be the default.
+- Prop names MUST be clear with sensible defaults.
+- APIs MUST NOT be overengineered before real usage justifies it.
+- Registry items MUST be installable, readable, and easy to adapt.
+- Public registry code and docs-facing source files MUST follow the comment and file header rules in `.pi/references/docs-component-format-spec.md`.
+- When building or refactoring public jalco ui components, agents MUST use `.pi/skills/jalco-component-builder/SKILL.md` as the primary workflow skill.
+- Agents SHOULD treat `shadcn-ui`, `.pi/skills/tailwind-design-system/SKILL.md`, `.pi/skills/vercel-composition-patterns/SKILL.md`, `.pi/skills/vercel-react-best-practices/SKILL.md`, and `component-engineering` as supporting references during component work.
+- When building or maintaining registry infrastructure or items, agents MUST consult `.pi/skills/jalco-shadcn-registry/SKILL.md`.
+- When creating or revising component documentation, agents MUST consult `.pi/skills/jalco-writing-component-docs/SKILL.md`.
+- The Vercel React best-practices skill SHOULD be used for performance, rendering, data fetching, and Next.js architecture decisions.
+- The Vercel composition patterns skill SHOULD be used for component API design, composition, compound components, and avoiding boolean-prop-heavy interfaces.
+- The Tailwind design-system skill SHOULD be used for Tailwind v4 tokens, semantic styling, variant systems, theming, and design-system consistency.
+- The Jalco shadcn registry skill SHOULD be used for item typing, `registry.json`, namespacing, authentication planning, MCP compatibility, Open in v0 considerations, and registry structure decisions.
+
+### Component quality bar
+
+Public jalco ui components MUST feel intentional, production-ready, and visually complete in their default state.
+
+When designing or reviewing a component:
+- MUST start from a clear use case, not from a styling trick or a variant list
+- SHOULD prefer one strong layout idea over stacked decorative treatments
+- SHOULD use spacing, typography, grouping, and alignment to create hierarchy before reaching for extra color, borders, shadows, or icons
+- MUST keep APIs smaller and more semantic than the first draft
+- SHOULD favor fewer, stronger variants over many shallow permutations
+- MUST ensure the default example is the most compelling and broadly useful version
+- MUST make demos feel like real product UI, not component laboratory output
+- MUST NOT ship a public component unless it is visually distinct enough to justify its existence in the registry
+
+A public variant MUST:
+- represent a real use case or semantic difference
+- have meaningful preview and docs coverage
+- remain understandable from its API name alone
+
+MUST NOT include:
+- decorative-only variants
+- prop-heavy APIs that expose internal styling decisions
+- generic card wrappers with little opinion
+- demos padded with badges, icons, or fake complexity to compensate for weak structure
+- components whose examples look unfinished without consumer customization
+
+### Component creation workflow
+
+When building a new public component, agents MUST NOT jump straight to implementation. Every new component MUST be developed on a feature branch and merged to main via a PR that passes the component checklist.
+
+#### Branch and PR requirements
+
+All work MUST happen on a branch. Branch names MUST follow [Conventional Branch](https://conventional-branch.github.io/) naming:
+
+```text
+/
+```
+
+Supported types:
+- `feat/` — new features and components (e.g. `feat/tooltip`, `feat/stat-card`)
+- `fix/` — bug fixes (e.g. `fix/icon-alignment`)
+- `chore/` — dependency updates, config, docs-only changes (e.g. `chore/update-deps`)
+- `hotfix/` — urgent production fixes (e.g. `hotfix/broken-build`)
+- `release/` — release preparation (e.g. `release/v1.0.0`)
+
+Rules:
+- Branch names MUST use lowercase letters, numbers, and hyphens only.
+- Branch names MUST NOT contain consecutive, leading, or trailing hyphens.
+- Descriptions SHOULD be concise and descriptive.
+- Agents MUST NOT commit directly to `main`.
+
+For component branches specifically:
+- All implementation, docs, previews, and screenshots MUST happen on the branch.
+- A PR MUST be opened using the component PR template (`.github/PULL_REQUEST_TEMPLATE/component.md`).
+- The PR MUST pass every checklist item before merging.
+- Dark and light mode screenshots MUST be included in the PR body.
+
+#### Implementation steps
+
+1. Clarify the component's use case and desired feel.
+2. Use the `question` or `questionnaire` tool when requirements, variants, or usage context are unclear.
+3. Decide whether the artifact is a primitive, composed component, or block.
+4. Prefer a single-file implementation unless multiple files materially improve runtime correctness, reuse, readability, or installability.
+5. Reuse established Jalco/shadcn variant language when appropriate, but MUST NOT add variants mechanically.
+6. MUST NOT add new dependencies unless they materially improve the component and are justified against copy-paste and registry ergonomics.
+7. Implement the component with accessible structure, restrained styling, and realistic demo content.
+8. Document the component in the same change, including preview, installation, and usage.
+9. Create a card preview file at `components/docs/previews/.tsx` showing the component and its key variants, then run `pnpm previews:generate`.
+10. Add the component to the sidebar nav in `lib/docs.ts` with `badge: "New"` and `badgeAdded` set to today's ISO date (e.g. `"2026-03-12"`).
+11. Generate screenshots via `/dev/screenshots` — use "Save All → public/previews/" to write both `-dark.png` and `-light.png`.
+12. Run `pnpm registry:build` and `pnpm build` to verify everything compiles.
+13. Open a PR with the component template and verify every checklist item.
+
+### File boundaries and component structure
+
+Public jalco ui components SHOULD use a single file unless multiple files materially improve readability, reuse, runtime correctness, or installability.
+
+Use one file when:
+- the component is one conceptual unit
+- helpers are local to the component
+- subcomponents are primarily meaningful together
+- the main adoption path benefits from opening and editing one file
+- the file remains easy to scan and review
+
+Split into multiple files when:
+- parts are meaningfully reusable outside the component
+- runtime boundaries differ (`use client`, server-only code, dynamic loading, etc.)
+- the component is a true multi-part block rather than a single UI primitive
+- registry packaging or install targets become clearer
+- a single file becomes harder to understand than the separated version
+
+MUST NOT:
+- create `types.ts`, `constants.ts`, or `utils.ts` files for tiny component-local code
+- split purely to simulate architecture
+- make copy-paste adoption worse with unnecessary indirection
+
+For public registry items, file structure MUST be optimized for readability and adaptation before abstraction.
+
+### Dependency judgment
+
+Agents MUST prefer existing dependencies, browser APIs, CSS, and current repo primitives before adding new packages.
+
+Before adding a dependency, agents MUST evaluate:
+- whether the behavior can be achieved with current repo dependencies or native CSS/browser APIs
+- whether the dependency materially improves the public component
+- whether it increases adoption or registry friction
+- whether a consumer would reasonably expect that dependency for this kind of component
+
+No new dependency SHOULD be added unless the payoff is clear.
+
+### Showcasing components and variants
+
+When adding a new component or docs component to the site, agents MUST follow the established showcase pattern from `app/page.tsx`:
+
+- **Section wrapper:** Each component gets its own `` with `rounded-xl border p-4 sm:p-5` and a `flex flex-col gap-4` layout.
+- **Section header:** A title (`text-lg font-semibold tracking-tight`) and a short description (`text-sm text-muted-foreground`). For registry items, include an `` aligned to the right on larger screens.
+- **Variant showcase:** When a component has multiple variants, props, or visual states, each one MUST be shown as a labeled sub-section:
+ - Group all variants in a `
`.
+ - Each variant gets a `
` containing:
+ - A label: `
Variant Name
`
+ - The component rendered with that variant's props.
+ - Labels MUST be descriptive and concise (e.g., "Default", "Scrollable", "Muted + Collapsible", "Colored Icons").
+- **Single-variant components:** If a component only has one visual state, render it directly inside the section without variant labels.
+- **Realistic content:** Examples MUST use realistic, polished content — not lorem ipsum or bare-minimum placeholders.
+
+### Styling
+
+- Styling patterns MUST be uniform across components and docs.
+- Existing utility/classname conventions MUST be preferred over inventing new ones.
+- Visual consistency between preview examples, code blocks, and docs pages MUST be maintained.
+- One-off styling MUST NOT be used unless there is a documented reason.
+
+### Comments and file headers
+
+- Jalco ui file headers and comment style MUST be applied to original Jalco-authored public registry items and docs-facing source files.
+- Copied, upstream, generated, or template-derived files MUST NOT be mass-retrofitted unless they are being meaningfully rewritten.
+- Public jalco ui registry files SHOULD use a consistent top-of-file header comment when appropriate.
+- For public Jalco-authored component entry files, the header SHOULD include:
+ - `jalco-ui`
+ - component name
+ - `by Justin Levine`
+ - `ui.justinlevine.me`
+ - one-sentence description
+ - key public props when useful
+ - dependencies, only when the file has noteworthy external or registry requirements
+ - inspiration / attribution, only when there is real upstream inspiration worth crediting
+ - notes only when runtime behavior materially affects usage
+- For smaller supporting files, a lighter header or no header MAY be used if the file is already obvious.
+- File headers MUST be compact and human-written in tone.
+- File headers MUST NOT duplicate the full docs page inside a source comment.
+- **Decorative separator banners MUST NOT appear in source code.** This includes `/* --- */`, `/* === */`, `/* Section Name */` surrounded by dashes, or any padded block-comment dividers. These are AI slop. Use whitespace to separate sections. If a label is genuinely needed, use a single plain `// Label` comment — no box, no dashes, no padding.
+- Inline comments MUST be minimal and useful.
+- No comment is preferred over obvious commentary.
+- Comments SHOULD explain non-obvious decisions, constraints, attribution, or important integration context.
+- Comments MUST NOT narrate straightforward code or restate what the code already makes obvious.
+
+### Documentation
+
+- Every meaningful feature MUST include or update docs.
+- Documentation MUST be concise and skimmable.
+- Examples SHOULD reflect real usage.
+- Installation instructions MUST be accurate for multiple package managers when relevant.
+- If a component or block has constraints, they MUST be called out explicitly.
+
+### Catalog card previews
+
+Every public registry component MUST have a card preview file so it appears on the `/docs` catalog page and the `/dev/screenshots` utility page.
+
+- A file MUST be created at `components/docs/previews/.tsx` for each component.
+- The file MUST default-export an async server component that renders a miniature version of the component with realistic sample data.
+- Previews SHOULD be small and self-contained — just enough to visually represent the component in a card thumbnail.
+- When a component has meaningful variants, sizes, icon styles, or layout exports, they SHOULD be shown in the preview file using a vertical or wrapped flex layout.
+- These files are docs-site only — they MUST NOT be part of the installable registry item.
+- After creating or removing a preview file, `pnpm previews:generate` MUST be run to regenerate the import map.
+- The generated import map lives in `components/docs/__generated__/preview-imports.ts` and is gitignored.
+- The codegen runs automatically on `pnpm dev` and `pnpm build`.
+
+### Screenshot utility page
+
+A dev-only page at `/dev/screenshots` renders every component preview at full size inside a fixed 1280×640 frame for capturing PNGs (Product Hunt, social cards, marketing).
+
+- The page auto-discovers previews from the same generated import map — no extra wiring needed.
+- Each component has a per-component scale slider (40%–150%) and a download button.
+- A global pixel ratio selector (1x, 2x, 3x) controls export resolution.
+- "Download All" batch-saves every component as a PNG.
+- The page is excluded from robots.txt and marked `noindex`.
+- When adding a new component, the preview file automatically appears on this page after running `pnpm previews:generate`.
+
+### Writing component docs
+
+- `.pi/references/docs-component-format-spec.md` MUST be followed as the canonical docs format guide for public component and block pages.
+- Component doc descriptions MUST start with a concise one-sentence summary of what the component does.
+- Descriptions MUST NOT start with "A", "An", or "A React component for...".
+- Descriptions MUST NOT contain implementation details, subjective adjectives, or unnecessary jargon.
+- For registry-backed components, descriptions MUST be aligned between docs frontmatter and registry metadata.
+- `## Features` SHOULD only be used when a component has non-obvious capabilities, interaction patterns, or constraints.
+- Features sections SHOULD be limited to 2-4 short bullets written in capability-first language.
+- Component docs MUST support the site's preview, code, install, and usage flow using the shared docs anatomy: Metadata, Header, Preview, Installation, Usage, then only justified optional sections.
+- Not every example is a variant; Variants, Sizes, Examples, Configurations, and bundled export labels MUST be used intentionally.
+- Important setup requirements MUST be surfaced before Examples; adoption blockers MUST NOT be buried in Notes.
+- API, variants, examples, requirements, or notes sections SHOULD only be added when they provide meaningful value.
+- Naming MUST be aligned across component titles, slugs, registry items, preview names, and exports.
+- Examples SHOULD use realistic, polished content over placeholder content.
+- When changing a public component's API, variants, states, or installation surface, all affected docs MUST be updated in the same change.
+- For public component changes, agents MUST check related docs pages, preview/demo files, homepage or showcase examples, usage snippets, and registry metadata.
+- Public variants MUST NOT be added or removed without verifying that labels, examples, and preview coverage still match the shipped component.
+
+## Commit standards
+
+This repository MUST use [Conventional Commits](https://www.conventionalcommits.org/).
+
+Format:
+
+```text
+():
+```
+
+Examples:
+- `feat(registry): add initial component schema`
+- `fix(docs): correct pnpm install command`
+- `docs(intro): add registry overview page`
+- `refactor(ui): simplify code block tabs`
+- `chore(repo): add AGENTS.md guidance`
+
+### Allowed types
+
+`feat`, `fix`, `docs`, `refactor`, `style`, `test`, `chore`, `build`, `ci`, `perf`, `revert`
+
+### Commit rules
+
+- Commits MUST use the imperative mood.
+- Subject lines MUST be concise.
+- Subject lines MUST NOT end with a period.
+- Each commit MUST be focused to one logical change.
+- Formatting-only changes MUST NOT be mixed with feature work unless necessary.
+- Small commits SHOULD be preferred over large mixed commits.
+- Secrets, tokens, or local environment files MUST NOT be committed.
+
+## Pull request standards
+
+PRs SHOULD be small, clear, and easy to review.
+
+### PR templates
+
+Two PR templates are available:
+- **Default** (`.github/pull_request_template.md`) — for general changes (fixes, docs, refactors, infra).
+- **Component** (`.github/PULL_REQUEST_TEMPLATE/component.md`) — for new public components. Includes the full component shipping checklist.
+
+When opening a component PR on GitHub, the component template MUST be selected from the template dropdown, or `?template=component.md` appended to the PR URL.
+
+### General PR checklist
+
+- What changed MUST be summarized.
+- Why the change was made MUST be explained.
+- Design or API decisions SHOULD be noted.
+- Screenshots/GIFs SHOULD be included for UI changes.
+- Docs MUST be updated if behavior, installation, or usage changed.
+- Relevant commands/builds/tests MUST be verified before opening or merging.
+
+### Component PR checklist
+
+Every new public component PR MUST pass these before merging:
+- Component source in `registry//` with registry.json entry
+- Sidebar nav entry in `lib/docs.ts` with `badge: "New"` and `badgeAdded` set to today's date
+- Docs page at `app/docs/components//page.tsx` with matching description
+- Card preview at `components/docs/previews/.tsx` with key variants
+- `pnpm previews:generate` run
+- Screenshots at `public/previews/-dark.png` and `-light.png` (1280×640 @ 2x)
+- `pnpm registry:build` and `pnpm build` pass
+- Dark and light screenshots attached to the PR
+
+### PR title
+
+PR titles MUST use Conventional Commit style.
+
+Examples:
+- `feat(registry): add tooltip component`
+- `fix(registry): resolve invalid item path`
+- `docs(stepper): add usage examples`
+
+## Agent workflow expectations
+
+When working in this repository, agents:
+- MUST read existing files before editing them.
+- MUST reuse established patterns and structure.
+- MUST NOT perform broad rewrites unless explicitly requested.
+- SHOULD call out tradeoffs when introducing new patterns.
+- MUST prefer surgical edits with minimal blast radius.
+- SHOULD keep generated output and formatting noise to a minimum.
+- MUST document new conventions in this file or the relevant docs.
+
+### Prompt and slash-command workflow
+
+For component-focused work, agents MUST prefer the shared jalco ui prompts and workflow files:
+- `.pi/prompts/component-create.md` for creating a new component, block, or docs-facing UI artifact
+- `.pi/prompts/component-review.md` for auditing an existing component, preview, or public API
+- `.pi/skills/jalco-component-builder/SKILL.md` as the primary workflow skill behind both flows
+
+When a user asks to create or review a component, agents MUST NOT jump straight to implementation. Start from the Jalco component-builder workflow, clarify requirements when needed, then implement and document the result.
+
+## Consistency rules
+
+- One naming convention per concern MUST be used and kept consistent.
+- Public APIs MUST be stable and intentional.
+- Example data MUST be realistic and tidy.
+- Docs copy, component names, and registry item names MUST be aligned.
+- If introducing a new pattern, it MUST be applied consistently or documented as exceptional.
+
+## Open-source readiness
+
+Because this code is public:
+- Code and docs MUST be written as if others will learn from them.
+- Private/internal shorthand MUST NOT appear in committed code.
+- Descriptive names MUST be preferred over personal abbreviations.
+- Onboarding friction MUST be kept low for contributors and users.
+- Installation and usage paths MUST be obvious.
+
+## When unsure
+
+If a decision is unclear, prefer:
+1. readability
+2. accessibility
+3. consistency
+4. maintainability
+5. extensibility
+
+## Initial conventions for jal-co/ui
+
+Until the project evolves further, default to:
+- clean documentation-first structure
+- shadcn-aligned ergonomics
+- strong preview/code/install UX
+- multi-package-manager install examples where relevant
+- polished, production-quality examples over quantity