{"id":"d3896099-5422-4329-8f0e-dc39a48a0403","entityType":"agent","slug":"clawhub-iliaal-compound-eng-react-frontend","name":"ia-react-frontend","canonicalUrl":"https://www.xpersona.co/agent/clawhub-iliaal-compound-eng-react-frontend","canonicalPath":"/agent/clawhub-iliaal-compound-eng-react-frontend","generatedAt":"2026-10-09T15:16:07.370Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-09T12:23:05.550Z","emptyReason":null},"description":"React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, reviewing React code, or synchronizing JSON locales and reviewing translations in a React or frontend interface. For visual design and aesthetic direction, use frontend-design instead. Skill: ia-react-frontend Owner: iliaal Summary: React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, reviewing React code, or synchronizing JSON locales and reviewing translations in a React or frontend interface. For visual design and aesthetic direction, use frontend-design instead. Ta","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 2.7K downloads reported by the source. Last updated 10/9/2026.","installCommand":"clawhub skill install s17bcar8wq0xhegs0ny6f57ypd8484bw:compound-eng-react-frontend","sourceUrl":"https://clawhub.ai/iliaal/compound-eng-react-frontend","homepage":"https://clawhub.ai/iliaal/skills/compound-eng-react-frontend","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/iliaal/compound-eng-react-frontend","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/iliaal/skills/compound-eng-react-frontend","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":46,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-09T12:23:05.550Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T12:23:05.550Z","emptyReason":null},"stars":null,"forks":null,"downloads":2661,"packageName":null,"latestVersion":"5.0.1","tractionLabel":"2.7K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T12:23:05.549Z","emptyReason":null},"lastUpdatedAt":"2026-10-09T12:23:05.550Z","lastCrawledAt":"2026-10-09T12:23:05.549Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-10T12:23:05.549Z","lastVerifiedAt":null,"highlights":[{"version":"5.0.1","createdAt":"2026-10-03T17:07:02.338Z","changelog":"v5.0.1","fileCount":16,"zipByteSize":34912},{"version":"5.0.0","createdAt":"2026-09-26T23:19:48.089Z","changelog":"v5.0.0","fileCount":15,"zipByteSize":32128},{"version":"4.5.2","createdAt":"2026-09-08T01:49:01.814Z","changelog":"v4.5.2","fileCount":9,"zipByteSize":20452},{"version":"4.5.0","createdAt":"2026-08-29T22:22:10.718Z","changelog":"v4.5.0","fileCount":6,"zipByteSize":16946},{"version":"4.4.3","createdAt":"2026-08-29T12:33:05.422Z","changelog":"v4.4.3","fileCount":6,"zipByteSize":13462},{"version":"4.4.1","createdAt":"2026-08-10T19:39:29.452Z","changelog":"v4.4.1","fileCount":6,"zipByteSize":13443},{"version":"4.2.1","createdAt":"2026-07-11T11:15:24.505Z","changelog":"v4.2.1","fileCount":6,"zipByteSize":12746},{"version":"4.2.0","createdAt":"2026-07-07T18:39:13.514Z","changelog":"v4.2.0","fileCount":6,"zipByteSize":12634}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17bcar8wq0xhegs0ny6f57ypd8484bw:compound-eng-react-frontend","setupComplexity":"low","setupSteps":["Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-09T15:16:07.365Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-iliaal-compound-eng-react-frontend/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-09T12:23:05.550Z","emptyReason":null},"readme":"Skill: ia-react-frontend\n\nOwner: iliaal\n\nSummary: React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, reviewing React code, or synchronizing JSON locales and reviewing translations in a React or frontend interface. For visual design and aesthetic direction, use frontend-design instead.\n\nTags: latest:5.0.1\n\nVersion history:\n\nv5.0.1 | 2026-10-03T17:07:02.338Z | user\n\nv5.0.1\n\nv5.0.0 | 2026-09-26T23:19:48.089Z | user\n\nv5.0.0\n\nv4.5.2 | 2026-09-08T01:49:01.814Z | user\n\nv4.5.2\n\nv4.5.0 | 2026-08-29T22:22:10.718Z | user\n\nv4.5.0\n\nv4.4.3 | 2026-08-29T12:33:05.422Z | user\n\nv4.4.3\n\nv4.4.1 | 2026-08-10T19:39:29.452Z | user\n\nv4.4.1\n\nv4.2.1 | 2026-07-11T11:15:24.505Z | user\n\nv4.2.1\n\nv4.2.0 | 2026-07-07T18:39:13.514Z | user\n\nv4.2.0\n\nv4.1.0 | 2026-06-01T16:01:17.068Z | user\n\nv4.1.0\n\nv3.0.5 | 2026-04-30T00:03:32.781Z | user\n\nv3.0.5\n\nv3.0.4 | 2026-04-27T14:39:28.668Z | user\n\nv3.0.4\n\nv3.0.3 | 2026-04-24T12:35:02.978Z | user\n\nv3.0.3\n\nv3.0.2 | 2026-04-24T11:50:25.488Z | user\n\nv3.0.2\n\nv3.0.1 | 2026-04-24T11:31:07.875Z | user\n\nv3.0.1\n\nv3.0.0 | 2026-04-23T19:28:24.001Z | user\n\nv3.0.0\n\nv2.56.1 | 2026-04-18T13:30:22.887Z | user\n\nv2.56.1\n\nv2.56.0 | 2026-04-14T12:40:30.585Z | user\n\nv2.56.0\n\nv2.55.1 | 2026-04-12T14:30:44.420Z | user\n\nv2.55.1\n\nv2.55.0 | 2026-04-11T01:01:25.140Z | user\n\nv2.55.0\n\nv2.53.2 | 2026-04-08T14:21:14.907Z | user\n\nv2.53.2\n\nv2.53.0 | 2026-04-06T02:57:43.378Z | user\n\nv2.53.0\n\nArchive index:\n\nArchive v5.0.1: 16 files, 34912 bytes\n\nFiles: references/components-and-state.md (9513b), references/e2e-testing.md (6946b), references/locale-synchronization.md (2013b), references/rendering-and-frameworks.md (6401b), references/tailwind-class-composition.md (3559b), references/tailwind-component-patterns.md (3851b), references/tailwind-configuration.md (6164b), references/tailwind-layout-patterns.md (3770b), references/tailwind-v3-to-v4.md (1732b), references/tailwind.md (3955b), references/test-selection.md (1547b), references/testing.md (8245b), skill-card.md (2109b), SKILL.md (4740b), SPEC.md (4506b), _meta.json (146b)\n\nFile v5.0.1:SKILL.md\n\n---\nname: ia-react-frontend\nclass: language\ndescription: >-\n  React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when\n  working with React component structure, state management, Next.js routing,\n  Vitest, React Testing Library, reviewing React code, or synchronizing JSON\n  locales and reviewing translations in a React or frontend interface. For\n  visual design and aesthetic direction, use frontend-design instead.\npaths: \"**/*.tsx,**/*.jsx,**/*.ts,**/*.css,**/tailwind.config.*,**/*.html,**/*.vue,**/*.blade.php\"\n---\n\n# React Frontend\n\n**Verify before implementing**: For App Router patterns, React 19 APIs, or version-specific behavior, look up current docs (Context7 `query-docs` if available, else the framework's official docs via web search) before writing code. Training data may lag current releases.\n\n## Working rules\n\n- Keep derived state in render and user actions in event handlers; use effects for external synchronization.\n- Give async work a lifecycle and cancellation policy; represent failure separately from pending and empty data.\n- Preserve focus when hiding interactive regions and exercise keyboard navigation in a real browser.\n- Validate and authorize every public server action; send only needed fields across server/client boundaries.\n- Measure performance changes and test user-visible behavior, not type-checking alone.\n\n## Effects Decision Tree\n\nEffects are escape hatches; most logic should NOT use effects.\n\n| Need | Solution |\n|------|----------|\n| Derived value from props/state | Calculate during render (useMemo if expensive) |\n| Reset state on prop change | `key` prop on component |\n| Respond to user event | Event handler |\n| Notify parent of state change | Call onChange in event handler, or fully controlled component |\n| Chain of state updates | Calculate all next state in one event handler |\n| Sync with external system | Effect with cleanup |\n\n**Effect rules:**\n- Never suppress the linter; fix the code instead\n- Use updater functions (`setItems(prev => [...prev, item])`) to remove state dependencies\n- Move objects/functions inside effects to stabilize dependencies\n- `useEffectEvent` for non-reactive values (e.g., theme in a connection effect)\n- Always return cleanup for subscriptions, connections, listeners\n- Data fetching cancellation (pick by situation): `AbortController` for fetch; `ignore` flag for non-cancellable promises. With React Query, pass the query function's signal to the transport, such as `queryFn: ({ signal }) => fetch(url, { signal })`. Without consuming that signal, an unused query can finish and populate the cache; do not describe that behavior as transport cancellation.\n\n\n## Discipline\n\n- Simplicity first: every change as simple as possible, impact minimal code\n- Only touch what's necessary; avoid introducing unrelated changes\n- No hacky workarounds: if a fix feels wrong, step back and implement the clean solution\n- Before adding a new abstraction, verify it appears in 3+ places\n\n\n## References\n\n- [testing.md](./references/testing.md): Component, hook, and mocking test examples\n- [e2e-testing.md](./references/e2e-testing.md): Playwright E2E patterns\n\n\n## Verify\n\n- TypeScript compiles with zero errors\n- No suppressed lint rules (`eslint-disable`, `@ts-ignore`) in new code\n- `useEffect` dependency arrays not manually overridden\n- No `forwardRef` usage in React 19+ projects (use `ref` prop directly)\n\n## Task-specific references\n\nRead the relevant reference before implementing or reviewing the matching behavior:\n\n- For component types, state ownership, async races, focus, or cached query behavior: [components-and-state.md](./references/components-and-state.md).\n- For performance, React APIs, Next.js boundaries, or caching: [rendering-and-frameworks.md](./references/rendering-and-frameworks.md).\n- For Tailwind CSS: utilities, `@theme` tokens, CVA/tailwind-variants, dark mode, v3-to-v4 migration, or overflow and `hidden` pitfalls: [tailwind.md](./references/tailwind.md).\n- For component, hook, browser, or integration test changes: [test-selection.md](./references/test-selection.md).\n- For synchronizing JSON locale files or reviewing translations: [locale-synchronization.md](./references/locale-synchronization.md).\n\nExisting specialized references, when the corresponding topic applies:\n\n- Tailwind details behind [tailwind.md](./references/tailwind.md): [tailwind-configuration.md](./references/tailwind-configuration.md), [tailwind-v3-to-v4.md](./references/tailwind-v3-to-v4.md), [tailwind-class-composition.md](./references/tailwind-class-composition.md), [tailwind-component-patterns.md](./references/tailwind-component-patterns.md), [tailwind-layout-patterns.md](./references/tailwind-layout-patterns.md).\n\nFile v5.0.1:_meta.json\n\n{\n  \"ownerId\": \"kn715jrbbh71q9zncr0bqdkr8n848q1a\",\n  \"slug\": \"compound-eng-react-frontend\",\n  \"version\": \"5.0.1\",\n  \"publishedAt\": 1791047222338\n}\n\nFile v5.0.1:references/components-and-state.md\n\n# Components, state, and interaction\n\n## Component TypeScript\n\n- Extend native elements with `ComponentPropsWithoutRef<'button'>`, add custom props via intersection\n- Use `React.ReactNode` for children, `React.ReactElement` for single element, render prop `(data: T) => ReactNode`\n- Discriminated unions for variant props; TypeScript narrows automatically in branches\n- Generic components: `<T>` with `keyof T` for column keys, `T extends { id: string }` for constraints\n- Event types: `React.MouseEvent<HTMLButtonElement>`, `FormEvent<HTMLFormElement>`, `ChangeEvent<HTMLInputElement>`\n- `as const` for custom hook tuple returns\n- `useRef<HTMLInputElement>(null)` for DOM (use `?.`), `useRef<number>(0)` for mutable values\n- Explicit `useState<User | null>(null)` for unions/null\n- Pass optional handlers through unwrapped: `onX={(a) => handler?.(a)}` is always truthy, so a child that renders a control only when `onX` is provided always renders it, and the click silently does nothing. Pass `handler` (or `undefined`) and gate the control on the real handler's presence.\n- useReducer actions as discriminated unions: `{ type: 'set'; payload: number } | { type: 'reset' }`\n- useContext null guard: throw in custom `useX()` hook if context is null\n- **A parameter type whose properties are all optional is a weak type, and a mismatched argument fails to compile rather than passing `undefined`.** TypeScript requires the argument to share at least one property with a weak type, so `(record: { newField?: boolean })` rejects a generated type that does not yet carry `newField` with `TS2559: Type 'X' has no properties in common with type 'Y'`. Intersect with the base type instead (`T & { newField?: boolean }`); the shim then deletes cleanly once the field lands upstream\n\n\n## Concurrency & Race Classes\n\nFive race classes survive type-checking and unit tests; hunt each one during review (cleanup/cancellation mechanics: Effect rules above):\n\n| Class | Production signal | Fix |\n|-------|-------------------|-----|\n| Lifecycle cleanup gap | \"state update on unmounted component\" warnings, leaks under rapid navigation | Return cleanup from every effect that registers a listener/timer/observer |\n| Remount-timing mistake | Async callback mutates state/DOM after route change/unmount (`fetch().then(setData)` resolves post-navigation) | Cancel per the cancellation hierarchy |\n| Boolean-as-state for non-binary UI | Contradictory combos (`isLoading: true, error: Error`) | State constant (`'idle' \\| 'loading' \\| 'success' \\| 'error'`) + transition function; invalid states unreachable |\n| Stale promise/timer, no cancel path | Promise chain or `setTimeout` holds `setState` after the component moved on | Bind every async op to a cancel mechanism; test the cleanup path |\n| Per-element handlers on large lists | N closures/subscriptions per row, stale-closure bugs on rapid re-renders | Delegate: one parent handler + `event.target.closest(...)` when >~50 items or frequent updates |\n| Gate keyed on a child's success-only callback | Parent's submit stays locked behind \"still loading, try again in a moment\" copy that never resolves; only a page reload escapes | Report failures up (`onLoadError`) as well as successes, and split the flag into loading / loaded / failed; a boolean cannot carry a terminal state. Keep the action blocked in both if proceeding on unknown data is unsafe; the fix is honest copy plus a real in-place retry, not unblocking |\n| `inert` toggled from a blur-managed flag | First `Tab` *inside* the subtree sends focus to `<body>`; the next `Tab` restarts at the top of the document and skips the (now inert) subtree entirely | React maps `onBlur` to native `focusout`, which fires on intra-subtree moves, and `focusin`/`focusout` are `DiscreteEventPriority`, so React commits `inert` synchronously *between* the two events, landing it on the already-focused incoming control. Stand down only when focus truly leaves: `if (e.currentTarget.contains(e.relatedTarget)) return;` |\n\n**Focus-ownership rules:**\n- Never toggle `inert` on a subtree that currently holds focus. The blunt version has no guard at all: a scroll-driven `inert={!isVisible}` on a sticky bar, drawer, or collapsing panel strands the user on a control that is invisible, inert, and unactivatable. Hand focus to the equivalent visible control before hiding, and pass `focus({ preventScroll: true })` when the handoff fires from a scroll handler, or `focus()` scrolls its target into view and fights the scroll the user is performing. If the handoff target carries the same focus listeners that feed the guard, `focus()` arms the flag as a side effect of doing its job and the subtree never goes inert again; make the handoff symmetric (two effects guarding opposite values of one flag) rather than adding an exception to the guard. `aria-hidden` without `inert` fixes double announcement but leaves the duplicate tab stops. Assert on what the user can *do* (does the handler fire, where does `Tab` go), not on `document.activeElement`; Chromium resolves the unfocusing steps lazily and it reads back inconsistently\n- A blur-managed \"focus is inside\" flag cannot be cleared by a blur that never fires. Headless popover primitives restore focus to the element that *opened* the content on close; when the popover is anchored to an input with no trigger element, that restore no-ops, the library preventDefaults the focus-scope restore, and focus lands on `document.body`. The input never receives another `blur`, so the flag sticks `true` for the component's lifetime and anything gated on it (a \"re-seed local text from `props.value`\" effect, for instance) is silently dead. Clear it explicitly in the select handler and on close when `document.activeElement` is not the input. The same design usually adds `onOpenAutoFocus={e => e.preventDefault()}` to avoid stealing typing focus, which leaves the content pointer-only: no trigger to Tab to and no auto-focus in. Add an explicit affordance plus `aria-haspopup`/`aria-expanded`. Browser-dependent: Chromium and Firefox blur the input on `mousedown`, Safari does not, so \"works on my machine\" from Safari proves nothing\n\n\n## State Management\n\n```\nLocal UI state       → useState, useReducer\nShared client state  → Zustand (simple) | Redux Toolkit (complex)\nAtomic/granular      → Jotai\nServer/remote data   → React Query (TanStack Query)\nURL state            → nuqs, router search params\nForm state           → React Hook Form\n```\n\n**Key patterns:**\n- Zustand: `create<State>()(devtools(persist((set) => ({...}))))`; use slices for scale, selective subscriptions to prevent re-renders\n- React Query: query keys factory (`['users', 'detail', id] as const`), `staleTime`/`gcTime`, optimistic updates with `onMutate`/`onError` rollback\n- React Query `isError` means *a fetch failed*, not *there is no data*: a failed refetch sets `status: 'error'` while retaining the last successful payload, so the usual `isLoading ? spinner : isError ? errorPanel : content` ladder routes a working, fully cached list into the error panel. The defaults compose into it: `refetchOnMount: true` + `staleTime: 0` refetch on every mount, `retry: false` makes one blip terminal, and `gcTime: 5min` keeps the cache alive across a modal's unmount/remount. Gate the branch on data-absence: `isLoadingError` (`isError && !hasData`), or `isError && derived.length === 0` when the suite mocks the hook and leaves `isLoadingError` undefined. Audit the side effects with it: `useEffect(() => { if (isError) toast(...) }, [isError])` fires over the live list too\n- The mirror case has the same tell: under `retry: false` a first load that fails leaves `data` `undefined` forever, so a branch gated on `data !== undefined` folds *failed* into *pending* and renders \"Loading…\" permanently. Whether it is recoverable is decided by mount topology, not by open/closed state: a component rendered unconditionally inside a ref-driven popup is mounted for the life of the page, so `refetchOnMount` never fires again. Any remedy that adds a branch on `isError` must itself be gated on data-absence, or it re-introduces the previous bullet. Enumerate all four states before writing either gate (`isLoading` for first load with no data yet, `isFetching` for any fetch in flight including a background refetch over a warm cache, `isError` for last fetch failed with cache possibly still present, and loaded-and-genuinely-empty) and state the action in each: `!isFetching` misses the error state, `!isFetching && !isError` mishandles a background refetch of a legitimately empty result. The write path has the same shape, inverted: a fail-closed save gate keyed on `isError` blocks a valid submit whenever cached data is present\n- A mutate-scoped `onSuccess` requires a mounted observer when success dispatches. A synchronous hook-level callback can finish before deferred query notifications unmount the row, but that ordering is not a general lifetime guarantee. If hook-level `onSuccess` removes the row and then awaits a refresh, the row can unmount before success dispatches and the mutate-scoped toast can be dropped. Put side effects that must survive unmount in the mutation's hook-level callbacks. Read the installed scheduler and awaited callback chain, and run a known-bad control that removes the observer before dispatch before accepting or dismissing a lifetime finding.\n- Never duplicate server data (React Query) in a client store (Zustand)\n- Colocate state close to where it's used\n\nFile v5.0.1:references/e2e-testing.md\n\n# E2E Testing with Playwright\n\n> When to read: when authoring Playwright end-to-end tests: directory layout, fixtures, page objects, network mocking, CI integration.\n\n## Directory Structure\n\n```\nproject-root/\n├── playwright.config.ts\n└── e2e/\n    ├── fixtures/\n    │   ├── auth.fixture.ts\n    │   └── test-data.fixture.ts\n    ├── pages/\n    │   ├── base.page.ts\n    │   └── <page-name>.page.ts\n    ├── tests/\n    │   ├── auth/\n    │   │   └── login.spec.ts\n    │   └── smoke/\n    │       └── critical-paths.spec.ts\n    └── utils/\n        └── api-helpers.ts\n```\n\nNaming: tests `<feature>.spec.ts`, page objects `<page>.page.ts`, fixtures `<concern>.fixture.ts`.\n\n## Configuration\n\nKeep this config at the project root and run the CLI from that root. Playwright resolves `testDir` relative to the config file. For a nested config, adjust its relative directories and pass `--config <path>` explicitly.\n\n```typescript\nimport { defineConfig, devices } from '@playwright/test';\n\nexport default defineConfig({\n  testDir: './e2e/tests',\n  fullyParallel: true,\n  forbidOnly: !!process.env.CI,\n  retries: process.env.CI ? 2 : 0,\n  workers: process.env.CI ? 1 : undefined,\n  reporter: 'html',\n  expect: {\n    toHaveScreenshot: { animations: 'disabled' },\n  },\n  use: {\n    baseURL: 'http://localhost:5173',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n  },\n  projects: [\n    { name: 'setup', testDir: './e2e/fixtures', testMatch: 'auth.fixture.ts' },\n    {\n      name: 'chromium',\n      use: { ...devices['Desktop Chrome'], storageState: 'e2e/.auth/user.json' },\n      dependencies: ['setup'],\n    },\n  ],\n  webServer: {\n    command: 'npm run dev',\n    url: 'http://localhost:5173',\n    reuseExistingServer: !process.env.CI,\n  },\n});\n```\n\n## Page Object Model\n\nTests never use selectors directly; page objects encapsulate all locators and actions.\n\n```typescript\n// e2e/pages/base.page.ts\nimport { type Page, type Locator } from '@playwright/test';\n\nexport abstract class BasePage {\n  constructor(protected readonly page: Page) {}\n  abstract goto(): Promise<void>;\n  abstract readonly ready: Locator;\n  async waitForLoad() { await this.ready.waitFor(); }\n  get toast(): Locator { return this.page.getByRole('alert'); }\n}\n\n// e2e/pages/users.page.ts\nexport class UsersPage extends BasePage {\n  readonly ready: Locator;\n  readonly createButton: Locator;\n  readonly searchInput: Locator;\n\n  constructor(page: Page) {\n    super(page);\n    this.ready = page.getByRole('heading', { name: /users/i });\n    this.createButton = page.getByRole('button', { name: /create/i });\n    this.searchInput = page.getByRole('searchbox', { name: /search/i });\n  }\n\n  async goto() {\n    await this.page.goto('/users');\n    await this.waitForLoad();\n  }\n\n  async searchFor(query: string) {\n    const resp = this.page.waitForResponse('**/api/users?*');\n    await this.searchInput.fill(query);\n    await resp;\n  }\n}\n```\n\nRules: locators as public readonly properties, actions as async methods with internal waits, no assertions in page objects, one PO per page.\n\n## Selector Priority\n\n| Priority | Method | Use when |\n|----------|--------|----------|\n| 1 | `getByRole` | Buttons, links, headings, inputs |\n| 2 | `getByLabel` | Form inputs with labels |\n| 3 | `getByPlaceholder` | Search inputs |\n| 4 | `getByText` | Static text content |\n| 5 | `getByTestId` | No accessible selector available |\n\nNever use CSS selectors, XPath, or DOM structure selectors. When adding `data-testid`, use `<action>-<entity>-<type>` pattern: `create-user-btn`.\n\n## Filling Inputs\n\nPrefer `locator.fill(value)` to `page.keyboard.type()`. Synthesised keystrokes drop characters intermittently under a browser-attached session (CDP against an already-running browser), and the driver reports the full string as typed while the DOM holds a short value, so the assertion that would catch it is the one nobody writes. Rich-text editors whose state lives outside the element's `value` (ProseMirror, Slate, TipTap) ignore programmatic writes and still need `type()`; there, assert `input_value()` (or the editor's own serialized content) after typing and retry on a short read.\n\n## Wait Strategies\n\nNever use `waitForTimeout` or `setTimeout`. Do not use `waitForLoadState('networkidle')` as a readiness signal; Playwright's API docs mark it discouraged for testing and point to web assertions instead. Start a `waitForResponse` before the action that triggers the request, or a fast response is missed. Use explicit conditions:\n\n```typescript\nawait page.getByRole('heading', { name: 'Dashboard' }).waitFor();\nawait page.waitForURL('/dashboard');\nconst resp = page.waitForResponse(\n  (r) => r.url().includes('/api/users') && r.status() === 200,\n);\nawait page.getByRole('button', { name: /load/i }).click();\nawait resp;\nawait page.getByTestId('spinner').waitFor({ state: 'hidden' });\n```\n\n## Auth State Reuse\n\nSave auth state once, reuse across all tests:\n\n```typescript\n// e2e/fixtures/auth.fixture.ts\nimport { test as setup } from '@playwright/test';\n\nsetup('authenticate', async ({ page }) => {\n  await page.goto('/login');\n  await page.getByLabel('Email').fill('testuser@example.com');\n  await page.getByLabel('Password').fill('TestPassword123!');\n  await page.getByRole('button', { name: /sign in/i }).click();\n  await page.waitForURL('/dashboard');\n  await page.context().storageState({ path: 'e2e/.auth/user.json' });\n});\n```\n\nTests receive auth state via `storageState` in config projects.\n\n## Test Data & Network\n\n- Tests create own data via API helpers (faster than UI), clean up in `finally` blocks\n- Mock responses with `page.route('**/api/path', route => route.fulfill({ ... }))`\n- Simulate errors with `route.abort('failed')`\n\n## Flaky Test Fixes\n\n| Cause | Fix |\n|-------|-----|\n| Hardcoded waits | Explicit wait conditions |\n| Shared test data | Each test creates its own |\n| Animations | Wait for the actual interaction result; for screenshot assertions, use `expect.toHaveScreenshot.animations: 'disabled'` as configured above |\n| Race conditions | Wait for API responses before assertions |\n\nThe screenshot animation option affects screenshot assertions. It does not disable application animations during interaction tests.\n\n**Quarantine workflow**: confirm flakiness before quarantining:\n```bash\nnpx playwright test --repeat-each=10 path/to/test.spec.ts  # Confirm flakiness\nnpx playwright test --retries=3 path/to/test.spec.ts       # Check if retries help\n```\n\nMark confirmed flaky tests with an issue reference:\n```typescript\ntest.fixme(true, 'Flaky - Issue #123');                       // Always skip\ntest.skip(!!process.env.CI, 'Flaky in CI only - Issue #123'); // Skip in CI only\n```\n\n```bash\nnpx playwright test --headed --debug  # Debug mode\nnpx playwright show-trace trace.zip   # Trace viewer\nnpx playwright test --ui              # Interactive UI\n```\n\nFile v5.0.1:references/locale-synchronization.md\n\n# JSON locale synchronization\n\nSynchronize the requested messages with the application's installed message formatter and usage context. Produce a focused locale diff and report structural checks separately from language review.\n\n1. Read the locale configuration and source messages. Trace each changed key to its component or call site. Identify the message's meaning, UI role, interpolation values, and space constraints; a key name alone does not establish translation context.\n2. Compare source history to identify added, changed, and removed messages. If history is unavailable, report translation staleness as unknown. Key parity alone cannot show whether an existing translation still matches a changed source message.\n3. Update only the authorized keys and locales. Preserve unrelated translations, non-string values, and array structure. Confirm usage before removing a message; absence from one source file does not prove the application no longer uses the key.\n4. Preserve required placeholder names and formatter tokens exactly. Validate plural and select grammar with the installed formatter. Use the categories required by the target locale rather than copying the source locale's categories. Preserve interpolation bindings and the markup expected by the renderer; translated text may reorder placeholders or tags where the formatter permits it.\n5. Parse the edited JSON and run the repository's locale or message validation. Check key coverage against the configured fallback policy. Verify placeholder compatibility, plural branches, markup structure, and unchanged non-string values. Reject a structurally valid message that loses a required substitution or branch.\n6. Exercise changed messages in the UI, including representative plural values, long text, and right-to-left layout when applicable. Report linguistic accuracy or visual fit as unverified when no fluent review or browser check occurred. A parser or placeholder check establishes structural compatibility, not translation quality.\n\nFile v5.0.1:references/rendering-and-frameworks.md\n\n# Rendering and framework patterns\n\n## Performance\n\n**Critical: eliminate waterfalls:**\n- `Promise.all()` for independent async operations\n- Move `await` into branches where actually needed\n- Suspense boundaries to stream slow content\n\n**Critical: bundle size:**\n- Import directly from modules, avoid barrel files (`index.ts` re-exports)\n- `next/dynamic` or `React.lazy()` for heavy components\n- Defer third-party scripts (analytics, logging) until after hydration\n- Preload on hover/focus for perceived speed\n- `content-visibility: auto` + `contain-intrinsic-size` on long lists skips off-screen layout/paint\n\n**Re-render optimization:**\n- Never define a component inside another component. Each parent render creates a new function identity, and React compares element *types* to decide whether to update or replace: a new type means the whole subtree unmounts and remounts, so local state is lost, effects re-run, and DOM nodes are recreated. Symptoms are behavioral, not slow: an input loses focus on every keystroke, animations restart, scroll position resets. Hoist the component to module scope and pass what it needed via props. The React Compiler does not save this one; the type identity changes before memoization applies\n- Derive state during render, not in effects\n- Subscribe to derived booleans, not raw objects (`state.items.length > 0` not `state.items`)\n- Functional setState for stable callbacks: `setCount(c => c + 1)`\n- Lazy state init: `useState(() => expensiveComputation())`\n- `useTransition` for non-urgent updates (search filtering)\n- `useDeferredValue` for expensive derived UI\n- Don't subscribe to searchParams/state read only in callbacks; read on demand\n- Use ternary (`condition ? <A /> : <B />`), not `&&` for conditionals\n- `React.memo` only for expensive subtrees with stable props\n- Hoist static JSX outside components\n\n**React Compiler** (React 19): auto-memoizes, so write idiomatic React without adding unnecessary manual memoization. Keep existing `useMemo`/`useCallback`/`memo` until identity-sensitive effects and measured performance verify that removal preserves behavior. Enable via `reactCompiler: true` in next.config (non-framework: `babel-plugin-react-compiler`). Keep components pure.\n\n\n## React 19\n\n- **ref as prop**: `forwardRef` deprecated. Accept `ref?: React.Ref<HTMLElement>` as regular prop\n- **useActionState**: replaces `useFormState`: `const [state, formAction, isPending] = useActionState(action, initialState)`\n- **use()**: unwrap Promise or Context during render (not in callbacks/effects). Enables conditional context reads\n- **useOptimistic**: `const [optimistic, addOptimistic] = useOptimistic(state, mergeFn)` for instant UI feedback\n- **useFormStatus**: `const { pending } = useFormStatus()` in child of `<form action={...}>`\n- **Server Components**: default in App Router. Async, access DB/secrets directly. No hooks, no event handlers\n- **Server Actions**: `'use server'` directive. Validate inputs (Zod), `revalidateTag`/`revalidatePath` after mutations. **Server Actions are public endpoints**; always verify auth/authz inside each action, not just in middleware or layout guards\n- **`<Activity mode='visible'|'hidden'>`** preserves state/DOM for toggled components (experimental)\n\n\n## Next.js App Router\n\n**File conventions:** `page.tsx` (route UI), `layout.tsx` (shared wrapper), `template.tsx` (re-mounted on navigation, unlike layout), `loading.tsx` (Suspense), `error.tsx` (error boundary), `not-found.tsx` (404), `default.tsx` (parallel route fallback), `route.ts` (API endpoint)\n\n**Rendering modes:** Server Components (default) | Client (`'use client'`) | Static (build) | Dynamic (request) | Streaming (progressive)\n\n**Decision:** Server Component unless it needs hooks, event handlers, or browser APIs. Split: server parent + client child. Isolate interactive components as `'use client'` leaf components; keep server components static with no global state or event handlers.\n\n**Server → client boundary:** pass only the fields a client component actually uses, not whole ORM rows or fetch objects. Every prop crossing the `'use client'` boundary is serialized into the payload, so a 50-field `user` object read for one field still ships all 50.\n\n**Client-only state that drives first paint** (theme, locale, feature flag, auth hint): reading `localStorage` during render breaks SSR, and reading it in `useEffect` paints the default first, so the correct value arrives one frame later as a visible flash. Set the value on the document with a small synchronous inline script that runs before hydration, typically writing a `class` or `data-` attribute on `<html>` that CSS already keys on. The script is developer-authored and must never interpolate user, request, or database data; it is the one place `dangerouslySetInnerHTML` is warranted, and only for a literal string.\n\n**Routing patterns:**\n- Route groups `(name)`: organize without affecting URL\n- Parallel routes `@slot`: independent loading states in same layout\n- Intercepting routes `(.)`: modal overlays with full-page fallback\n\n**Caching:**\n- `fetch(url, { cache: 'force-cache' })`: static\n- `fetch(url, { next: { revalidate: 60 } })`: ISR\n- `fetch(url, { cache: 'no-store' })`: dynamic\n- Tag-based: `fetch(url, { next: { tags: ['products'] } })` then `revalidateTag('products')`\n\n**Data fetching:**\n- Fetch in Server Components where data is used\n- Use Suspense boundaries for slow queries\n- `React.cache()` for per-request dedup\n- `generateStaticParams` for static generation\n- `generateMetadata` for dynamic SEO\n- Static metadata with `title: { default: 'App', template: '%s | App' }` for cascading page titles\n- `after()` for non-blocking side effects (logging, analytics); runs after response is sent\n- Hoist static I/O (fonts, config) to module level; runs once, not per request\n- Never hold request-scoped or user data in module-level mutable state: server renders run concurrently in one process, so shared module state leaks across requests (one user's data surfacing in another's response). Hoist only immutable static I/O; keep request data local to the render tree (pass as props)\n\n\n## Tailwind Integration\n\nFor Tailwind v4 configuration, utility patterns, dark mode, and component variants, see [tailwind.md](./tailwind.md).\n\n**Class sorting in JSX**: keep Tailwind classes in canonical order (enforce via `eslint-plugin-better-tailwindcss`).\n\nFile v5.0.1:references/tailwind-class-composition.md\n\n# Class generation and composition\n\n## ESLint Integration\n\nUse `eslint-plugin-better-tailwindcss` for automated class validation:\n- `no-conflicting-classes`: catches `text-red-500 text-blue-500`\n- `no-unknown-classes`: flags typos\n- `enforce-canonical-classes`: normalizes shorthand\n- `no-duplicate-classes`: removes redundant entries\n- `no-deprecated-classes`: catches v3 classes removed in v4\n- `useSortedClasses`: enforces canonical class order; configure `attributes: [\"classList\"]` and `functions: [\"clsx\", \"cva\", \"cn\", \"tv\", \"tw\"]` to cover JSX utility functions\n\n\n## Class Merging\n\nUse `cn()` combining `clsx` + `tailwind-merge` for conditional/dynamic classes. Use plain strings for static `className` attributes.\n\n```typescript\nimport { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\nexport function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }\n```\n\n```typescript\n// Static: plain string\n<button className=\"rounded-lg px-4 py-2 font-medium bg-blue-600\">\n\n// Conditional: use cn()\n<button className={cn(\"rounded-lg px-4 py-2\", isActive ? \"bg-blue-600\" : \"bg-gray-700\")} />\n```\n\n**Keep class names whole in the source.** The example above works because both branches are complete literals. Tailwind's scanner does literal string matching over source text and never evaluates JavaScript, so a class assembled by interpolation is invisible to it and the utility is simply never generated. The failure is silent: no error, no warning, just missing styles.\n\n```typescript\n// Broken: `bg-red-500` never appears in the source, so it is never generated\n<div className={`bg-${color}-500`} />\n\n// Works: every candidate class is a complete literal the scanner can see\nconst BG = { red: \"bg-red-500\", blue: \"bg-blue-500\" } as const;\n\nfunction Swatch({ color }: { color: keyof typeof BG }) {\n  return <div className={BG[color]} />;\n}\n```\n\nThe same applies to classes built in a non-scanned location (a string in a database, a CMS field, or a file outside the configured `@source` paths). Confirm the source actually gets scanned before assuming a literal is enough.\n\n`@source` directives resolve relative to the file they appear in, so a shared token package pulling in a sibling (`@source '../../ui/src/**/*.{ts,tsx}'`) is what makes a `libs/ui`-only utility generate in every consuming app. The real generation risk is a utility with **no** prior usage anywhere, and it fails invisibly rather than loudly: an SVG whose root carries `fill=\"none\"` and whose paths swap `fill=\"#355BF5\"` for `className=\"fill-primary-500\"` renders *invisible*, not mis-colored. Grep the compiled CSS of every consuming app, not one.\n\nVerify by building, not by reading: when class names or scanned sources changed, run the real Tailwind build and grep the output CSS for the expected utilities. Reviewing the `className` attribute proves the string is right, not that the rule exists.\n\n\n## Component Variants\n\nUse `tailwind-variants` (`tv()`) for type-safe variant components. Alternative: `class-variance-authority` (`cva()`).\n\n```typescript\nimport { tv } from \"tailwind-variants\";\nconst button = tv({\n  base: \"rounded-lg px-4 py-2 font-medium transition-colors\",\n  variants: {\n    color: { primary: \"bg-blue-600 text-white\", secondary: \"bg-gray-200 text-gray-800\" },\n    size: { sm: \"text-sm px-3 py-1\", md: \"text-base\", lg: \"text-lg px-6 py-3\" },\n  },\n  defaultVariants: { color: \"primary\", size: \"md\" },\n});\n```\n\nSee [tailwind-variants patterns](./tailwind-component-patterns.md) for slots, composition, and responsive variants.\n\nFile v5.0.1:references/tailwind-component-patterns.md\n\n# Component Patterns\n\n## tailwind-variants (tv)\n\nType-safe component variants with slots, composition, and responsive support.\n\n### Slots API\n\n```typescript\nimport { tv } from \"tailwind-variants\";\n\nconst card = tv({\n  slots: {\n    base: \"rounded-lg border shadow-sm\",\n    header: \"flex flex-col space-y-1.5 p-6\",\n    title: \"text-2xl font-semibold leading-none tracking-tight\",\n    content: \"p-6 pt-0\",\n    footer: \"flex items-center p-6 pt-0\",\n  },\n  variants: {\n    elevated: { true: { base: \"shadow-lg border-0\" } },\n  },\n});\n\nconst { base, header, title, content, footer } = card({ elevated: true });\n```\n\n### Composition\n\n```typescript\nconst baseButton = tv({ base: \"rounded-lg font-medium transition-colors\" });\n\nconst iconButton = tv({\n  extend: baseButton,\n  base: \"inline-flex items-center justify-center\",\n  variants: {\n    size: { sm: \"size-8\", md: \"size-10\", lg: \"size-12\" },\n  },\n});\n```\n\n### Responsive Variants\n\nFor current Tailwind Variants with Tailwind v4, put responsive prefixes in complete class strings. The old `responsiveVariants` option and object-shaped breakpoint values are unavailable.\n\n```typescript\nconst grid = tv({\n  base: \"grid gap-4\",\n  variants: {\n    layout: {\n      compact: \"grid-cols-1 sm:grid-cols-2 lg:grid-cols-4\",\n      spacious: \"grid-cols-1 md:grid-cols-2\",\n    },\n  },\n  defaultVariants: { layout: \"compact\" },\n});\n\nconst gridClassName = grid({ layout: \"compact\" });\n```\n\nUse `gridClassName` as the container's `className`. Include the recipe file in Tailwind's scanned sources. See [Tailwind Variants v4 guidance](https://www.tailwind-variants.org/docs/tailwind-v4#responsive-variants).\n\n## CVA (class-variance-authority)\n\nAlternative to tailwind-variants: simpler API, no slots.\n\n```typescript\nimport { cva, type VariantProps } from \"class-variance-authority\";\n\nconst buttonVariants = cva(\n  \"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50\",\n  {\n    variants: {\n      variant: {\n        default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n        outline: \"border border-border bg-background hover:bg-accent\",\n        ghost: \"hover:bg-accent hover:text-accent-foreground\",\n      },\n      size: {\n        sm: \"h-9 rounded-md px-3\",\n        default: \"h-10 px-4 py-2\",\n        lg: \"h-11 rounded-md px-8\",\n        icon: \"size-10\",\n      },\n    },\n    defaultVariants: { variant: \"default\", size: \"default\" },\n  }\n);\n\nexport interface ButtonProps\n  extends React.ButtonHTMLAttributes<HTMLButtonElement>,\n    VariantProps<typeof buttonVariants> {}\n\nexport function Button({ className, variant, size, ...props }: ButtonProps) {\n  return <button className={cn(buttonVariants({ variant, size, className }))} {...props} />;\n}\n```\n\n## Compound Components (React 19)\n\nReact 19 passes ref as a regular prop; no `forwardRef` needed.\n\n```typescript\nexport function Card({ className, ref, ...props }: React.HTMLAttributes<HTMLDivElement> & { ref?: React.Ref<HTMLDivElement> }) {\n  return <div ref={ref} className={cn(\"rounded-lg border bg-card text-card-foreground shadow-sm\", className)} {...props} />;\n}\n\nexport function CardHeader({ className, ref, ...props }: React.HTMLAttributes<HTMLDivElement> & { ref?: React.Ref<HTMLDivElement> }) {\n  return <div ref={ref} className={cn(\"flex flex-col space-y-1.5 p-6\", className)} {...props} />;\n}\n```\n\n## ESLint Integration\n\nUse `eslint-plugin-better-tailwindcss` for v4 class validation:\n\n| Rule | Purpose |\n|------|---------|\n| `no-conflicting-classes` | Detect classes that override each other |\n| `no-unknown-classes` | Flag classes not registered with Tailwind |\n| `enforce-shorthand-classes` | `size-6` not `w-6 h-6`; `p-6` not `px-6 py-6` |\n| `no-deprecated-classes` | Catch v3 class names used in v4 projects |\n\nFile v5.0.1:references/tailwind-configuration.md\n\n# Configuration and migration\n\n## CSS-First Configuration\n\nv4 prefers CSS configuration. Legacy JavaScript configuration remains supported through an explicit `@config` directive; v4 does not detect it automatically. Preserve an existing config until its settings and plugins have equivalent verified coverage in CSS or compatibility loading. Check loader support before referencing a TypeScript config. See the [official migration guide](https://tailwindcss.com/docs/upgrade-guide#using-a-javascript-config-file).\n\nFor example, load a supported legacy config using its actual path relative to the stylesheet:\n\n```css\n@config \"../../tailwind.config.js\";\n```\n\nMigrate unsupported legacy options separately: `corePlugins`, `safelist`, and `separator` are not supported through v4 compatibility loading. Use `@source inline()` for a safelist where needed. Verify generated utilities and affected interfaces before removing the old file.\n\n| Directive | Purpose |\n|-----------|---------|\n| `@import \"tailwindcss\"` | Entry point (replaces `@tailwind base/components/utilities`) |\n| `@theme { }` | Define/extend design tokens; auto-generates utility classes |\n| `@theme inline { }` | Map CSS variables to Tailwind utilities without generating new vars |\n| `@theme static { }` | Emit all theme variables, including unused ones; utility generation still applies |\n| `@utility name { }` | Create custom utilities (replaces `@layer components` + `@apply`) |\n| `@custom-variant name (selector)` | Define custom variants |\n\n```css\n@import \"tailwindcss\";\n\n@theme {\n  --color-brand: oklch(0.72 0.11 178);\n  --font-display: \"Inter\", sans-serif;\n  --animate-fade-in: fade-in 0.2s ease-out;\n  @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }\n}\n\n@custom-variant dark (&:where(.dark, .dark *));\n```\n\nTokens defined with `@theme` become utilities automatically: `--color-brand` produces `bg-brand`, `text-brand`, `border-brand`. Define z-index as tokens (`--z-modal: 50`) and reference via `z-(--z-modal)` instead of arbitrary `z-50`. The `oklch()` form above matches how v4 defines its own default palette; lightness is perceptually uniform there, so a scale stepped by L reads evenly, and the `/N` opacity modifier mixes in the same space (`bg-brand/50` compiles to `color-mix(in oklab, var(--color-brand) 50%, transparent)`).\n\n- **Derive alpha variants from one token instead of hand-picking shades**: `--color-brand-soft: color-mix(in oklab, var(--color-brand) 10%, transparent);` inside `@theme` yields a named `bg-brand-soft` that tracks the base token; use it only when a named token must exist (design-system contract, shared across apps), since the `/N` modifier already covers one-off use.\n- **Clear a namespace for a strict design system**: `--color-*: initial;` as the first line of `@theme` removes the entire default palette (no `bg-red-500`, no emitted `--color-red-*` variables), so only the tokens declared after it exist; `--color-lime-*: initial;` drops a single default color, and `--*: initial;` resets every namespace (spacing, fonts, breakpoints) for a fully custom theme.\n\nFor custom properties that should not define Tailwind utilities, declare them in ordinary CSS such as `:root`, outside `@theme`.\n\n**`@theme` tokens are tree-shaken.** v4 emits only the variables it can see used, so a token existing in a shared file says nothing about whether it reaches a given app's bundle. Measured on one shared token file feeding two apps: 20 of 59 `--color-*` emitted into one, 19 of 59 into the other. `@theme static` is the opt-out. A `var(--color-x)` reference inside your own hand-written CSS **counts as a use**, so pointing a custom property at a token (`--app-checkbox-border: var(--color-border-400)`) is self-sustaining, not fragile: Tailwind sees your CSS, not just your class names. Never rate a \"this indirection depends on some unrelated utility still existing\" concern on tree-shaking alone: delete the last utility usage in that app's scan set, rebuild, and read the compiled CSS. Assert the utility actually vanished as the applied control, or a build that silently no-opped (wrong package filter, stale `dist`) reads identically, producing the same false conclusion from nothing.\n\n**CSS Modules**: reference the actual stylesheet that defines the theme, utilities, and variants, for example `@reference \"../../app.css\";` with the path adjusted relative to the module. Use `@reference \"tailwindcss\";` when only the default theme is needed. A package alias such as `#tailwind` works only when that alias is explicitly configured and resolves to the correct stylesheet.\n\n**Animations (tw-animate-css)**: use `animate-in`/`animate-out` base classes combined with effect classes (`fade-in`, `slide-in-from-top`). Decimal spacing gotcha: use bracket notation `[0.625rem]` instead of fractional values like `2.5`.\n\n\n## v3 to v4 Migration\n\nFor projects upgrading from v3 to v4, see [tailwind-v3-to-v4.md](./tailwind-v3-to-v4.md) for the full breaking-change table and codemod guidance. For greenfield v4 work, current patterns are above.\n\n\n## Common Errors\n\n| Symptom | Fix |\n|---------|-----|\n| `bg-primary` doesn't work | Add `@theme inline { --color-primary: var(--primary); }` |\n| Colors all black/white | Double `hsl()` wrapping; use `var(--color)` not `hsl(var(--color))` |\n| `@apply` fails on custom class | Use `@utility` instead of `@layer components` |\n| Build fails after migration | Inspect the build error and config loading; preserve the legacy config until settings/plugins are covered by CSS or supported `@config` loading |\n| Animations broken | Replace `tailwindcss-animate` with `tw-animate-css` |\n| `.dark { @theme { } }` fails | v4 does not support nested `@theme`; use `:root`/`.dark` CSS vars mapped via `@theme inline` |\n\n\n## Dark Mode (v4 Pattern)\n\n```css\n:root { --background: hsl(0 0% 100%); --foreground: hsl(222 84% 4.9%); }\n.dark { --background: hsl(222 84% 4.9%); --foreground: hsl(210 40% 98%); }\n@theme inline { --color-background: var(--background); --color-foreground: var(--foreground); }\n```\n\nSemantic classes (`bg-background`, `text-foreground`) auto-switch; no `dark:` variants needed for themed colors.\n\nFile v5.0.1:references/tailwind-layout-patterns.md\n\n# Layout Patterns\n\n## Grid Template Areas\n\nDefine reusable grid areas with `@utility`:\n\n```css\n@utility grid-areas-dashboard {\n  grid-template-areas: \"header header header\" \"nav main aside\" \"nav footer footer\";\n}\n@utility area-header { grid-area: header; }\n@utility area-nav { grid-area: nav; }\n@utility area-main { grid-area: main; }\n```\n\n```html\n<div class=\"grid grid-areas-dashboard grid-cols-[200px_1fr_250px] grid-rows-[60px_1fr_40px]\">\n  <header class=\"area-header\">Header</header>\n  <nav class=\"area-nav\">Nav</nav>\n  <main class=\"area-main\">Content</main>\n</div>\n```\n\n## Auto-Responsive Grids\n\n```html\n<!-- Auto-fit: cards stretch to fill -->\n<div class=\"grid grid-cols-[repeat(auto-fit,minmax(280px,1fr))] gap-6\">\n\n<!-- Auto-fill: maintains track size, leaves empty space -->\n<div class=\"grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-4\">\n\n<!-- Safe minimum (handles container < minmax min) -->\n<div class=\"grid grid-cols-[repeat(auto-fill,minmax(min(100%,300px),1fr))] gap-4\">\n```\n\n## Z-Index Management\n\nDefine a z-index scale in `@theme` tokens instead of arbitrary numbers:\n\n```css\n@theme {\n  --z-dropdown: 100;\n  --z-sticky: 200;\n  --z-fixed: 300;\n  --z-modal-backdrop: 400;\n  --z-modal: 500;\n  --z-popover: 600;\n  --z-tooltip: 700;\n  --z-toast: 800;\n}\n```\n\nReference with `z-(--z-modal)` syntax; never use `z-[9999]`.\n\n## Container Queries\n\nComponent-level responsiveness independent of viewport. Container queries are built into Tailwind v4; no `@tailwindcss/container-queries` plugin is needed. The separate plugin applies only to compatible Tailwind v3 projects.\n\n```html\n<article class=\"@container\">\n  <div class=\"flex flex-col @sm:flex-row gap-4\">\n    <img class=\"w-full @sm:w-32 @lg:w-48 aspect-video @sm:aspect-square object-cover\" />\n    <div class=\"flex-1 min-w-0\">\n      <h3 class=\"text-base @md:text-lg @lg:text-xl font-semibold truncate\">Title</h3>\n      <p class=\"text-sm @md:text-base line-clamp-2 @lg:line-clamp-3\">Description</p>\n    </div>\n  </div>\n</article>\n```\n\n| Use Container Queries | Use Viewport Queries |\n|----------------------|---------------------|\n| Reusable components | Page-level layouts |\n| Sidebar widgets | Navigation bars |\n| Card grids | Hero sections |\n| Embedded/CMS content | Full-width sections |\n\nNamed containers scope queries: `@container/sidebar` with `@lg/sidebar:flex-row`.\n\n## Fluid Typography\n\nEliminate breakpoint jumps with `clamp()`:\n\n```css\n@theme {\n  --text-fluid-base: clamp(1rem, 0.9rem + 0.5vw, 1.125rem);\n  --text-fluid-xl: clamp(1.25rem, 1rem + 1.25vw, 1.5rem);\n  --text-fluid-3xl: clamp(1.875rem, 1.2rem + 3.375vw, 2.5rem);\n}\n```\n\nAlways combine `vw` with `rem`; pure `vw` breaks when users zoom (WCAG violation).\n\n## Custom Utilities\n\n```css\n@utility scrollbar-none {\n  scrollbar-width: none;\n  -ms-overflow-style: none;\n}\n\n@utility text-gradient {\n  @apply bg-linear-to-r from-primary to-accent bg-clip-text text-transparent;\n}\n```\n\n## Native CSS Animations (v4)\n\nDefine keyframes inside `@theme` and reference with `--animate-*` tokens:\n\n```css\n@theme {\n  --animate-slide-up: slide-up 0.3s ease-out;\n  @keyframes slide-up {\n    from { opacity: 0; transform: translateY(20px); }\n    to { opacity: 1; transform: translateY(0); }\n  }\n}\n```\n\nUse `@starting-style` for entry animations on native popovers/dialogs:\n\n```css\n[popover]:popover-open { opacity: 1; transform: scale(1); }\n@starting-style { [popover]:popover-open { opacity: 0; transform: scale(0.95); } }\n```\n\nRespect motion preferences: `motion-safe:animate-bounce motion-reduce:animate-none`.\n\n## Safe Area Handling (Notched Devices)\n\n```css\n@utility safe-area-pt { padding-top: env(safe-area-inset-top); }\n@utility safe-area-pb { padding-bottom: env(safe-area-inset-bottom); }\n```\n\nApply to fixed headers/footers on mobile.\n\nFile v5.0.1:references/tailwind-v3-to-v4.md\n\n# v3 to v4 Breaking Changes\n\nReference for migrating an existing Tailwind v3 project to v4. For greenfield v4 work, [tailwind.md](./tailwind.md) covers current patterns directly.\n\n| v3 | v4 | Notes |\n|----|-----|-------|\n| Legacy Tailwind config | CSS configuration or explicit `@config` compatibility | Retire the file only after its settings/plugins have verified equivalent coverage; migrate unsupported legacy options separately |\n| `@tailwind base/components/utilities` | `@import \"tailwindcss\"` | Single import |\n| `darkMode: \"class\"` | `@custom-variant dark (...)` | CSS-only |\n| `bg-gradient-to-r` | `bg-linear-to-r` | Also: `bg-radial`, `bg-conic` |\n| `bg-opacity-60` | `bg-red-500/60` | All `*-opacity-*` removed |\n| `rounded-sm` | `rounded-xs` | Radius scale shifted down one step |\n| `rounded` | `rounded-sm` | (run `@tailwindcss/upgrade` codemod) |\n| `rounded-md`, `rounded-lg`, `rounded-xl` | Unchanged | Default radii remain 6px, 8px, and 12px |\n| `min-h-screen` | `min-h-dvh` | `dvh` handles mobile browser chrome |\n| `w-6 h-6` | `size-6` | Size shorthand for equal w/h |\n| `space-x-4` | `gap-4` | Gap handles flex/grid wrapping correctly |\n| `text-base leading-7` | `text-base/7` | Inline line-height modifier |\n| `require(\"tailwindcss-animate\")` | `tw-animate-css` | CSS-only animations |\n| display utility beats `[hidden]` | `[hidden]` beats display utilities | Preflight adds `[hidden]:where(:not([hidden=\"until-found\"])) { display: none !important }`; remove the attribute instead of overriding it |\n\nRun `@tailwindcss/upgrade` codemod before hand-editing; it handles the mechanical class renames. Hand-fix `@theme` migration, custom variants, and any project-specific config patterns the codemod cannot infer.\n\nFile v5.0.1:references/tailwind.md\n\n# Tailwind CSS v4\n\n**Verify before implementing**: For v4-specific syntax (`@theme`, `@variant`, CSS-first config), look up current official docs before writing code. Prefer Context7 (`query-docs`) when available. Otherwise use available web tools to read the [Tailwind CSS docs](https://tailwindcss.com/docs/) for the project's version. Tailwind v4 changed significantly from v3 and training data may be stale.\n\n## Working rules\n\n- Keep utility names as complete source literals and confirm their files are scanned.\n- Use shared design tokens and one consistent visibility mechanism.\n- Inspect generated CSS after source/configuration changes; JSX strings alone do not prove utilities exist.\n- Test scrolling, overlays, and focus behavior in a browser when layout containment changes.\n\n## Coding Rules\n\n- **`gap` over `space-x`/`space-y`**: gap handles wrapping; space-* breaks on wrap\n- **`size-*` over `w-* h-*`** for equal dimensions\n- **`min-h-dvh` over `min-h-screen`**: dvh accounts for mobile browser chrome\n- **Opacity modifier** (`bg-black/50`): `*-opacity-*` utilities are removed in v4\n- **Design tokens over arbitrary values**: check `@theme` before using `[#hex]`\n- **Never construct classes dynamically**: `text-${color}-500` won't be detected; use complete class names\n- **`@utility` over `@apply` with `@layer`**: `@apply` on `@layer` classes fails in v4\n- **Parent padding over last-child margin**: use padding on containers instead of bottom margins on the last child\n- **`overflow-x-auto` makes a scroll container on BOTH axes**: the utility emits only `overflow-x: auto`, but CSS Overflow 3 computes a `visible` value on the other axis to `auto` once either axis is scrollable, so a wrapper added purely to allow horizontal panning silently clips or scrolls whatever overflows it vertically: a non-portalled dropdown, popover, tooltip, custom select, or focus ring. jsdom does no layout, so no unit test catches it; enumerate every component rendered inside the new wrapper and confirm each overlay-ish one escapes it. Portaling is opt-in, not automatic: Radix exposes it as a separate `*.Portal` part wrapping `*.Content`, so read the component rather than assuming a library handles it. Same computed-value rule read backwards: before blaming a page-level scrollbar, walk every ancestor's `overflow` and name the element that actually scrolls\n- **Never express visibility as the native `hidden` attribute plus a display utility**: the two resolve in opposite directions across versions. v4's Preflight ships `[hidden]:where(:not([hidden=\"until-found\"])) { display: none !important }`, so the attribute wins and an element expected to be visible stays hidden; on v3, or wherever Preflight is disabled or not loaded, the author-origin utility (`block`, `flex`, `grid`) beats the UA-origin `[hidden]` rule regardless of specificity and the element stays on screen with `hidden` set. Toggle one mechanism: `clsx(base, open ? 'block' : 'hidden')`. Neither direction is visible to jsdom's `toBeInTheDocument`; only `toBeVisible` or a real browser engine catches it\n\n## Verify\n\n- Build passes with zero errors (`npm run build` or equivalent)\n- No v3 class names remain in changed files (check with `@tailwindcss/upgrade --dry-run` if available)\n- No conflicting classes on the same element\n\n## Task-specific references\n\n- For theme tokens, build configuration, dark mode, or missing styles: [tailwind-configuration.md](./tailwind-configuration.md).\n- For migrating an existing v3 project: [tailwind-v3-to-v4.md](./tailwind-v3-to-v4.md).\n- For class merging, scanning paths, variants, or lint integration: [tailwind-class-composition.md](./tailwind-class-composition.md).\n- For tailwind-variants slots, CVA, or compound components: [tailwind-component-patterns.md](./tailwind-component-patterns.md).\n- For grid areas, container queries, z-index management, or fluid typography: [tailwind-layout-patterns.md](./tailwind-layout-patterns.md).\n\nArchive v5.0.0: 15 files, 32128 bytes\n\nFiles: references/components-and-state.md (9228b), references/e2e-testing.md (6344b), references/rendering-and-frameworks.md (6261b), references/tailwind-class-composition.md (3559b), references/tailwind-component-patterns.md (3428b), references/tailwind-configuration.md (5023b), references/tailwind-layout-patterns.md (3655b), references/tailwind-v3-to-v4.md (1582b), references/tailwind.md (3803b), references/test-selection.md (1547b), references/testing.md (8023b), skill-card.md (1827b), SKILL.md (4288b), SPEC.md (4506b), _meta.json (146b)\n\nFile v5.0.0:SKILL.md\n\n---\nname: ia-react-frontend\nclass: language\ndescription: >-\n  React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when\n  working with React component structure, state management, Next.js routing,\n  Vitest, React Testing Library, or reviewing React code. For visual design and\n  aesthetic direction, use frontend-design instead.\npaths: \"**/*.tsx,**/*.jsx,**/*.ts,**/*.css,**/tailwind.config.*,**/*.html,**/*.vue,**/*.blade.php\"\n---\n\n# React Frontend\n\n**Verify before implementing**: For App Router patterns, React 19 APIs, or version-specific behavior, look up current docs (Context7 `query-docs` if available, else the framework's official docs via web search) before writing code. Training data may lag current releases.\n\n## Working rules\n\n- Keep derived state in render and user actions in event handlers; use effects for external synchronization.\n- Give async work a lifecycle and cancellation policy; represent failure separately from pending and empty data.\n- Preserve focus when hiding interactive regions and exercise keyboard navigation in a real browser.\n- Validate and authorize every public server action; send only needed fields across server/client boundaries.\n- Measure performance changes and test user-visible behavior, not type-checking alone.\n\n## Effects Decision Tree\n\nEffects are escape hatches; most logic should NOT use effects.\n\n| Need | Solution |\n|------|----------|\n| Derived value from props/state | Calculate during render (useMemo if expensive) |\n| Reset state on prop change | `key` prop on component |\n| Respond to user event | Event handler |\n| Notify parent of state change | Call onChange in event handler, or fully controlled component |\n| Chain of state updates | Calculate all next state in one event handler |\n| Sync with external system | Effect with cleanup |\n\n**Effect rules:**\n- Never suppress the linter; fix the code instead\n- Use updater functions (`setItems(prev => [...prev, item])`) to remove state dependencies\n- Move objects/functions inside effects to stabilize dependencies\n- `useEffectEvent` for non-reactive values (e.g., theme in a connection effect)\n- Always return cleanup for subscriptions, connections, listeners\n- Data fetching cancellation (pick by situation): `AbortController` for fetch; `ignore` flag for non-cancellable promises; React Query handles both automatically\n\n\n## Discipline\n\n- Simplicity first: every change as simple as possible, impact minimal code\n- Only touch what's necessary; avoid introducing unrelated changes\n- No hacky workarounds: if a fix feels wrong, step back and implement the clean solution\n- Before adding a new abstraction, verify it appears in 3+ places\n\n\n## References\n\n- [testing.md](./references/testing.md): Component, hook, and mocking test examples\n- [e2e-testing.md](./references/e2e-testing.md): Playwright E2E patterns\n\n\n## Verify\n\n- TypeScript compiles with zero errors\n- No suppressed lint rules (`eslint-disable`, `@ts-ignore`) in new code\n- `useEffect` dependency arrays not manually overridden\n- No `forwardRef` usage in React 19+ projects (use `ref` prop directly)\n\n## Task-specific references\n\nRead the relevant reference before implementing or reviewing the matching behavior:\n\n- For component types, state ownership, async races, focus, or cached query behavior: [components-and-state.md](./references/components-and-state.md).\n- For performance, React APIs, Next.js boundaries, or caching: [rendering-and-frameworks.md](./references/rendering-and-frameworks.md).\n- For Tailwind CSS: utilities, `@theme` tokens, CVA/tailwind-variants, dark mode, v3-to-v4 migration, or overflow and `hidden` pitfalls: [tailwind.md](./references/tailwind.md).\n- For component, hook, browser, or integration test changes: [test-selection.md](./references/test-selection.md).\n\nExisting specialized references, when the corresponding topic applies:\n\n- Tailwind details behind [tailwind.md](./references/tailwind.md): [tailwind-configuration.md](./references/tailwind-configuration.md), [tailwind-v3-to-v4.md](./references/tailwind-v3-to-v4.md), [tailwind-class-composition.md](./references/tailwind-class-composition.md), [tailwind-component-patterns.md](./references/tailwind-component-patterns.md), [tailwind-layout-patterns.md](./references/tailwind-layout-patterns.md).\n\nFile v5.0.0:_meta.json\n\n{\n  \"ownerId\": \"kn715jrbbh71q9zncr0bqdkr8n848q1a\",\n  \"slug\": \"compound-eng-react-frontend\",\n  \"version\": \"5.0.0\",\n  \"publishedAt\": 1790464788089\n}\n\nFile v5.0.0:references/components-and-state.md\n\n# Components, state, and interaction\n\n## Component TypeScript\n\n- Extend native elements with `ComponentPropsWithoutRef<'button'>`, add custom props via intersection\n- Use `React.ReactNode` for children, `React.ReactElement` for single element, render prop `(data: T) => ReactNode`\n- Discriminated unions for variant props; TypeScript narrows automatically in branches\n- Generic components: `<T>` with `keyof T` for column keys, `T extends { id: string }` for constraints\n- Event types: `React.MouseEvent<HTMLButtonElement>`, `FormEvent<HTMLFormElement>`, `ChangeEvent<HTMLInputElement>`\n- `as const` for custom hook tuple returns\n- `useRef<HTMLInputElement>(null)` for DOM (use `?.`), `useRef<number>(0)` for mutable values\n- Explicit `useState<User | null>(null)` for unions/null\n- useReducer actions as discriminated unions: `{ type: 'set'; payload: number } | { type: 'reset' }`\n- useContext null guard: throw in custom `useX()` hook if context is null\n- **A parameter type whose properties are all optional is a weak type, and a mismatched argument fails to compile rather than passing `undefined`.** TypeScript requires the argument to share at least one property with a weak type, so `(record: { newField?: boolean })` rejects a generated type that does not yet carry `newField` with `TS2559: Type 'X' has no properties in common with type 'Y'`. Intersect with the base type instead (`T & { newField?: boolean }`); the shim then deletes cleanly once the field lands upstream\n\n\n## Concurrency & Race Classes\n\nFive race classes survive type-checking and unit tests; hunt each one during review (cleanup/cancellation mechanics: Effect rules above):\n\n| Class | Production signal | Fix |\n|-------|-------------------|-----|\n| Lifecycle cleanup gap | \"state update on unmounted component\" warnings, leaks under rapid navigation | Return cleanup from every effect that registers a listener/timer/observer |\n| Remount-timing mistake | Async callback mutates state/DOM after route change/unmount (`fetch().then(setData)` resolves post-navigation) | Cancel per the cancellation hierarchy |\n| Boolean-as-state for non-binary UI | Contradictory combos (`isLoading: true, error: Error`) | State constant (`'idle' \\| 'loading' \\| 'success' \\| 'error'`) + transition function; invalid states unreachable |\n| Stale promise/timer, no cancel path | Promise chain or `setTimeout` holds `setState` after the component moved on | Bind every async op to a cancel mechanism; test the cleanup path |\n| Per-element handlers on large lists | N closures/subscriptions per row, stale-closure bugs on rapid re-renders | Delegate: one parent handler + `event.target.closest(...)` when >~50 items or frequent updates |\n| Gate keyed on a child's success-only callback | Parent's submit stays locked behind \"still loading, try again in a moment\" copy that never resolves; only a page reload escapes | Report failures up (`onLoadError`) as well as successes, and split the flag into loading / loaded / failed; a boolean cannot carry a terminal state. Keep the action blocked in both if proceeding on unknown data is unsafe; the fix is honest copy plus a real in-place retry, not unblocking |\n| `inert` toggled from a blur-managed flag | First `Tab` *inside* the subtree sends focus to `<body>`; the next `Tab` restarts at the top of the document and skips the (now inert) subtree entirely | React maps `onBlur` to native `focusout`, which fires on intra-subtree moves, and `focusin`/`focusout` are `DiscreteEventPriority`, so React commits `inert` synchronously *between* the two events, landing it on the already-focused incoming control. Stand down only when focus truly leaves: `if (e.currentTarget.contains(e.relatedTarget)) return;` |\n\n**Focus-ownership rules:**\n- Never toggle `inert` on a subtree that currently holds focus. The blunt version has no guard at all: a scroll-driven `inert={!isVisible}` on a sticky bar, drawer, or collapsing panel strands the user on a control that is invisible, inert, and unactivatable. Hand focus to the equivalent visible control before hiding, and pass `focus({ preventScroll: true })` when the handoff fires from a scroll handler, or `focus()` scrolls its target into view and fights the scroll the user is performing. If the handoff target carries the same focus listeners that feed the guard, `focus()` arms the flag as a side effect of doing its job and the subtree never goes inert again; make the handoff symmetric (two effects guarding opposite values of one flag) rather than adding an exception to the guard. `aria-hidden` without `inert` fixes double announcement but leaves the duplicate tab stops. Assert on what the user can *do* (does the handler fire, where does `Tab` go), not on `document.activeElement`; Chromium resolves the unfocusing steps lazily and it reads back inconsistently\n- A blur-managed \"focus is inside\" flag cannot be cleared by a blur that never fires. Headless popover primitives restore focus to the element that *opened* the content on close; when the popover is anchored to an input with no trigger element, that restore no-ops, the library preventDefaults the focus-scope restore, and focus lands on `document.body`. The input never receives another `blur`, so the flag sticks `true` for the component's lifetime and anything gated on it (a \"re-seed local text from `props.value`\" effect, for instance) is silently dead. Clear it explicitly in the select handler and on close when `document.activeElement` is not the input. The same design usually adds `onOpenAutoFocus={e => e.preventDefault()}` to avoid stealing typing focus, which leaves the content pointer-only: no trigger to Tab to and no auto-focus in. Add an explicit affordance plus `aria-haspopup`/`aria-expanded`. Browser-dependent: Chromium and Firefox blur the input on `mousedown`, Safari does not, so \"works on my machine\" from Safari proves nothing\n\n\n## State Management\n\n```\nLocal UI state       → useState, useReducer\nShared client state  → Zustand (simple) | Redux Toolkit (complex)\nAtomic/granular      → Jotai\nServer/remote data   → React Query (TanStack Query)\nURL state            → nuqs, router search params\nForm state           → React Hook Form\n```\n\n**Key patterns:**\n- Zustand: `create<State>()(devtools(persist((set) => ({...}))))`; use slices for scale, selective subscriptions to prevent re-renders\n- React Query: query keys factory (`['users', 'detail', id] as const`), `staleTime`/`gcTime`, optimistic updates with `onMutate`/`onError` rollback\n- React Query `isError` means *a fetch failed*, not *there is no data*: a failed refetch sets `status: 'error'` while retaining the last successful payload, so the usual `isLoading ? spinner : isError ? errorPanel : content` ladder routes a working, fully cached list into the error panel. The defaults compose into it: `refetchOnMount: true` + `staleTime: 0` refetch on every mount, `retry: false` makes one blip terminal, and `gcTime: 5min` keeps the cache alive across a modal's unmount/remount. Gate the branch on data-absence: `isLoadingError` (`isError && !hasData`), or `isError && derived.length === 0` when the suite mocks the hook and leaves `isLoadingError` undefined. Audit the side effects with it: `useEffect(() => { if (isError) toast(...) }, [isError])` fires over the live list too\n- The mirror case has the same tell: under `retry: false` a first load that fails leaves `data` `undefined` forever, so a branch gated on `data !== undefined` folds *failed* into *pending* and renders \"Loading…\" permanently. Whether it is recoverable is decided by mount topology, not by open/closed state: a component rendered unconditionally inside a ref-driven popup is mounted for the life of the page, so `refetchOnMount` never fires again. Any remedy that adds a branch on `isError` must itself be gated on data-absence, or it re-introduces the previous bullet. Enumerate all four states before writing either gate (`isLoading` for first load with no data yet, `isFetching` for any fetch in flight including a background refetch over a warm cache, `isError` for last fetch failed with cache possibly still present, and loaded-and-genuinely-empty) and state the action in each: `!isFetching` misses the error state, `!isFetching && !isError` mishandles a background refetch of a legitimately empty result. The write path has the same shape, inverted: a fail-closed save gate keyed on `isError` blocks a valid submit whenever cached data is present\n- A mutate-scoped `onSuccess` survives an unmount that the mutation itself caused, so \"the success toast is dropped on promote/archive/delete\" is usually a false finding. The mutation dispatches success on the microtask after the hook-level `onSuccess` await resolves, while query-observer notifications (the ones that re-render the list and unmount the row) flush on a zero-delay timer; that is an ordering guarantee, not a race. The documented \"callbacks do not fire on unmount\" caveat describes a different unmount (navigation, closing a drawer). Read the scheduler and run a known-bad control (remove the observer before dispatch) before accepting the finding\n- Never duplicate server data (React Query) in a client store (Zustand)\n- Colocate state close to where it's used\n\nFile v5.0.0:references/e2e-testing.md\n\n# E2E Testing with Playwright\n\n> When to read: when authoring Playwright end-to-end tests: directory layout, fixtures, page objects, network mocking, CI integration.\n\n## Directory Structure\n\n```\ne2e/\n├── playwright.config.ts\n├── fixtures/\n│   ├── auth.fixture.ts\n│   └── test-data.fixture.ts\n├── pages/\n│   ├── base.page.ts\n│   └── <page-name>.page.ts\n├── tests/\n│   ├── auth/\n│   │   └── login.spec.ts\n│   └── smoke/\n│       └── critical-paths.spec.ts\n└── utils/\n    └── api-helpers.ts\n```\n\nNaming: tests `<feature>.spec.ts`, page objects `<page>.page.ts`, fixtures `<concern>.fixture.ts`.\n\n## Configuration\n\n```typescript\nimport { defineConfig, devices } from '@playwright/test';\n\nexport default defineConfig({\n  testDir: './e2e/tests',\n  fullyParallel: true,\n  forbidOnly: !!process.env.CI,\n  retries: process.env.CI ? 2 : 0,\n  workers: process.env.CI ? 1 : undefined,\n  reporter: 'html',\n  use: {\n    baseURL: 'http://localhost:5173',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n  },\n  projects: [\n    { name: 'setup', testDir: './e2e/fixtures', testMatch: 'auth.fixture.ts' },\n    {\n      name: 'chromium',\n      use: { ...devices['Desktop Chrome'], storageState: 'e2e/.auth/user.json' },\n      dependencies: ['setup'],\n    },\n  ],\n  webServer: {\n    command: 'npm run dev',\n    url: 'http://localhost:5173',\n    reuseExistingServer: !process.env.CI,\n  },\n});\n```\n\n## Page Object Model\n\nTests never use selectors directly; page objects encapsulate all locators and actions.\n\n```typescript\n// e2e/pages/base.page.ts\nimport { type Page, type Locator } from '@playwright/test';\n\nexport abstract class BasePage {\n  constructor(protected readonly page: Page) {}\n  abstract goto(): Promise<void>;\n  abstract readonly ready: Locator;\n  async waitForLoad() { await this.ready.waitFor(); }\n  get toast(): Locator { return this.page.getByRole('alert'); }\n}\n\n// e2e/pages/users.page.ts\nexport class UsersPage extends BasePage {\n  readonly ready: Locator;\n  readonly createButton: Locator;\n  readonly searchInput: Locator;\n\n  constructor(page: Page) {\n    super(page);\n    this.ready = page.getByRole('heading', { name: /users/i });\n    this.createButton = page.getByRole('button', { name: /create/i });\n    this.searchInput = page.getByRole('searchbox', { name: /search/i });\n  }\n\n  async goto() {\n    await this.page.goto('/users');\n    await this.waitForLoad();\n  }\n\n  async searchFor(query: string) {\n    const resp = this.page.waitForResponse('**/api/users?*');\n    await this.searchInput.fill(query);\n    await resp;\n  }\n}\n```\n\nRules: locators as public readonly properties, actions as async methods with internal waits, no assertions in page objects, one PO per page.\n\n## Selector Priority\n\n| Priority | Method | Use when |\n|----------|--------|----------|\n| 1 | `getByRole` | Buttons, links, headings, inputs |\n| 2 | `getByLabel` | Form inputs with labels |\n| 3 | `getByPlaceholder` | Search inputs |\n| 4 | `getByText` | Static text content |\n| 5 | `getByTestId` | No accessible selector available |\n\nNever use CSS selectors, XPath, or DOM structure selectors. When adding `data-testid`, use `<action>-<entity>-<type>` pattern: `create-user-btn`.\n\n## Filling Inputs\n\nPrefer `locator.fill(value)` to `page.keyboard.type()`. Synthesised keystrokes drop characters intermittently under a browser-attached session (CDP against an already-running browser), and the driver reports the full string as typed while the DOM holds a short value, so the assertion that would catch it is the one nobody writes. Rich-text editors whose state lives outside the element's `value` (ProseMirror, Slate, TipTap) ignore programmatic writes and still need `type()`; there, assert `input_value()` (or the editor's own serialized content) after typing and retry on a short read.\n\n## Wait Strategies\n\nNever use `waitForTimeout` or `setTimeout`. Do not use `waitForLoadState('networkidle')` as a readiness signal; Playwright's API docs mark it discouraged for testing and point to web assertions instead. Start a `waitForResponse` before the action that triggers the request, or a fast response is missed. Use explicit conditions:\n\n```typescript\nawait page.getByRole('heading', { name: 'Dashboard' }).waitFor();\nawait page.waitForURL('/dashboard');\nconst resp = page.waitForResponse(\n  (r) => r.url().includes('/api/users') && r.status() === 200,\n);\nawait page.getByRole('button', { name: /load/i }).click();\nawait resp;\nawait page.getByTestId('spinner').waitFor({ state: 'hidden' });\n```\n\n## Auth State Reuse\n\nSave auth state once, reuse across all tests:\n\n```typescript\n// e2e/fixtures/auth.fixture.ts\nimport { test as setup } from '@playwright/test';\n\nsetup('authenticate', async ({ page }) => {\n  await page.goto('/login');\n  await page.getByLabel('Email').fill('testuser@example.com');\n  await page.getByLabel('Password').fill('TestPassword123!');\n  await page.getByRole('button', { name: /sign in/i }).click();\n  await page.waitForURL('/dashboard');\n  await page.context().storageState({ path: 'e2e/.auth/user.json' });\n});\n```\n\nTests receive auth state via `storageState` in config projects.\n\n## Test Data & Network\n\n- Tests create own data via API helpers (faster than UI), clean up in `finally` blocks\n- Mock responses with `page.route('**/api/path', route => route.fulfill({ ... }))`\n- Simulate errors with `route.abort('failed')`\n\n## Flaky Test Fixes\n\n| Cause | Fix |\n|-------|-----|\n| Hardcoded waits | Explicit wait conditions |\n| Shared test data | Each test creates its own |\n| Animations | `animations: 'disabled'` in config |\n| Race conditions | Wait for API responses before assertions |\n\n**Quarantine workflow**: confirm flakiness before quarantining:\n```bash\nnpx playwright test --repeat-each=10 path/to/test.spec.ts  # Confirm flakiness\nnpx playwright test --retries=3 path/to/test.spec.ts       # Check if retries help\n```\n\nMark confirmed flaky tests with an issue reference:\n```typescript\ntest.fixme(true, 'Flaky - Issue #123');                       // Always skip\ntest.skip(!!process.env.CI, 'Flaky in CI only - Issue #123'); // Skip in CI only\n```\n\n```bash\nnpx playwright test --headed --debug  # Debug mode\nnpx playwright show-trace trace.zip   # Trace viewer\nnpx playwright test --ui              # Interactive UI\n```\n\nFile v5.0.0:references/rendering-and-frameworks.md\n\n# Rendering and framework patterns\n\n## Performance\n\n**Critical: eliminate waterfalls:**\n- `Promise.all()` for independent async operations\n- Move `await` into branches where actually needed\n- Suspense boundaries to stream slow content\n\n**Critical: bundle size:**\n- Import directly from modules, avoid barrel files (`index.ts` re-exports)\n- `next/dynamic` or `React.lazy()` for heavy components\n- Defer third-party scripts (analytics, logging) until after hydration\n- Preload on hover/focus for perceived speed\n- `content-visibility: auto` + `contain-intrinsic-size` on long lists skips off-screen layout/paint\n\n**Re-render optimization:**\n- Never define a component inside another component. Each parent render creates a new function identity, and React compares element *types* to decide whether to update or replace: a new type means the whole subtree unmounts and remounts, so local state is lost, effects re-run, and DOM nodes are recreated. Symptoms are behavioral, not slow: an input loses focus on every keystroke, animations restart, scroll position resets. Hoist the component to module scope and pass what it needed via props. The React Compiler does not save this one; the type identity changes before memoization applies\n- Derive state during render, not in effects\n- Subscribe to derived booleans, not raw objects (`state.items.length > 0` not `state.items`)\n- Functional setState for stable callbacks: `setCount(c => c + 1)`\n- Lazy state init: `useState(() => expensiveComputation())`\n- `useTransition` for non-urgent updates (search filtering)\n- `useDeferredValue` for expensive derived UI\n- Don't subscribe to searchParams/state read only in callbacks; read on demand\n- Use ternary (`condition ? <A /> : <B />`), not `&&` for conditionals\n- `React.memo` only for expensive subtrees with stable props\n- Hoist static JSX outside components\n\n**React Compiler** (React 19): auto-memoizes, so write idiomatic React and remove manual `useMemo`/`useCallback`/`memo`. Enable via `reactCompiler: true` in next.config (non-framework: `babel-plugin-react-compiler`). Keep components pure.\n\n\n## React 19\n\n- **ref as prop**: `forwardRef` deprecated. Accept `ref?: React.Ref<HTMLElement>` as regular prop\n- **useActionState**: replaces `useFormState`: `const [state, formAction, isPending] = useActionState(action, initialState)`\n- **use()**: unwrap Promise or Context during render (not in callbacks/effects). Enables conditional context reads\n- **useOptimistic**: `const [optimistic, addOptimistic] = useOptimistic(state, mergeFn)` for instant UI feedback\n- **useFormStatus**: `const { pending } = useFormStatus()` in child of `<form action={...}>`\n- **Server Components**: default in App Router. Async, access DB/secrets directly. No hooks, no event handlers\n- **Server Actions**: `'use server'` directive. Validate inputs (Zod), `revalidateTag`/`revalidatePath` after mutations. **Server Actions are public endpoints**; always verify auth/authz inside each action, not just in middleware or layout guards\n- **`<Activity mode='visible'|'hidden'>`** preserves state/DOM for toggled components (experimental)\n\n\n## Next.js App Router\n\n**File conventions:** `page.tsx` (route UI), `layout.tsx` (shared wrapper), `template.tsx` (re-mounted on navigation, unlike layout), `loading.tsx` (Suspense), `error.tsx` (error boundary), `not-found.tsx` (404), `default.tsx` (parallel route fallback), `route.ts` (API endpoint)\n\n**Rendering modes:** Server Components (default) | Client (`'use client'`) | Static (build) | Dynamic (request) | Streaming (progressive)\n\n**Decision:** Server Component unless it needs hooks, event handlers, or browser APIs. Split: server parent + client child. Isolate interactive components as `'use client'` leaf components; keep server components static with no global state or event handlers.\n\n**Server → client boundary:** pass only the fields a client component actually uses, not whole ORM rows or fetch objects. Every prop crossing the `'use client'` boundary is serialized into the payload, so a 50-field `user` object read for one field still ships all 50.\n\n**Client-only state that drives first paint** (theme, locale, feature flag, auth hint): reading `localStorage` during render breaks SSR, and reading it in `useEffect` paints the default first, so the correct value arrives one frame later as a visible flash. Set the value on the document with a small synchronous inline script that runs before hydration, typically writing a `class` or `data-` attribute on `<html>` that CSS already keys on. The script is developer-authored and must never interpolate user, request, or database data; it is the one place `dangerouslySetInnerHTML` is warranted, and only for a literal string.\n\n**Routing patterns:**\n- Route groups `(name)`: organize without affecting URL\n- Parallel routes `@slot`: independent loading states in same layout\n- Intercepting routes `(.)`: modal overlays with full-page fallback\n\n**Caching:**\n- `fetch(url, { cache: 'force-cache' })`: static\n- `fetch(url, { next: { revalidate: 60 } })`: ISR\n- `fetch(url, { cache: 'no-store' })`: dynamic\n- Tag-based: `fetch(url, { next: { tags: ['products'] } })` then `revalidateTag('products')`\n\n**Data fetching:**\n- Fetch in Server Components where data is used\n- Use Suspense boundaries for slow queries\n- `React.cache()` for per-request dedup\n- `generateStaticParams` for static generation\n- `generateMetadata` for dynamic SEO\n- Static metadata with `title: { default: 'App', template: '%s | App' }` for cascading page titles\n- `after()` for non-blocking side effects (logging, analytics); runs after response is sent\n- Hoist static I/O (fonts, config) to module level; runs once, not per request\n- Never hold request-scoped or user data in module-level mutable state: server renders run concurrently in one process, so shared module state leaks across requests (one user's data surfacing in another's response). Hoist only immutable static I/O; keep request data local to the render tree (pass as props)\n\n\n## Tailwind Integration\n\nFor Tailwind v4 configuration, utility patterns, dark mode, and component variants, see [tailwind.md](./tailwind.md).\n\n**Class sorting in JSX**: keep Tailwind classes in canonical order (enforce via `eslint-plugin-better-tailwindcss`).\n\nFile v5.0.0:references/tailwind-class-composition.md\n\n# Class generation and composition\n\n## ESLint Integration\n\nUse `eslint-plugin-better-tailwindcss` for automated class validation:\n- `no-conflicting-classes`: catches `text-red-500 text-blue-500`\n- `no-unknown-classes`: flags typos\n- `enforce-canonical-classes`: normalizes shorthand\n- `no-duplicate-classes`: removes redundant entries\n- `no-deprecated-classes`: catches v3 classes removed in v4\n- `useSortedClasses`: enforces canonical class order; configure `attributes: [\"classList\"]` and `functions: [\"clsx\", \"cva\", \"cn\", \"tv\", \"tw\"]` to cover JSX utility functions\n\n\n## Class Merging\n\nUse `cn()` combining `clsx` + `tailwind-merge` for conditional/dynamic classes. Use plain strings for static `className` attributes.\n\n```typescript\nimport { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\nexport function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }\n```\n\n```typescript\n// Static: plain string\n<button className=\"rounded-lg px-4 py-2 font-medium bg-blue-600\">\n\n// Conditional: use cn()\n<button className={cn(\"rounded-lg px-4 py-2\", isActive ? \"bg-blue-600\" : \"bg-gray-700\")} />\n```\n\n**Keep class names whole in the source.** The example above works because both branches are complete literals. Tailwind's scanner does literal string matching over source text and never evaluates JavaScript, so a class assembled by interpolation is invisible to it and the utility is simply never generated. The failure is silent: no error, no warning, just missing styles.\n\n```typescript\n// Broken: `bg-red-500` never appears in the source, so it is never generated\n<div className={`bg-${color}-500`} />\n\n// Works: every candidate class is a complete literal the scanner can see\nconst BG = { red: \"bg-red-500\", blue: \"bg-blue-500\" } as const;\n\nfunction Swatch({ color }: { color: keyof typeof BG }) {\n  return <div className={BG[color]} />;\n}\n```\n\nThe same applies to classes built in a non-scanned location (a string in a database, a CMS field, or a file outside the configured `@source` paths). Confirm the source actually gets scanned before assuming a literal is enough.\n\n`@source` directives resolve relative to the file they appear in, so a shared token package pulling in a sibling (`@source '../../ui/src/**/*.{ts,tsx}'`) is what makes a `libs/ui`-only utility generate in every consuming app. The real generation risk is a utility with **no** prior usage anywhere, and it fails invisibly rather than loudly: an SVG whose root carries `fill=\"none\"` and whose paths swap `fill=\"#355BF5\"` for `className=\"fill-primary-500\"` renders *invisible*, not mis-colored. Grep the compiled CSS of every consuming app, not one.\n\nVerify by building, not by reading: when class names or scanned sources changed, run the real Tailwind build and grep the output CSS for the expected utilities. Reviewing the `className` attribute proves the string is right, not that the rule exists.\n\n\n## Component Variants\n\nUse `tailwind-variants` (`tv()`) for type-safe variant components. Alternative: `class-variance-authority` (`cva()`).\n\n```typescript\nimport { tv } from \"tailwind-variants\";\nconst button = tv({\n  base: \"rounded-lg px-4 py-2 font-medium transition-colors\",\n  variants: {\n    color: { primary: \"bg-blue-600 text-white\", secondary: \"bg-gray-200 text-gray-800\" },\n    size: { sm: \"text-sm px-3 py-1\", md: \"text-base\", lg: \"text-lg px-6 py-3\" },\n  },\n  defaultVariants: { color: \"primary\", size: \"md\" },\n});\n```\n\nSee [tailwind-variants patterns](./tailwind-component-patterns.md) for slots, composition, and responsive variants.\n\nFile v5.0.0:references/tailwind-component-patterns.md\n\n# Component Patterns\n\n## tailwind-variants (tv)\n\nType-safe component variants with slots, composition, and responsive support.\n\n### Slots API\n\n```typescript\nimport { tv } from \"tailwind-variants\";\n\nconst card = tv({\n  slots: {\n    base: \"rounded-lg border shadow-sm\",\n    header: \"flex flex-col space-y-1.5 p-6\",\n    title: \"text-2xl font-semibold leading-none tracking-tight\",\n    content: \"p-6 pt-0\",\n    footer: \"flex items-center p-6 pt-0\",\n  },\n  variants: {\n    elevated: { true: { base: \"shadow-lg border-0\" } },\n  },\n});\n\nconst { base, header, title, content, footer } = card({ elevated: true });\n```\n\n### Composition\n\n```typescript\nconst baseButton = tv({ base: \"rounded-lg font-medium transition-colors\" });\n\nconst iconButton = tv({\n  extend: baseButton,\n  base: \"inline-flex items-center justify-center\",\n  variants: {\n    size: { sm: \"size-8\", md: \"size-10\", lg: \"size-12\" },\n  },\n});\n```\n\n### Responsive Variants\n\n```typescript\nconst grid = tv({\n  base: \"grid gap-4\",\n  variants: {\n    cols: { 1: \"grid-cols-1\", 2: \"grid-cols-2\", 3: \"grid-cols-3\", 4: \"grid-cols-4\" },\n  },\n  responsiveVariants: [\"sm\", \"md\", \"lg\"],\n});\n\n// Usage: <div className={grid({ cols: { initial: 1, sm: 2, lg: 4 } })} />\n```\n\n## CVA (class-variance-authority)\n\nAlternative to tailwind-variants: simpler API, no slots.\n\n```typescript\nimport { cva, type VariantProps } from \"class-variance-authority\";\n\nconst buttonVariants = cva(\n  \"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50\",\n  {\n    variants: {\n      variant: {\n        default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n        outline: \"border border-border bg-background hover:bg-accent\",\n        ghost: \"hover:bg-accent hover:text-accent-foreground\",\n      },\n      size: {\n        sm: \"h-9 rounded-md px-3\",\n        default: \"h-10 px-4 py-2\",\n        lg: \"h-11 rounded-md px-8\",\n        icon: \"size-10\",\n      },\n    },\n    defaultVariants: { variant: \"default\", size: \"default\" },\n  }\n);\n\nexport interface ButtonProps\n  extends React.ButtonHTMLAttributes<HTMLButtonElement>,\n    VariantProps<typeof buttonVariants> {}\n\nexport function Button({ className, variant, size, ...props }: ButtonProps) {\n  return <button className={cn(buttonVariants({ variant, size, className }))} {...props} />;\n}\n```\n\n## Compound Components (React 19)\n\nReact 19 passes ref as a regular prop; no `forwardRef` needed.\n\n```typescript\nexport function Card({ className, ref, ...props }: React.HTMLAttributes<HTMLDivElement> & { ref?: React.Ref<HTMLDivElement> }) {\n  return <div ref={ref} className={cn(\"rounded-lg border bg-card text-card-foreground shadow-sm\", className)} {...props} />;\n}\n\nexport function CardHeader({ className, ref, ...props }: React.HTMLAttributes<HTMLDivElement> & { ref?: React.Ref<HTMLDivElement> }) {\n  return <div ref={ref} className={cn(\"flex flex-col space-y-1.5 p-6\", className)} {...props} />;\n}\n```\n\n## ESLint Integration\n\nUse `eslint-plugin-better-tailwindcss` for v4 class validation:\n\n| Rule | Purpose |\n|------|---------|\n| `no-conflicting-classes` | Detect classes that override each other |\n| `no-unknown-classes` | Flag classes not registered with Tailwind |\n| `enforce-shorthand-classes` | `size-6` not `w-6 h-6`; `p-6` not `px-6 py-6` |\n| `no-deprecated-classes` | Catch v3 class names used in v4 projects |\n\nFile v5.0.0:references/tailwind-configuration.md\n\n# Configuration and migration\n\n## CSS-First Configuration\n\nv4 eliminates `tailwind.config.ts`. All configuration lives in CSS.\n\n| Directive | Purpose |\n|-----------|---------|\n| `@import \"tailwindcss\"` | Entry point (replaces `@tailwind base/components/utilities`) |\n| `@theme { }` | Define/extend design tokens; auto-generates utility classes |\n| `@theme inline { }` | Map CSS variables to Tailwind utilities without generating new vars |\n| `@theme static { }` | Emit all theme variables, including unused ones; utility generation still applies |\n| `@utility name { }` | Create custom utilities (replaces `@layer components` + `@apply`) |\n| `@custom-variant name (selector)` | Define custom variants |\n\n```css\n@import \"tailwindcss\";\n\n@theme {\n  --color-brand: oklch(0.72 0.11 178);\n  --font-display: \"Inter\", sans-serif;\n  --animate-fade-in: fade-in 0.2s ease-out;\n  @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }\n}\n\n@custom-variant dark (&:where(.dark, .dark *));\n```\n\nTokens defined with `@theme` become utilities automatically: `--color-brand` produces `bg-brand`, `text-brand`, `border-brand`. Define z-index as tokens (`--z-modal: 50`) and reference via `z-(--z-modal)` instead of arbitrary `z-50`. The `oklch()` form above matches how v4 defines its own default palette; lightness is perceptually uniform there, so a scale stepped by L reads evenly, and the `/N` opacity modifier mixes in the same space (`bg-brand/50` compiles to `color-mix(in oklab, var(--color-brand) 50%, transparent)`).\n\n- **Derive alpha variants from one token instead of hand-picking shades**: `--color-brand-soft: color-mix(in oklab, var(--color-brand) 10%, transparent);` inside `@theme` yields a named `bg-brand-soft` that tracks the base token; use it only when a named token must exist (design-system contract, shared across apps), since the `/N` modifier already covers one-off use.\n- **Clear a namespace for a strict design system**: `--color-*: initial;` as the first line of `@theme` removes the entire default palette (no `bg-red-500`, no emitted `--color-red-*` variables), so only the tokens declared after it exist; `--color-lime-*: initial;` drops a single default color, and `--*: initial;` resets every namespace (spacing, fonts, breakpoints) for a fully custom theme.\n\nFor custom properties that should not define Tailwind utilities, declare them in ordinary CSS such as `:root`, outside `@theme`.\n\n**`@theme` tokens are tree-shaken.** v4 emits only the variables it can see used, so a token existing in a shared file says nothing about whether it reaches a given app's bundle. Measured on one shared token file feeding two apps: 20 of 59 `--color-*` emitted into one, 19 of 59 into the other. `@theme static` is the opt-out. A `var(--color-x)` reference inside your own hand-written CSS **counts as a use**, so pointing a custom property at a token (`--app-checkbox-border: var(--color-border-400)`) is self-sustaining, not fragile: Tailwind sees your CSS, not just your class names. Never rate a \"this indirection depends on some unrelated utility still existing\" concern on tree-shaking alone: delete the last utility usage in that app's scan set, rebuild, and read the compiled CSS. Assert the utility actually vanished as the applied control, or a build that silently no-opped (wrong package filter, stale `dist`) reads identically, producing the same false conclusion from nothing.\n\n**CSS Modules**: when using `.module.css` with Tailwind v4, add `@reference \"#tailwind\";` at the top of the module file to enable theme token access inside the module.\n\n**Animations (tw-animate-css)**: use `animate-in`/`animate-out` base classes combined with effect classes (`fade-in`, `slide-in-from-top`). Decimal spacing gotcha: use bracket notation `[0.625rem]` instead of fractional values like `2.5`.\n\n\n## v3 to v4 Migration\n\nFor projects upgrading from v3 to v4, see [tailwind-v3-to-v4.md](./tailwind-v3-to-v4.md) for the full breaking-change table and codemod guidance. For greenfield v4 work, current patterns are above.\n\n\n## Common Errors\n\n| Symptom | Fix |\n|---------|-----|\n| `bg-primary` doesn't work | Add `@theme inline { --color-primary: var(--primary); }` |\n| Colors all black/white | Double `hsl()` wrapping; use `var(--color)` not `hsl(var(--color))` |\n| `@apply` fails on custom class | Use `@utility` instead of `@layer components` |\n| Build fails after migration | Delete `tailwind.config.ts` |\n| Animations broken | Replace `tailwindcss-animate` with `tw-animate-css` |\n| `.dark { @theme { } }` fails | v4 does not support nested `@theme`; use `:root`/`.dark` CSS vars mapped via `@theme inline` |\n\n\n## Dark Mode (v4 Pattern)\n\n```css\n:root { --background: hsl(0 0% 100%); --foreground: hsl(222 84% 4.9%); }\n.dark { --background: hsl(222 84% 4.9%); --foreground: hsl(210 40% 98%); }\n@theme inline { --color-background: var(--background); --color-foreground: var(--foreground); }\n```\n\nSemantic classes (`bg-background`, `text-foreground`) auto-switch; no `dark:` variants needed for themed colors.\n\nFile v5.0.0:references/tailwind-layout-patterns.md\n\n# Layout Patterns\n\n## Grid Template Areas\n\nDefine reusable grid areas with `@utility`:\n\n```css\n@utility grid-areas-dashboard {\n  grid-template-areas: \"header header header\" \"nav main aside\" \"nav footer footer\";\n}\n@utility area-header { grid-area: header; }\n@utility area-nav { grid-area: nav; }\n@utility area-main { grid-area: main; }\n```\n\n```html\n<div class=\"grid grid-areas-dashboard grid-cols-[200px_1fr_250px] grid-rows-[60px_1fr_40px]\">\n  <header class=\"area-header\">Header</header>\n  <nav class=\"area-nav\">Nav</nav>\n  <main class=\"area-main\">Content</main>\n</div>\n```\n\n## Auto-Responsive Grids\n\n```html\n<!-- Auto-fit: cards stretch to fill -->\n<div class=\"grid grid-cols-[repeat(auto-fit,minmax(280px,1fr))] gap-6\">\n\n<!-- Auto-fill: maintains track size, leaves empty space -->\n<div class=\"grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-4\">\n\n<!-- Safe minimum (handles container < minmax min) -->\n<div class=\"grid grid-cols-[repeat(auto-fill,minmax(min(100%,300px),1fr))] gap-4\">\n```\n\n## Z-Index Management\n\nDefine a z-index scale in `@theme` tokens instead of arbitrary numbers:\n\n```css\n@theme {\n  --z-dropdown: 100;\n  --z-sticky: 200;\n  --z-fixed: 300;\n  --z-modal-backdrop: 400;\n  --z-modal: 500;\n  --z-popover: 600;\n  --z-tooltip: 700;\n  --z-toast: 800;\n}\n```\n\nReference with `z-(--z-modal)` syntax; never use `z-[9999]`.\n\n## Container Queries\n\nComponent-level responsiveness independent of viewport.\n\n```css\n@plugin \"@tailwindcss/container-queries\";\n```\n\n```html\n<article class=\"@container\">\n  <div class=\"flex flex-col @sm:flex-row gap-4\">\n    <img class=\"w-full @sm:w-32 @lg:w-48 aspect-video @sm:aspect-square object-cover\" />\n    <div class=\"flex-1 min-w-0\">\n      <h3 class=\"text-base @md:text-lg @lg:text-xl font-semibold truncate\">Title</h3>\n      <p class=\"text-sm @md:text-base line-clamp-2 @lg:line-clamp-3\">Description</p>\n    </div>\n  </div>\n</article>\n```\n\n| Use Container Queries | Use Viewport Queries |\n|----------------------|---------------------|\n| Reusable components | Page-level layouts |\n| Sidebar widgets | Navigation bars |\n| Card grids | Hero sections |\n| Embedded/CMS content | Full-width sections |\n\nNamed containers scope queries: `@container/sidebar` with `@lg/sidebar:flex-row`.\n\n## Fluid Typography\n\nEliminate breakpoint jumps with `clamp()`:\n\n```css\n@theme {\n  --text-fluid-base: clamp(1rem, 0.9rem + 0.5vw, 1.125rem);\n  --text-fluid-xl: clamp(1.25rem, 1rem + 1.25vw, 1.5rem);\n  --text-fluid-3xl: clamp(1.875rem, 1.2rem + 3.375vw, 2.5rem);\n}\n```\n\nAlways combine `vw` with `rem`; pure `vw` breaks when users zoom (WCAG violation).\n\n## Custom Utilities\n\n```css\n@utility scrollbar-none {\n  scrollbar-width: none;\n  -ms-overflow-style: none;\n}\n\n@utility text-gradient {\n  @apply bg-linear-to-r from-primary to-accent bg-clip-text text-transparent;\n}\n```\n\n## Native CSS Animations (v4)\n\nDefine keyframes inside `@theme` and reference with `--animate-*` tokens:\n\n```css\n@theme {\n  --animate-slide-up: slide-up 0.3s ease-out;\n  @keyframes slide-up {\n    from { opacity: 0; transform: translateY(20px); }\n    to { opacity: 1; transform: translateY(0); }\n  }\n}\n```\n\nUse `@starting-style` for entry animations on native popovers/dialogs:\n\n```css\n[popover]:popover-open { opacity: 1; transform: scale(1); }\n@starting-style { [popover]:popover-open { opacity: 0; transform: scale(0.95); } }\n```\n\nRespect motion preferences: `motion-safe:animate-bounce motion-reduce:animate-none`.\n\n## Safe Area Handling (Notched Devices)\n\n```css\n@utility safe-area-pt { padding-top: env(safe-area-inset-top); }\n@utility safe-area-pb { padding-bottom: env(safe-area-inset-bottom); }\n```\n\nApply to fixed headers/footers on mobile.\n\nFile v5.0.0:references/tailwind-v3-to-v4.md\n\n# v3 to v4 Breaking Changes\n\nReference for migrating an existing Tailwind v3 project to v4. For greenfield v4 work, [tailwind.md](./tailwind.md) covers current patterns directly.\n\n| v3 | v4 | Notes |\n|----|-----|-------|\n| `tailwind.config.ts` | `@theme` in CSS | Delete config file |\n| `@tailwind base/components/utilities` | `@import \"tailwindcss\"` | Single import |\n| `darkMode: \"class\"` | `@custom-variant dark (...)` | CSS-only |\n| `bg-gradient-to-r` | `bg-linear-to-r` | Also: `bg-radial`, `bg-conic` |\n| `bg-opacity-60` | `bg-red-500/60` | All `*-opacity-*` removed |\n| `rounded-sm` | `rounded-xs` | Radius scale shifted down one step |\n| `rounded` | `rounded-sm` | (run `@tailwindcss/upgrade` codemod) |\n| `rounded-md`, `rounded-lg`, `rounded-xl` | Unchanged | Default radii remain 6px, 8px, and 12px |\n| `min-h-screen` | `min-h-dvh` | `dvh` handles mobile browser chrome |\n| `w-6 h-6` | `size-6` | Size shorthand for equal w/h |\n| `space-x-4` | `gap-4` | Gap handles flex/grid wrapping correctly |\n| `text-base leading-7` | `text-base/7` | Inline line-height modifier |\n| `require(\"tailwindcss-animate\")` | `tw-animate-css` | CSS-only animations |\n| display utility beats `[hidden]` | `[hidden]` beats display utilities | Preflight adds `[hidden]:where(:not([hidden=\"until-found\"])) { display: none !important }`; remove the attribute instead of overriding it |\n\nRun `@tailwindcss/upgrade` codemod before hand-editing; it handles the mechanical class renames. Hand-fix `@theme` migration, custom variants, and any project-specific config patterns the codemod cannot infer.\n\nFile v5.0.0:references/tailwind.md\n\n# Tailwind CSS v4\n\n**Verify before implementing**: For v4-specific syntax (`@theme`, `@variant`, CSS-first config), look up current docs via Context7 (`query-docs`) before writing code. Tailwind v4 changed significantly from v3 and training data may be stale.\n\n## Working rules\n\n- Keep utility names as complete source literals and confirm their files are scanned.\n- Use shared design tokens and one consistent visibility mechanism.\n- Inspect generated CSS after source/configuration changes; JSX strings alone do not prove utilities exist.\n- Test scrolling, overlays, and focus behavior in a browser when layout containment changes.\n\n## Coding Rules\n\n- **`gap` over `space-x`/`space-y`**: gap handles wrapping; space-* breaks on wrap\n- **`size-*` over `w-* h-*`** for equal dimensions\n- **`min-h-dvh` over `min-h-screen`**: dvh accounts for mobile browser chrome\n- **Opacity modifier** (`bg-black/50`): `*-opacity-*` utilities are removed in v4\n- **Design tokens over arbitrary values**: check `@theme` before using `[#hex]`\n- **Never construct classes dynamically**: `text-${color}-500` won't be detected; use complete class names\n- **`@utility` over `@apply` with `@layer`**: `@apply` on `@layer` classes fails in v4\n- **Parent padding over last-child margin**: use padding on containers instead of bottom margins on the last child\n- **`overflow-x-auto` makes a scroll container on BOTH axes**: the utility emits only `overflow-x: auto`, but CSS Overflow 3 computes a `visible` value on the other axis to `auto` once either axis is scrollable, so a wrapper added purely to allow horizontal panning silently clips or scrolls whatever overflows it vertically: a non-portalled dropdown, popover, tooltip, custom select, or focus ring. jsdom does no layout, so no unit test catches it; enumerate every component rendered inside the new wrapper and confirm each overlay-ish one escapes it. Portaling is opt-in, not automatic: Radix exposes it as a separate `*.Portal` part wrapping `*.Content`, so read the component rather than assuming a library handles it. Same computed-value rule read backwards: before blaming a page-level scrollbar, walk every ancestor's `overflow` and name the element that actually scrolls\n- **Never express visibility as the native `hidden` attribute plus a display utility**: the two resolve in opposite directions across versions. v4's Preflight ships `[hidden]:where(:not([hidden=\"until-found\"])) { display: none !important }`, so the attribute wins and an element expected to be visible stays hidden; on v3, or wherever Preflight is disabled or not loaded, the author-origin utility (`block`, `flex`, `grid`) beats the UA-origin `[hidden]` rule regardless of specificity and the element stays on screen with `hidden` set. Toggle one mechanism: `clsx(base, open ? 'block' : 'hidden')`. Neither direction is visible to jsdom's `toBeInTheDocument`; only `toBeVisible` or a real browser engine catches it\n\n## Verify\n\n- Build passes with zero errors (`npm run build` or equivalent)\n- No v3 class names remain in changed files (check with `@tailwindcss/upgrade --dry-run` if available)\n- No conflicting classes on the same element\n\n## Task-specific references\n\n- For theme tokens, build configuration, dark mode, or missing styles: [tailwind-configuration.md](./tailwind-configuration.md).\n- For migrating an existing v3 project: [tailwind-v3-to-v4.md](./tailwind-v3-to-v4.md).\n- For class merging, scanning paths, variants, or lint integration: [tailwind-class-composition.md](./tailwind-class-composition.md).\n- For tailwind-variants slots, CVA, or compound components: [tailwind-component-patterns.md](./tailwind-component-patterns.md).\n- For grid areas, container queries, z-index management, or fluid typography: [tailwind-layout-patterns.md](./tailwind-layout-patterns.md).\n\nFile v5.0.0:references/test-selection.md\n\n# Test selection\n\n## Testing (Vitest + React Testing Library)\n\n- **Component tests**: Vitest + RTL, co-located `*.test.tsx`. Default for React components.\n- **Hook tests**: `renderHook` + `act`, co-located `*.test.ts`\n- **Unit tests**: Vitest for pure functions, utilities, services\n- **E2E**: Playwright for user flows and critical paths\n- **Query priority**: `getByRole` > `getByLabelText` > `getByPlaceholderText` > `getByText` > `getByTestId`\n- Mock API services and external providers; render child components real for integration confidence\n- One behavior per test with AAA structure. Name: `should <behavior> when <condition>`\n- Use `userEvent` over `fireEvent` for realistic interactions\n- `findBy*` for async elements, `waitFor` after state-triggering actions\n- `vi.clearAllMocks()` in `beforeEach` on Vitest 4 or with `clearMocks: false` (Vitest 5 clears by default). Recreate state per test.\n- Timing (`useLayoutEffect` vs `useEffect` report races), engine fidelity (jsdom/happy-dom vs a real browser engine for parser/layout-dependent behavior), interaction-mode pitfalls (`userEvent` delay, fake-timer incompatibility, `fireEvent` vs `userEvent` tradeoffs), and runner/environment failures (`vmThreads` OOM, happy-dom swallowing `console.*`): see [testing.md](./testing.md)\nGeneral testing discipline (anti-patterns, rationalization resistance): see the `ia-writing-tests` skill.\nSee [testing patterns and examples](./testing.md) for component, hook, and mocking examples.\nSee [e2e testing](./e2e-testing.md) for Playwright patterns.\n\nArchive v4.5.2: 9 files, 20452 bytes\n\nFiles: references/components-and-state.md (9246b), references/e2e-testing.md (5986b), references/rendering-and-frameworks.md (6310b), references/test-selection.md (1478b), references/testing.md (6726b), skill-card.md (2169b), SKILL.md (3657b), SPEC.md (4518b), _meta.json (146b)\n\nFile v4.5.2:SKILL.md\n\n---\nname: ia-react-frontend\nclass: language\ndescription: >-\n  React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when\n  working with React component structure, state management, Next.js routing,\n  Vitest, React Testing Library, or reviewing React code. For visual design and\n  aesthetic direction, use frontend-design instead.\npaths: \"**/*.tsx,**/*.jsx,**/*.ts\"\n---\n\n# React Frontend\n\n**Verify before implementing**: For App Router patterns, React 19 APIs, or version-specific behavior, look up current docs (Context7 `query-docs` if available, else the framework's official docs via web search) before writing code. Training data may lag current releases.\n\n## Working rules\n\n- Keep derived state in render and user actions in event handlers; use effects for external synchronization.\n- Give async work a lifecycle and cancellation policy; represent failure separately from pending and empty data.\n- Preserve focus when hiding interactive regions and exercise keyboard navigation in a real browser.\n- Validate and authorize every public server action; send only needed fields across server/client boundaries.\n- Measure performance changes and test user-visible behavior, not type-checking alone.\n\n## Effects Decision Tree\n\nEffects are escape hatches -- most logic should NOT use effects.\n\n| Need | Solution |\n|------|----------|\n| Derived value from props/state | Calculate during render (useMemo if expensive) |\n| Reset state on prop change | `key` prop on component |\n| Respond to user event | Event handler |\n| Notify parent of state change | Call onChange in event handler, or fully controlled component |\n| Chain of state updates | Calculate all next state in one event handler |\n| Sync with external system | Effect with cleanup |\n\n**Effect rules:**\n- Never suppress the linter -- fix the code instead\n- Use updater functions (`setItems(prev => [...prev, item])`) to remove state dependencies\n- Move objects/functions inside effects to stabilize dependencies\n- `useEffectEvent` for non-reactive values (e.g., theme in a connection effect)\n- Always return cleanup for subscriptions, connections, listeners\n- Data fetching cancellation (pick by situation): `AbortController` for fetch; `ignore` flag for non-cancellable promises; React Query handles both automatically\n\n\n## Discipline\n\n- Simplicity first -- every change as simple as possible, impact minimal code\n- Only touch what's necessary -- avoid introducing unrelated changes\n- No hacky workarounds -- if a fix feels wrong, step back and implement the clean solution\n- Before adding a new abstraction, verify it appears in 3+ places\n\n\n## References\n\n- [testing.md](./references/testing.md) -- Component, hook, and mocking test examples\n- [e2e-testing.md](./references/e2e-testing.md) -- Playwright E2E patterns\n\n\n## Verify\n\n- TypeScript compiles with zero errors\n- No suppressed lint rules (`eslint-disable`, `@ts-ignore`) in new code\n- `useEffect` dependency arrays not manually overridden\n- No `forwardRef` usage in React 19+ projects (use `ref` prop directly)\n\n## Task-specific references\n\nRead the relevant reference before implementing or reviewing the matching behavior:\n\n- For component types, state ownership, async races, focus, or cached query behavior: [components-and-state.md](./references/components-and-state.md).\n- For performance, React APIs, Next.js boundaries, caching, or Tailwind integration: [rendering-and-frameworks.md](./references/rendering-and-frameworks.md).\n- For component, hook, browser, or integration test changes: [test-selection.md](./references/test-selection.md).\n\nExisting specialized references, when the corresponding topic applies:\n\nFile v4.5.2:_meta.json\n\n{\n  \"ownerId\": \"kn715jrbbh71q9zncr0bqdkr8n848q1a\",\n  \"slug\": \"compound-eng-react-frontend\",\n  \"version\": \"4.5.2\",\n  \"publishedAt\": 1788832141814\n}\n\nFile v4.5.2:references/components-and-state.md\n\n# Components, state, and interaction\n\n## Component TypeScript\n\n- Extend native elements with `ComponentPropsWithoutRef<'button'>`, add custom props via intersection\n- Use `React.ReactNode` for children, `React.ReactElement` for single element, render prop `(data: T) => ReactNode`\n- Discriminated unions for variant props -- TypeScript narrows automatically in branches\n- Generic components: `<T>` with `keyof T` for column keys, `T extends { id: string }` for constraints\n- Event types: `React.MouseEvent<HTMLButtonElement>`, `FormEvent<HTMLFormElement>`, `ChangeEvent<HTMLInputElement>`\n- `as const` for custom hook tuple returns\n- `useRef<HTMLInputElement>(null)` for DOM (use `?.`), `useRef<number>(0)` for mutable values\n- Explicit `useState<User | null>(null)` for unions/null\n- useReducer actions as discriminated unions: `{ type: 'set'; payload: number } | { type: 'reset' }`\n- useContext null guard: throw in custom `useX()` hook if context is null\n- **A parameter type whose properties are all optional is a weak type, and a mismatched argument fails to compile rather than passing `undefined`.** TypeScript requires the argument to share at least one property with a weak type, so `(record: { newField?: boolean })` rejects a generated type that does not yet carry `newField` with `TS2559: Type 'X' has no properties in common with type 'Y'`. Intersect with the base type instead (`T & { newField?: boolean }`) -- the shim then deletes cleanly once the field lands upstream\n\n\n## Concurrency & Race Classes\n\nFive race classes survive type-checking and unit tests -- hunt each one during review (cleanup/cancellation mechanics: Effect rules above):\n\n| Class | Production signal | Fix |\n|-------|-------------------|-----|\n| Lifecycle cleanup gap | \"state update on unmounted component\" warnings, leaks under rapid navigation | Return cleanup from every effect that registers a listener/timer/observer |\n| Remount-timing mistake | Async callback mutates state/DOM after route change/unmount (`fetch().then(setData)` resolves post-navigation) | Cancel per the cancellation hierarchy |\n| Boolean-as-state for non-binary UI | Contradictory combos (`isLoading: true, error: Error`) | State constant (`'idle' \\| 'loading' \\| 'success' \\| 'error'`) + transition function; invalid states unreachable |\n| Stale promise/timer, no cancel path | Promise chain or `setTimeout` holds `setState` after the component moved on | Bind every async op to a cancel mechanism; test the cleanup path |\n| Per-element handlers on large lists | N closures/subscriptions per row, stale-closure bugs on rapid re-renders | Delegate: one parent handler + `event.target.closest(...)` when >~50 items or frequent updates |\n| Gate keyed on a child's success-only callback | Parent's submit stays locked behind \"still loading, try again in a moment\" copy that never resolves; only a page reload escapes | Report failures up (`onLoadError`) as well as successes, and split the flag into loading / loaded / failed -- a boolean cannot carry a terminal state. Keep the action blocked in both if proceeding on unknown data is unsafe; the fix is honest copy plus a real in-place retry, not unblocking |\n| `inert` toggled from a blur-managed flag | First `Tab` *inside* the subtree sends focus to `<body>`; the next `Tab` restarts at the top of the document and skips the (now inert) subtree entirely | React maps `onBlur` to native `focusout`, which fires on intra-subtree moves, and `focusin`/`focusout` are `DiscreteEventPriority` -- React commits `inert` synchronously *between* the two events, landing it on the already-focused incoming control. Stand down only when focus truly leaves: `if (e.currentTarget.contains(e.relatedTarget)) return;` |\n\n**Focus-ownership rules:**\n- Never toggle `inert` on a subtree that currently holds focus. The blunt version has no guard at all -- a scroll-driven `inert={!isVisible}` on a sticky bar, drawer, or collapsing panel strands the user on a control that is invisible, inert, and unactivatable. Hand focus to the equivalent visible control before hiding, and pass `focus({ preventScroll: true })` when the handoff fires from a scroll handler, or `focus()` scrolls its target into view and fights the scroll the user is performing. If the handoff target carries the same focus listeners that feed the guard, `focus()` arms the flag as a side effect of doing its job and the subtree never goes inert again -- make the handoff symmetric (two effects guarding opposite values of one flag) rather than adding an exception to the guard. `aria-hidden` without `inert` fixes double announcement but leaves the duplicate tab stops. Assert on what the user can *do* (does the handler fire, where does `Tab` go), not on `document.activeElement` -- Chromium resolves the unfocusing steps lazily and it reads back inconsistently\n- A blur-managed \"focus is inside\" flag cannot be cleared by a blur that never fires. Headless popover primitives restore focus to the element that *opened* the content on close; when the popover is anchored to an input with no trigger element, that restore no-ops, the library preventDefaults the focus-scope restore, and focus lands on `document.body` -- the input never receives another `blur`, so the flag sticks `true` for the component's lifetime and anything gated on it (a \"re-seed local text from `props.value`\" effect, for instance) is silently dead. Clear it explicitly in the select handler and on close when `document.activeElement` is not the input. The same design usually adds `onOpenAutoFocus={e => e.preventDefault()}` to avoid stealing typing focus, which leaves the content pointer-only: no trigger to Tab to and no auto-focus in. Add an explicit affordance plus `aria-haspopup`/`aria-expanded`. Browser-dependent -- Chromium and Firefox blur the input on `mousedown`, Safari does not, so \"works on my machine\" from Safari proves nothing\n\n\n## State Management\n\n```\nLocal UI state       → useState, useReducer\nShared client state  → Zustand (simple) | Redux Toolkit (complex)\nAtomic/granular      → Jotai\nServer/remote data   → React Query (TanStack Query)\nURL state            → nuqs, router search params\nForm state           → React Hook Form\n```\n\n**Key patterns:**\n- Zustand: `create<State>()(devtools(persist((set) => ({...}))))` -- use slices for scale, selective subscriptions to prevent re-renders\n- React Query: query keys factory (`['users', 'detail', id] as const`), `staleTime`/`gcTime`, optimistic updates with `onMutate`/`onError` rollback\n- React Query `isError` means *a fetch failed*, not *there is no data* -- a failed refetch sets `status: 'error'` while retaining the last successful payload, so the usual `isLoading ? spinner : isError ? errorPanel : content` ladder routes a working, fully cached list into the error panel. The defaults compose into it: `refetchOnMount: true` + `staleTime: 0` refetch on every mount, `retry: false` makes one blip terminal, and `gcTime: 5min` keeps the cache alive across a modal's unmount/remount. Gate the branch on data-absence -- `isLoadingError` (`isError && !hasData`), or `isError && derived.length === 0` when the suite mocks the hook and leaves `isLoadingError` undefined. Audit the side effects with it: `useEffect(() => { if (isError) toast(...) }, [isError])` fires over the live list too\n- The mirror case has the same tell: under `retry: false` a first load that fails leaves `data` `undefined` forever, so a branch gated on `data !== undefined` folds *failed* into *pending* and renders \"Loading…\" permanently. Whether it is recoverable is decided by mount topology, not by open/closed state -- a component rendered unconditionally inside a ref-driven popup is mounted for the life of the page, so `refetchOnMount` never fires again. Any remedy that adds a branch on `isError` must itself be gated on data-absence, or it re-introduces the previous bullet. Enumerate all four states before writing either gate -- `isLoading` (first load, no data yet), `isFetching` (any fetch in flight, including a background refetch over a warm cache), `isError` (last fetch failed, cache may still be present), and loaded-and-genuinely-empty -- and state the action in each: `!isFetching` misses the error state, `!isFetching && !isError` mishandles a background refetch of a legitimately empty result. The write path has the same shape, inverted: a fail-closed save gate keyed on `isError` blocks a valid submit whenever cached data is present\n- A mutate-scoped `onSuccess` survives an unmount that the mutation itself caused, so \"the success toast is dropped on promote/archive/delete\" is usually a false finding. The mutation dispatches success on the microtask after the hook-level `onSuccess` await resolves, while query-observer notifications -- the ones that re-render the list and unmount the row -- flush on a zero-delay timer; that is an ordering guarantee, not a race. The documented \"callbacks do not fire on unmount\" caveat describes a different unmount (navigation, closing a drawer). Read the scheduler and run a known-bad control (remove the observer before dispatch) before accepting the finding\n- Never duplicate server data (React Query) in a client store (Zustand)\n- Colocate state close to where it's used\n\nFile v4.5.2:references/e2e-testing.md\n\n# E2E Testing with Playwright\n\n> When to read: when authoring Playwright end-to-end tests — directory layout, fixtures, page objects, network mocking, CI integration.\n\n## Directory Structure\n\n```\ne2e/\n├── playwright.config.ts\n├── fixtures/\n│   ├── auth.fixture.ts\n│   └── test-data.fixture.ts\n├── pages/\n│   ├── base.page.ts\n│   └── <page-name>.page.ts\n├── tests/\n│   ├── auth/\n│   │   └── login.spec.ts\n│   └── smoke/\n│       └── critical-paths.spec.ts\n└── utils/\n    └── api-helpers.ts\n```\n\nNaming: tests `<feature>.spec.ts`, page objects `<page>.page.ts`, fixtures `<concern>.fixture.ts`.\n\n## Configuration\n\n```typescript\nimport { defineConfig, devices } from '@playwright/test';\n\nexport default defineConfig({\n  testDir: './e2e/tests',\n  fullyParallel: true,\n  forbidOnly: !!process.env.CI,\n  retries: process.env.CI ? 2 : 0,\n  workers: process.env.CI ? 1 : undefined,\n  reporter: 'html',\n  use: {\n    baseURL: 'http://localhost:5173',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n  },\n  projects: [\n    { name: 'setup', testDir: './e2e/fixtures', testMatch: 'auth.fixture.ts' },\n    {\n      name: 'chromium',\n      use: { ...devices['Desktop Chrome'], storageState: 'e2e/.auth/user.json' },\n      dependencies: ['setup'],\n    },\n  ],\n  webServer: {\n    command: 'npm run dev',\n    url: 'http://localhost:5173',\n    reuseExistingServer: !process.env.CI,\n  },\n});\n```\n\n## Page Object Model\n\nTests never use selectors directly -- page objects encapsulate all locators and actions.\n\n```typescript\n// e2e/pages/base.page.ts\nimport { type Page, type Locator } from '@playwright/test';\n\nexport abstract class BasePage {\n  constructor(protected readonly page: Page) {}\n  abstract goto(): Promise<void>;\n  async waitForLoad() { await this.page.waitForLoadState('networkidle'); }\n  get toast(): Locator { return this.page.getByRole('alert'); }\n}\n\n// e2e/pages/users.page.ts\nexport class UsersPage extends BasePage {\n  readonly createButton: Locator;\n  readonly searchInput: Locator;\n\n  constructor(page: Page) {\n    super(page);\n    this.createButton = page.getByRole('button', { name: /create/i });\n    this.searchInput = page.getByRole('searchbox', { name: /search/i });\n  }\n\n  async goto() {\n    await this.page.goto('/users');\n    await this.waitForLoad();\n  }\n\n  async searchFor(query: string) {\n    await this.searchInput.fill(query);\n    await this.page.waitForResponse('**/api/users?*');\n  }\n}\n```\n\nRules: locators as public readonly properties, actions as async methods with internal waits, no assertions in page objects, one PO per page.\n\n## Selector Priority\n\n| Priority | Method | Use when |\n|----------|--------|----------|\n| 1 | `getByRole` | Buttons, links, headings, inputs |\n| 2 | `getByLabel` | Form inputs with labels |\n| 3 | `getByPlaceholder` | Search inputs |\n| 4 | `getByText` | Static text content |\n| 5 | `getByTestId` | No accessible selector available |\n\nNever use CSS selectors, XPath, or DOM structure selectors. When adding `data-testid`, use `<action>-<entity>-<type>` pattern: `create-user-btn`.\n\n## Filling Inputs\n\nPrefer `locator.fill(value)` to `page.keyboard.type()`. Synthesised keystrokes drop characters intermittently under a browser-attached session (CDP against an already-running browser), and the driver reports the full string as typed while the DOM holds a short value -- so the assertion that would catch it is the one nobody writes. Rich-text editors whose state lives outside the element's `value` (ProseMirror, Slate, TipTap) ignore programmatic writes and still need `type()`; there, assert `input_value()` (or the editor's own serialized content) after typing and retry on a short read.\n\n## Wait Strategies\n\nNever use `waitForTimeout` or `setTimeout`. Use explicit conditions:\n\n```typescript\nawait page.getByRole('heading', { name: 'Dashboard' }).waitFor();\nawait page.waitForURL('/dashboard');\nawait page.waitForResponse(\n  (r) => r.url().includes('/api/users') && r.status() === 200,\n);\nawait page.getByTestId('spinner').waitFor({ state: 'hidden' });\n```\n\n## Auth State Reuse\n\nSave auth state once, reuse across all tests:\n\n```typescript\n// e2e/fixtures/auth.fixture.ts\nimport { test as setup } from '@playwright/test';\n\nsetup('authenticate', async ({ page }) => {\n  await page.goto('/login');\n  await page.getByLabel('Email').fill('testuser@example.com');\n  await page.getByLabel('Password').fill('TestPassword123!');\n  await page.getByRole('button', { name: /sign in/i }).click();\n  await page.waitForURL('/dashboard');\n  await page.context().storageState({ path: 'e2e/.auth/user.json' });\n});\n```\n\nTests receive auth state via `storageState` in config projects.\n\n## Test Data & Network\n\n- Tests create own data via API helpers (faster than UI), clean up in `finally` blocks\n- Mock responses with `page.route('**/api/path', route => route.fulfill({ ... }))`\n- Simulate errors with `route.abort('failed')`\n- Wait for responses: `const resp = page.waitForResponse('**/api/users'); await click; await resp;`\n\n## Flaky Test Fixes\n\n| Cause | Fix |\n|-------|-----|\n| Hardcoded waits | Explicit wait conditions |\n| Shared test data | Each test creates its own |\n| Animations | `animations: 'disabled'` in config |\n| Race conditions | Wait for API responses before assertions |\n\n**Quarantine workflow** -- confirm flakiness before quarantining:\n```bash\nnpx playwright test --repeat-each=10 path/to/test.spec.ts  # Confirm flakiness\nnpx playwright test --retries=3 path/to/test.spec.ts       # Check if retries help\n```\n\nMark confirmed flaky tests with an issue reference:\n```typescript\ntest.fixme(true, 'Flaky - Issue #123');                       // Always skip\ntest.skip(!!process.env.CI, 'Flaky in CI only - Issue #123'); // Skip in CI only\n```\n\n```bash\nnpx playwright test --headed --debug  # Debug mode\nnpx playwright show-trace trace.zip   # Trace viewer\nnpx playwright test --ui              # Interactive UI\n```\n\nFile v4.5.2:references/rendering-and-frameworks.md\n\n# Rendering and framework patterns\n\n## Performance\n\n**Critical -- eliminate waterfalls:**\n- `Promise.all()` for independent async operations\n- Move `await` into branches where actually needed\n- Suspense boundaries to stream slow content\n\n**Critical -- bundle size:**\n- Import directly from modules, avoid barrel files (`index.ts` re-exports)\n- `next/dynamic` or `React.lazy()` for heavy components\n- Defer third-party scripts (analytics, logging) until after hydration\n- Preload on hover/focus for perceived speed\n- `content-visibility: auto` + `contain-intrinsic-size` on long lists -- skips off-screen layout/paint\n\n**Re-render optimization:**\n- Never define a component inside another component. Each parent render creates a new function identity, and React compares element *types* to decide whether to update or replace -- a new type means the whole subtree unmounts and remounts, so local state is lost, effects re-run, and DOM nodes are recreated. Symptoms are behavioral, not slow: an input loses focus on every keystroke, animations restart, scroll position resets. Hoist the component to module scope and pass what it needed via props. The React Compiler does not save this one -- the type identity changes before memoization applies\n- Derive state during render, not in effects\n- Subscribe to derived booleans, not raw objects (`state.items.length > 0` not `state.items`)\n- Functional setState for stable callbacks: `setCount(c => c + 1)`\n- Lazy state init: `useState(() => expensiveComputation())`\n- `useTransition` for non-urgent updates (search filtering)\n- `useDeferredValue` for expensive derived UI\n- Don't subscribe to searchParams/state read only in callbacks -- read on demand\n- Use ternary (`condition ? <A /> : <B />`), not `&&` for conditionals\n- `React.memo` only for expensive subtrees with stable props\n- Hoist static JSX outside components\n\n**React Compiler** (React 19): auto-memoizes -- write idiomatic React, remove manual `useMemo`/`useCallback`/`memo`. Enable via `reactCompiler: true` in next.config (non-framework: `babel-plugin-react-compiler`). Keep components pure.\n\n\n## React 19\n\n- **ref as prop** -- `forwardRef` deprecated. Accept `ref?: React.Ref<HTMLElement>` as regular prop\n- **useActionState** -- replaces `useFormState`: `const [state, formAction, isPending] = useActionState(action, initialState)`\n- **use()** -- unwrap Promise or Context during render (not in callbacks/effects). Enables conditional context reads\n- **useOptimistic** -- `const [optimistic, addOptimistic] = useOptimistic(state, mergeFn)` for instant UI feedback\n- **useFormStatus** -- `const { pending } = useFormStatus()` in child of `<form action={...}>`\n- **Server Components** -- default in App Router. Async, access DB/secrets directly. No hooks, no event handlers\n- **Server Actions** -- `'use server'` directive. Validate inputs (Zod), `revalidateTag`/`revalidatePath` after mutations. **Server Actions are public endpoints** -- always verify auth/authz inside each action, not just in middleware or layout guards\n- **`<Activity mode='visible'|'hidden'>`** -- preserves state/DOM for toggled components (experimental)\n\n\n## Next.js App Router\n\n**File conventions:** `page.tsx` (route UI), `layout.tsx` (shared wrapper), `template.tsx` (re-mounted on navigation, unlike layout), `loading.tsx` (Suspense), `error.tsx` (error boundary), `not-found.tsx` (404), `default.tsx` (parallel route fallback), `route.ts` (API endpoint)\n\n**Rendering modes:** Server Components (default) | Client (`'use client'`) | Static (build) | Dynamic (request) | Streaming (progressive)\n\n**Decision:** Server Component unless it needs hooks, event handlers, or browser APIs. Split: server parent + client child. Isolate interactive components as `'use client'` leaf components -- keep server components static with no global state or event handlers.\n\n**Server → client boundary:** pass only the fields a client component actually uses, not whole ORM rows or fetch objects. Every prop crossing the `'use client'` boundary is serialized into the payload, so a 50-field `user` object read for one field still ships all 50.\n\n**Client-only state that drives first paint** (theme, locale, feature flag, auth hint): reading `localStorage` during render breaks SSR, and reading it in `useEffect` paints the default first, so the correct value arrives one frame later as a visible flash. Set the value on the document with a small synchronous inline script that runs before hydration -- typically writing a `class` or `data-` attribute on `<html>` that CSS already keys on. The script is developer-authored and must never interpolate user, request, or database data; it is the one place `dangerouslySetInnerHTML` is warranted, and only for a literal string.\n\n**Routing patterns:**\n- Route groups `(name)` -- organize without affecting URL\n- Parallel routes `@slot` -- independent loading states in same layout\n- Intercepting routes `(.)` -- modal overlays with full-page fallback\n\n**Caching:**\n- `fetch(url, { cache: 'force-cache' })` -- static\n- `fetch(url, { next: { revalidate: 60 } })` -- ISR\n- `fetch(url, { cache: 'no-store' })` -- dynamic\n- Tag-based: `fetch(url, { next: { tags: ['products'] } })` then `revalidateTag('products')`\n\n**Data fetching:**\n- Fetch in Server Components where data is used\n- Use Suspense boundaries for slow queries\n- `React.cache()` for per-request dedup\n- `generateStaticParams` for static generation\n- `generateMetadata` for dynamic SEO\n- Static metadata with `title: { default: 'App', template: '%s | App' }` for cascading page titles\n- `after()` for non-blocking side effects (logging, analytics) -- runs after response is sent\n- Hoist static I/O (fonts, config) to module level -- runs once, not per request\n- Never hold request-scoped or user data in module-level mutable state -- server renders run concurrently in one process, so shared module state leaks across requests (one user's data surfacing in another's response). Hoist only immutable static I/O; keep request data local to the render tree (pass as props)\n\n\n## Tailwind Integration\n\nFor Tailwind v4 configuration, utility patterns, dark mode, and component variants, see the `ia-tailwind-css` skill.\n\n**Class sorting in JSX**: keep Tailwind classes in canonical order (enforce via `eslint-plugin-better-tailwindcss`).\n\nFile v4.5.2:references/test-selection.md\n\n# Test selection\n\n## Testing (Vitest + React Testing Library)\n\n- **Component tests**: Vitest + RTL, co-located `*.test.tsx`. Default for React components.\n- **Hook tests**: `renderHook` + `act`, co-located `*.test.ts`\n- **Unit tests**: Vitest for pure functions, utilities, services\n- **E2E**: Playwright for user flows and critical paths\n- **Query priority**: `getByRole` > `getByLabelText` > `getByPlaceholderText` > `getByText` > `getByTestId`\n- Mock API services and external providers; render child components real for integration confidence\n- One behavior per test with AAA structure. Name: `should <behavior> when <condition>`\n- Use `userEvent` over `fireEvent` for realistic interactions\n- `findBy*` for async elements, `waitFor` after state-triggering actions\n- `vi.clearAllMocks()` in `beforeEach`. Recreate state per test.\n- Timing (`useLayoutEffect` vs `useEffect` report races), engine fidelity (jsdom/happy-dom vs a real browser engine for parser/layout-dependent behavior), interaction-mode pitfalls (`userEvent` delay, fake-timer incompatibility, `fireEvent` vs `userEvent` tradeoffs), and runner/environment failures (`vmThreads` OOM, happy-dom swallowing `console.*`): see [testing.md](./testing.md)\nGeneral testing discipline (anti-patterns, rationalization resistance): see the `ia-writing-tests` skill.\nSee [testing patterns and examples](./testing.md) for component, hook, and mocking examples.\nSee [e2e testing](./e2e-testing.md) for Playwright patterns.\n\nFile v4.5.2:references/testing.md\n\n# Testing React (Vitest + RTL)\n\n> When to read: when adding or fixing component tests with Vitest + React Testing Library — setup, queries, user-event, async assertions, mocking.\n\n## Setup\n\nVitest config: `environment: 'jsdom'`, `globals: true`, `setupFiles` pointing to a file that imports `@testing-library/jest-dom/vitest`. Use `@vitejs/plugin-react` and mirror path aliases from `tsconfig.json`.\n\n## Component Test\n\n```tsx\nimport { render, screen, waitFor } from '@testing-library/react';\nimport userEvent from '@testing-library/user-event';\n\nvi.mock('@/api/client');\n\ndescribe('UserForm', () => {\n  beforeEach(() => { vi.clearAllMocks(); });\n\n  it('should submit valid form data', async () => {\n    const onSubmit = vi.fn();\n    render(<UserForm onSubmit={onSubmit} />);\n\n    await userEvent.type(screen.getByLabelText(/email/i), 'test@example.com');\n    await userEvent.click(screen.getByRole('button', { name: /submit/i }));\n\n    await waitFor(() => {\n      expect(onSubmit).toHaveBeenCalledWith(\n        expect.objectContaining({ email: 'test@example.com' }),\n      );\n    });\n  });\n});\n```\n\n## Hook Test\n\n```typescript\nimport { renderHook, act } from '@testing-library/react';\n\nit('should debounce value updates', () => {\n  vi.useFakeTimers();\n  const { result, rerender } = renderHook(\n    ({ value }) => useDebounce(value, 300),\n    { initialProps: { value: 'initial' } },\n  );\n  rerender({ value: 'updated' });\n  expect(result.current).toBe('initial');\n  act(() => { vi.advanceTimersByTime(300); });\n  expect(result.current).toBe('updated');\n  vi.useRealTimers();\n});\n```\n\n## Mocking Patterns\n\n```typescript\n// Service mock -- mock the module, not the transport layer\nvi.mock('@/server-api/me/me.service', () => ({\n  MeService: { retrieveMe: vi.fn() },\n}));\n\n// QueryClient wrapper for components using TanStack Query\nconst createWrapper = () => {\n  const queryClient = new QueryClient({\n    defaultOptions: { queries: { retry: false } },\n  });\n  return ({ children }: { children: React.ReactNode }) => (\n    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>\n  );\n};\nrender(<Component />, { wrapper: createWrapper() });\n```\n\n## Test Classification\n\n| Type | Tool | Target | File pattern |\n|------|------|--------|-------------|\n| Unit | Vitest | Pure functions, utilities, services | Co-located `*.test.ts` |\n| Component | Vitest + RTL | React components | Co-located `*.test.tsx` |\n| Hook | Vitest + RTL | Custom hooks | Co-located `*.test.ts` |\n| E2E | Playwright | User flows, critical paths | Separate `e2e/` directory |\n\n## Running Tests\n\n```bash\nnpx vitest                         # Watch mode\nnpx vitest run                     # Single run (CI)\nnpx vitest run src/features/       # Test specific directory\nnpx vitest --coverage              # Coverage report\n```\n\n## Timing, Fidelity, and Interaction-Mode Pitfalls\n\nReport from `useLayoutEffect`, not `useEffect`, in a child stub whose report feeds a gate under test. A `useEffect` report lands a tick late: `render()` returns, the test queries and clicks before the report's `setState` has committed, and the click reads the pre-report state. RTL flushes layout effects *and their state updates* synchronously inside `render()`'s `act`. Awaiting a settled-state text papers over it only where there is a positive DOM signal -- a gate-*unsatisfiable* case has none, so it flakes or silently asserts the wrong branch.\n\njsdom and happy-dom are not evidence about a browser-rendered artifact. Where the behavior is decided by a parser, layout, or print engine -- a serialized DOM re-parsed by Chromium, `inert`, `postMessage` across an opaque origin -- execute it in the *sink's* engine (Playwright/Chromium against the repo's own dependency) and carry a known-bad control in the same batch. jsdom does not enforce the radio-group invariant on parse and does not enforce the opaque-origin `targetOrigin` check, so the natural regression test passes while the bug ships. Engine fidelity and path fidelity are separate requirements: load the committed artifact verbatim and drive it through its real entry point, because a hand-rebuilt reconstruction can invert the result while looking like executed evidence.\n\nUse `userEvent.setup({ delay: null })` in component tests. A bare `setup()` inserts a `setTimeout(0)` macrotask between every simulated keystroke and pointer event -- pure idle time in a test DOM, and the single largest source of a slow suite's tail.\n\n`vi.useFakeTimers()` freezes `findBy`/`waitFor` polling **and** `userEvent` (v14 awaits real timers internally), so the two do not compose. Under fake timers drive with `fireEvent` plus an explicit settle -- `await act(async () => { await vi.runOnlyPendingTimersAsync(); })`, or `advanceTimersByTimeAsync(N)` for a debounce window -- and assert both sides of the boundary: not-called at N-1ms, called once at Nms. A one-sided assertion passes against an eager implementation.\n\nFill forms with one `fireEvent.change` per field when typing is not the behavior under test. `user.type` into a `mode: 'onChange'` react-hook-form field pays a full-schema re-validation per keystroke, and it focuses the input, which mounts whatever popover is attached (a date field re-renders a 42-day calendar grid on every keystroke). Keep one keystroke-level test per form for validation coverage and convert the rest. `fireEvent` cannot drive components that need a real pointer sequence (a combobox opening on input click, a menu opening on `pointerdown`) -- those keep `userEvent`.\n\n## Runner and Environment Failures\n\nUnder `pool: 'vmThreads'` a worker's RSS grows monotonically across files, and the recycler's default threshold is a share of `os.totalmem()` -- the *host's* RAM, not the container's cgroup limit -- so in CI the kernel OOM-kills the worker before Vitest decides to recycle it. Fingerprint: `Worker exited unexpectedly` late in the run, every test that ran reporting green, and **no `Test Files ... | Tests ...` summary line at all**. Set `test.vmMemoryLimit` in the Vitest config (512MB is a sane starting point) on every app using a VM pool; it is a recycle threshold rather than a hard cap, and it is inert on non-VM pools, so it is safe to set repo-wide.\n\nhappy-dom installs a virtual console that swallows `console.*`, so debug output written from a test never reaches the runner and a diagnostic that prints nothing looks like a code path that never ran. Write diagnostics through `process.stdout.write`. Any console-reporting safety net (a setup file that fails the suite on an unexpected `console.error`, for instance) must write to stdout the same way, and must throw when the environment hook it depends on is missing rather than silently reporting nothing.\n\nFile v4.5.2:skill-card.md\n\n## Description:\n\nProvides React architecture patterns and guidance for TypeScript, Next.js, hooks, component structure, state management, routing, Vitest, React Testing Library, and React code review.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[iliaal](https://clawhub.ai/user/iliaal)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and engineers use this skill for React, TypeScript, Next.js, hooks, and frontend testing work, including implementation guidance and code review.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Frontend test commands and examples may execute project dependencies or browser automation in the user's environment.\n\nMitigation: Use reviewed lockfiles and local-only execution when running tests or Playwright flows.\n\nRisk: Playwright authentication state files can expose non-production test account sessions if committed.\n\nMitigation: Keep auth-state files out of version control and use dedicated non-production test accounts.\n\n## Reference(s):\n\n- [Skill page](https://clawhub.ai/iliaal/skills/compound-eng-react-frontend)\n- [Components, state, and interaction](references/components-and-state.md)\n- [E2E Testing with Playwright](references/e2e-testing.md)\n- [Rendering and framework patterns](references/rendering-and-frameworks.md)\n- [Test selection](references/test-selection.md)\n- [Testing React (Vitest + RTL)](references/testing.md)\n\n## Skill Output:\n\n**Output Type(s):** [Guidance, Markdown, Code, Shell commands, Configuration]\n\n**Output Format:** [Markdown guidance with inline TypeScript, TSX, JavaScript, shell command, and configuration examples]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May route the agent to bundled topic references before producing implementation or review guidance.]\n\n## Skill Version(s):\n\n4.5.2 (source: server release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nFile v4.5.2:SPEC.md\n\n# ia-react-frontend Specification\n\n## Intent\n\n`ia-react-frontend` is a `language`-class skill (stack-specific patterns and idioms). React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, or reviewing React code. For visual design and aesthetic direction, use frontend-design instead.\n\n## Scope\n\nIn scope:\n- Behaviors described in `SKILL.md` and routed via the should_trigger phrasings in `distillery/tests/fixtures/triggers/ia-react-frontend.jsonl`.\n- Updates to runtime behavior, structure, trigger precision, references, and validation.\n\nOut of scope:\n- Acting as the runtime instructions themselves (those live in `SKILL.md`).\n- Trigger phrasings already covered by adjacent `ia-*` skills (`validate-plugin` flags >70% description overlap as DUPLICATE_TRIGGER).\n- <!-- to fill in: domain-specific exclusions when the skill drifts -->\n\n## Trigger Context\n\n- Class: `language`\n- Hook regex: `plugins/whetstone/hooks/skill-patterns.sh` -> `SKILL_PATTERNS[ia-react-frontend]`\n- Common requests (from fixture should_trigger):\n  - \"create a React component with state management\"\n  - \"create a React hook for form validation\"\n  - \"fix the Next.js routing issue\"\n- Should not trigger for (from fixture should_not_trigger):\n  - \"write a Laravel migration for the orders table\"\n  - \"optimize the database indexes\"\n  - \"write a bash script for deployment\"\n\n## Source And Evidence Model\n\nAuthoritative sources:\n\n- `SKILL.md` -- runtime instructions and reference routing.\n- `references/*.md` -- bundled supplementary content (2 file(s)).\n- `distillery/tests/fixtures/triggers/ia-react-frontend.jsonl` -- positive and negative trigger phrasings under regression test.\n- `plugins/whetstone/hooks/skill-patterns.sh` -- regex pattern that fires this skill.\n- `distillery/.eval-data/ia-react-frontend/` -- harvested session examples (when present).\n\nData that must not be stored in this skill or its references:\n\n- Secrets, credentials, tokens.\n- Machine-specific filesystem paths (`/home/...`, `/Users/...`, `~/ai/...`). The validator (`MACHINE_PATH_LEAK`) flags these as HIGH.\n- Private URLs, customer data, or unredacted personal information.\n\n### Coverage matrix\n\n| Dimension | Status | Evidence |\n|---|---|---|\n| Trigger fixtures | complete | distillery/tests/fixtures/triggers/ia-react-frontend.jsonl (>=5 should_trigger, >=5 should_not_trigger) |\n| Hook regex pattern | complete | plugins/whetstone/hooks/skill-patterns.sh (`SKILL_PATTERNS[ia-react-frontend]`) |\n| Reference architecture | complete | 2 file(s) under references/ |\n| Real-usage signal | <!-- populated by harvest-sessions when sessions exist --> | distillery/.eval-data/ia-react-frontend/ (created by harvest-sessions) |\n\n## Evaluation\n\nLightweight (run on every change):\n\n```bash\npython3 distillery/scripts/distiller.py validate-plugin --component ia-react-frontend\npython3 distillery/scripts/distiller.py test-triggers --skill ia\n\nArchive v4.5.0: 6 files, 16946 bytes\n\nFiles: references/e2e-testing.md (5375b), references/testing.md (5522b), skill-card.md (2120b), SKILL.md (17627b), SPEC.md (4518b), _meta.json (146b)\n\nArchive v4.4.3: 6 files, 13462 bytes\n\nFiles: references/e2e-testing.md (5375b), references/testing.md (2810b), skill-card.md (2128b), SKILL.md (12743b), SPEC.md (4518b), _meta.json (146b)\n\nArchive v4.4.1: 6 files, 13443 bytes\n\nFiles: references/e2e-testing.md (5375b), references/testing.md (2810b), skill-card.md (2045b), SKILL.md (12794b), SPEC.md (4518b), _meta.json (146b)\n\nArchive v4.2.1: 6 files, 12746 bytes\n\nFiles: references/e2e-testing.md (5375b), references/testing.md (2810b), skill-card.md (1808b), SKILL.md (11567b), SPEC.md (4518b), _meta.json (146b)\n\nArchive v4.2.0: 6 files, 12634 bytes\n\nFiles: references/e2e-testing.md (5375b), references/testing.md (2810b), skill-card.md (2091b), SKILL.md (10985b), SPEC.md (4518b), _meta.json (146b)\n\nArchive v4.1.0: 6 files, 13053 bytes\n\nFiles: references/e2e-testing.md (5375b), references/testing.md (2810b), skill-card.md (1882b), SKILL.md (12109b), SPEC.md (4518b), _meta.json (146b)\n\nArchive v3.0.5: 6 files, 12902 bytes\n\nFiles: references/e2e-testing.md (5236b), references/testing.md (2660b), skill-card.md (1903b), SKILL.md (12098b), SPEC.md (4551b), _meta.json (146b)","readmeExcerpt":"Skill: ia-react-frontend Owner: iliaal Summary: React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, reviewing React code, or synchronizing JSON locales and reviewing translations in a React or frontend interface. For visual design and aesthetic direction, use frontend-design instead. Ta","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"Local UI state       → useState, useReducer\nShared client state  → Zustand (simple) | Redux Toolkit (complex)\nAtomic/granular      → Jotai\nServer/remote data   → React Query (TanStack Query)\nURL state            → nuqs, router search params\nForm state           → React Hook Form"},{"language":"text","snippet":"project-root/\n├── playwright.config.ts\n└── e2e/\n    ├── fixtures/\n    │   ├── auth.fixture.ts\n    │   └── test-data.fixture.ts\n    ├── pages/\n    │   ├── base.page.ts\n    │   └── <page-name>.page.ts\n    ├── tests/\n    │   ├── auth/\n    │   │   └── login.spec.ts\n    │   └── smoke/\n    │       └── critical-paths.spec.ts\n    └── utils/\n        └── api-helpers.ts"},{"language":"typescript","snippet":"import { defineConfig, devices } from '@playwright/test';\n\nexport default defineConfig({\n  testDir: './e2e/tests',\n  fullyParallel: true,\n  forbidOnly: !!process.env.CI,\n  retries: process.env.CI ? 2 : 0,\n  workers: process.env.CI ? 1 : undefined,\n  reporter: 'html',\n  expect: {\n    toHaveScreenshot: { animations: 'disabled' },\n  },\n  use: {\n    baseURL: 'http://localhost:5173',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n  },\n  projects: [\n    { name: 'setup', testDir: './e2e/fixtures', testMatch: 'auth.fixture.ts' },\n    {\n      name: 'chromium',\n      use: { ...devices['Desktop Chrome'], storageState: 'e2e/.auth/user.json' },\n      dependencies: ['setup'],\n    },\n  ],\n  webServer: {\n    command: 'npm run dev',\n    url: 'http://localhost:5173',\n    reuseExistingServer: !process.env.CI,\n  },\n});"},{"language":"typescript","snippet":"// e2e/pages/base.page.ts\nimport { type Page, type Locator } from '@playwright/test';\n\nexport abstract class BasePage {\n  constructor(protected readonly page: Page) {}\n  abstract goto(): Promise<void>;\n  abstract readonly ready: Locator;\n  async waitForLoad() { await this.ready.waitFor(); }\n  get toast(): Locator { return this.page.getByRole('alert'); }\n}\n\n// e2e/pages/users.page.ts\nexport class UsersPage extends BasePage {\n  readonly ready: Locator;\n  readonly createButton: Locator;\n  readonly searchInput: Locator;\n\n  constructor(page: Page) {\n    super(page);\n    this.ready = page.getByRole('heading', { name: /users/i });\n    this.createButton = page.getByRole('button', { name: /create/i });\n    this.searchInput = page.getByRole('searchbox', { name: /search/i });\n  }\n\n  async goto() {\n    await this.page.goto('/users');\n    await this.waitForLoad();\n  }\n\n  async searchFor(query: string) {\n    const resp = this.page.waitForResponse('**/api/users?*');\n    await this.searchInput.fill(query);\n    await resp;\n  }\n}"},{"language":"typescript","snippet":"await page.getByRole('heading', { name: 'Dashboard' }).waitFor();\nawait page.waitForURL('/dashboard');\nconst resp = page.waitForResponse(\n  (r) => r.url().includes('/api/users') && r.status() === 200,\n);\nawait page.getByRole('button', { name: /load/i }).click();\nawait resp;\nawait page.getByTestId('spinner').waitFor({ state: 'hidden' });"},{"language":"typescript","snippet":"// e2e/fixtures/auth.fixture.ts\nimport { test as setup } from '@playwright/test';\n\nsetup('authenticate', async ({ page }) => {\n  await page.goto('/login');\n  await page.getByLabel('Email').fill('testuser@example.com');\n  await page.getByLabel('Password').fill('TestPassword123!');\n  await page.getByRole('button', { name: /sign in/i }).click();\n  await page.waitForURL('/dashboard');\n  await page.context().storageState({ path: 'e2e/.auth/user.json' });\n});"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: ia-react-frontend\nclass: language\ndescription: >-\n  React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when\n  working with React component structure, state management, Next.js routing,\n  Vitest, React Testing Library, reviewing React code, or synchronizing JSON\n  locales and reviewing translations in a React or frontend interface. For\n  visual design and aesthetic direction, use frontend-design instead.\npaths: \"**/*.tsx,**/*.jsx,**/*.ts,**/*.css,**/tailwind.config.*,**/*.html,**/*.vue,**/*.blade.php\"\n---\n\n# React Frontend\n\n**Verify before implementing**: For App Router patterns, React 19 APIs, or version-specific behavior, look up current docs (Context7 `query-docs` if available, else the framework's official docs via web search) before writing code. Training data may lag current releases.\n\n## Working rules\n\n- Keep derived state in render and user actions in event handlers; use effects for external synchronization.\n- Give async work a lifecycle and cancellation policy; represent failure separately from pending and empty data.\n- Preserve focus when hiding interactive regions and exercise keyboard navigation in a real browser.\n- Validate and authorize every public server action; send only needed fields across server/client boundaries.\n- Measure performance changes and test user-visible behavior, not type-checking alone.\n\n## Effects Decision Tree\n\nEffects are escape hatches; most logic should NOT use effects.\n\n| Need | Solution |\n|------|----------|\n| Derived value from props/state | Calculate during render (useMemo if expensive) |\n| Reset state on prop change | `key` prop on component |\n| Respond to user event | Event handler |\n| Notify parent of state change | Call onChange in event handler, or fully controlled component |\n| Chain of state updates | Calculate all next state in one event handler |\n| Sync with external system | Effect with cleanup |\n\n**Effect rules:**\n- Never suppress the linter; fix the code instead\n- Use updater functions (`setItems(prev => [...prev, item])`) to remove state dependencies\n- Move objects/functions inside effects to stabilize dependencies\n- `useEffectEvent` for non-reactive values (e.g., theme in a connection effect)\n- Always return cleanup for subscriptions, connections, listeners\n- Data fetching cancellation (pick by situation): `AbortController` for fetch; `ignore` flag for non-cancellable promises. With React Query, pass the query function's signal to the transport, such as `queryFn: ({ signal }) => fetch(url, { signal })`. Without consuming that signal, an unused query can finish and populate the cache; do not describe that behavior as transport cancellation.\n\n\n## Discipline\n\n- Simplicity first: every change as simple as possible, impact minimal code\n- Only touch what's necessary; avoid introducing unrelated changes\n- No hacky workarounds: if a fix feels wrong, step back and implement the clean solution\n- Before adding a new abstraction, verify it appears in 3+ places\n\n\n## Refere"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn715jrbbh71q9zncr0bqdkr8n848q1a\",\n  \"slug\": \"compound-eng-react-frontend\",\n  \"version\": \"5.0.1\",\n  \"publishedAt\": 1791047222338\n}"},{"path":"references/components-and-state.md","content":"# Components, state, and interaction\n\n## Component TypeScript\n\n- Extend native elements with `ComponentPropsWithoutRef<'button'>`, add custom props via intersection\n- Use `React.ReactNode` for children, `React.ReactElement` for single element, render prop `(data: T) => ReactNode`\n- Discriminated unions for variant props; TypeScript narrows automatically in branches\n- Generic components: `<T>` with `keyof T` for column keys, `T extends { id: string }` for constraints\n- Event types: `React.MouseEvent<HTMLButtonElement>`, `FormEvent<HTMLFormElement>`, `ChangeEvent<HTMLInputElement>`\n- `as const` for custom hook tuple returns\n- `useRef<HTMLInputElement>(null)` for DOM (use `?.`), `useRef<number>(0)` for mutable values\n- Explicit `useState<User | null>(null)` for unions/null\n- Pass optional handlers through unwrapped: `onX={(a) => handler?.(a)}` is always truthy, so a child that renders a control only when `onX` is provided always renders it, and the click silently does nothing. Pass `handler` (or `undefined`) and gate the control on the real handler's presence.\n- useReducer actions as discriminated unions: `{ type: 'set'; payload: number } | { type: 'reset' }`\n- useContext null guard: throw in custom `useX()` hook if context is null\n- **A parameter type whose properties are all optional is a weak type, and a mismatched argument fails to compile rather than passing `undefined`.** TypeScript requires the argument to share at least one property with a weak type, so `(record: { newField?: boolean })` rejects a generated type that does not yet carry `newField` with `TS2559: Type 'X' has no properties in common with type 'Y'`. Intersect with the base type instead (`T & { newField?: boolean }`); the shim then deletes cleanly once the field lands upstream\n\n\n## Concurrency & Race Classes\n\nFive race classes survive type-checking and unit tests; hunt each one during review (cleanup/cancellation mechanics: Effect rules above):\n\n| Class | Production signal | Fix |\n|-------|-------------------|-----|\n| Lifecycle cleanup gap | \"state update on unmounted component\" warnings, leaks under rapid navigation | Return cleanup from every effect that registers a listener/timer/observer |\n| Remount-timing mistake | Async callback mutates state/DOM after route change/unmount (`fetch().then(setData)` resolves post-navigation) | Cancel per the cancellation hierarchy |\n| Boolean-as-state for non-binary UI | Contradictory combos (`isLoading: true, error: Error`) | State constant (`'idle' \\| 'loading' \\| 'success' \\| 'error'`) + transition function; invalid states unreachable |\n| Stale promise/timer, no cancel path | Promise chain or `setTimeout` holds `setState` after the component moved on | Bind every async op to a cancel mechanism; test the cleanup path |\n| Per-element handlers on large lists | N closures/subscriptions per row, stale-closure bugs on rapid re-renders | Delegate: one parent handler + `event.target.closest(...)` when >~50 items or frequent updates |\n| Gate keyed "},{"path":"references/e2e-testing.md","content":"# E2E Testing with Playwright\n\n> When to read: when authoring Playwright end-to-end tests: directory layout, fixtures, page objects, network mocking, CI integration.\n\n## Directory Structure\n\n```\nproject-root/\n├── playwright.config.ts\n└── e2e/\n    ├── fixtures/\n    │   ├── auth.fixture.ts\n    │   └── test-data.fixture.ts\n    ├── pages/\n    │   ├── base.page.ts\n    │   └── <page-name>.page.ts\n    ├── tests/\n    │   ├── auth/\n    │   │   └── login.spec.ts\n    │   └── smoke/\n    │       └── critical-paths.spec.ts\n    └── utils/\n        └── api-helpers.ts\n```\n\nNaming: tests `<feature>.spec.ts`, page objects `<page>.page.ts`, fixtures `<concern>.fixture.ts`.\n\n## Configuration\n\nKeep this config at the project root and run the CLI from that root. Playwright resolves `testDir` relative to the config file. For a nested config, adjust its relative directories and pass `--config <path>` explicitly.\n\n```typescript\nimport { defineConfig, devices } from '@playwright/test';\n\nexport default defineConfig({\n  testDir: './e2e/tests',\n  fullyParallel: true,\n  forbidOnly: !!process.env.CI,\n  retries: process.env.CI ? 2 : 0,\n  workers: process.env.CI ? 1 : undefined,\n  reporter: 'html',\n  expect: {\n    toHaveScreenshot: { animations: 'disabled' },\n  },\n  use: {\n    baseURL: 'http://localhost:5173',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n  },\n  projects: [\n    { name: 'setup', testDir: './e2e/fixtures', testMatch: 'auth.fixture.ts' },\n    {\n      name: 'chromium',\n      use: { ...devices['Desktop Chrome'], storageState: 'e2e/.auth/user.json' },\n      dependencies: ['setup'],\n    },\n  ],\n  webServer: {\n    command: 'npm run dev',\n    url: 'http://localhost:5173',\n    reuseExistingServer: !process.env.CI,\n  },\n});\n```\n\n## Page Object Model\n\nTests never use selectors directly; page objects encapsulate all locators and actions.\n\n```typescript\n// e2e/pages/base.page.ts\nimport { type Page, type Locator } from '@playwright/test';\n\nexport abstract class BasePage {\n  constructor(protected readonly page: Page) {}\n  abstract goto(): Promise<void>;\n  abstract readonly ready: Locator;\n  async waitForLoad() { await this.ready.waitFor(); }\n  get toast(): Locator { return this.page.getByRole('alert'); }\n}\n\n// e2e/pages/users.page.ts\nexport class UsersPage extends BasePage {\n  readonly ready: Locator;\n  readonly createButton: Locator;\n  readonly searchInput: Locator;\n\n  constructor(page: Page) {\n    super(page);\n    this.ready = page.getByRole('heading', { name: /users/i });\n    this.createButton = page.getByRole('button', { name: /create/i });\n    this.searchInput = page.getByRole('searchbox', { name: /search/i });\n  }\n\n  async goto() {\n    await this.page.goto('/users');\n    await this.waitForLoad();\n  }\n\n  async searchFor(query: string) {\n    const resp = this.page.waitForResponse('**/api/users?*');\n    await this.searchInput.fill(query);\n    await resp;\n  }\n}\n```\n\nRules: locators as public readonly properties, actions as async methods with internal waits, no"},{"path":"references/locale-synchronization.md","content":"# JSON locale synchronization\n\nSynchronize the requested messages with the application's installed message formatter and usage context. Produce a focused locale diff and report structural checks separately from language review.\n\n1. Read the locale configuration and source messages. Trace each changed key to its component or call site. Identify the message's meaning, UI role, interpolation values, and space constraints; a key name alone does not establish translation context.\n2. Compare source history to identify added, changed, and removed messages. If history is unavailable, report translation staleness as unknown. Key parity alone cannot show whether an existing translation still matches a changed source message.\n3. Update only the authorized keys and locales. Preserve unrelated translations, non-string values, and array structure. Confirm usage before removing a message; absence from one source file does not prove the application no longer uses the key.\n4. Preserve required placeholder names and formatter tokens exactly. Validate plural and select grammar with the installed formatter. Use the categories required by the target locale rather than copying the source locale's categories. Preserve interpolation bindings and the markup expected by the renderer; translated text may reorder placeholders or tags where the formatter permits it.\n5. Parse the edited JSON and run the repository's locale or message validation. Check key coverage against the configured fallback policy. Verify placeholder compatibility, plural branches, markup structure, and unchanged non-string values. Reject a structurally valid message that loses a required substitution or branch.\n6. Exercise changed messages in the UI, including representative plural values, long text, and right-to-left layout when applicable. Report linguistic accuracy or visual fit as unverified when no fluent review or browser check occurred. A parser or placeholder check establishes structural compatibility, not translation quality."}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, reviewing React code, or synchronizing JSON locales and reviewing translations in a React or frontend interface. For visual design and aesthetic direction, use frontend-design instead. Skill: ia-react-frontend Owner: iliaal Summary: React architecture patterns, TypeScript, Next.js, hooks, and testing. Use when working with React component structure, state management, Next.js routing, Vitest, React Testing Library, reviewing React code, or synchronizing JSON locales and reviewing translations in a React or frontend interface. For visual design and aesthetic direction, use frontend-design instead. Ta","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1610,"uniquenessScore":54,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-09T12:23:05.550Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-09T12:23:05.550Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T15:16:07.370Z","emptyReason":null},"items":[{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-10T18:48:31.762Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}