Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat: Add rules for 26 skills (AI, Cloudflare, utilities)
Jezaf86b566e978
diff --git a/skills/claude-agent-sdk/rules/claude-agent-sdk.md b/skills/claude-agent-sdk/rules/claude-agent-sdk.mdnew file mode 100644index 00000000..29c79c3e--- /dev/null+++ b/skills/claude-agent-sdk/rules/claude-agent-sdk.md@@ -0,0 +1,96 @@+---+paths: "**/*agent*.ts", "**/*.ts"+---++# Claude Agent SDK Corrections++This uses **@anthropic-ai/claude-agent-sdk v0.1.50**.++## MCP Tool Naming Convention++```typescript+/* ❌ Wrong naming */+const tool = 'mcp_server_tool'++/* ✅ Double underscores required */+const tool = 'mcp__server-name__tool-name'+// Format: mcp__<server-name>__<tool-name>+```++## No Default System Prompt++```typescript+/* ❌ Assuming default instructions */+const agent = new Agent({+ model: 'claude-sonnet-4-5-20250929',+ // No system prompt...+})++/* ✅ Always provide custom system instruction */+const agent = new Agent({+ model: 'claude-sonnet-4-5-20250929',+ system: 'You are a helpful assistant that...',+})+```++## Permission Control++```typescript+/* ✅ Implement canUseTool for security */+const agent = new Agent({+ model: 'claude-sonnet-4-5-20250929',+ canUseTool: async (tool) => {+ if (tool.name.startsWith('dangerous_')) return 'deny'+ if (tool.name === 'file_write') return 'ask'+ return 'allow'+ },+})++// Permission modes:+// 'default' - Normal permissions+// 'acceptEdits' - Auto-accept file edits+// 'bypassPermissions' - CI/CD only!+// 'plan' - Planning mode+```++## Session Forking (Unique Feature)++```typescript+/* ✅ Create branch without modifying original */+const forkedSession = await session.fork()+// Original session unchanged+// Forked session can diverge+```++## Subagent Definitions++```typescript+/* ❌ Missing required fields */+const subagent = { prompt: 'Do task' }++/* ✅ Include description and prompt */+const subagent = {+ description: 'Handles data processing tasks',+ prompt: 'Process the provided data and return results',+}+```++## Settings Priority++```+Highest → Lowest:+1. Programmatic (code)+2. Local (.claude/settings.local.json)+3. Project (.claude/settings.json)+4. User (~/.claude/settings.json)+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `mcp_server_tool` | `mcp__server__tool` (double underscores) |+| No system prompt | Always provide `system` instruction |+| Missing canUseTool | Implement permission control |+| Subagent without description | Include `description` and `prompt` |+| Tool timeout issues | >5 minutes raises error, handle long tasks |diff --git a/skills/claude-api/rules/claude-api.md b/skills/claude-api/rules/claude-api.mdnew file mode 100644index 00000000..92356d93--- /dev/null+++ b/skills/claude-api/rules/claude-api.md@@ -0,0 +1,102 @@+---+paths: "**/*.ts", "**/*.tsx", "**/*claude*.ts", "**/*anthropic*.ts"+---++# Claude API Corrections++Claude's training may reference older patterns. This uses **@anthropic-ai/sdk v0.70+**.++## Model Deprecations (Oct 2025)++```typescript+/* ❌ RETIRED models */+'claude-3.5-sonnet' // All versions retired+'claude-3-sonnet-20240229' // Retired++/* ❌ DEPRECATED */+'claude-3.7-sonnet' // Deprecated Oct 28, 2025++/* ✅ Active models */+'claude-sonnet-4-5-20250929' // Latest Sonnet+'claude-opus-4-5-20251101' // Latest Opus+'claude-haiku-4-5-20250929' // Latest Haiku+```++## Prompt Caching: cache_control on LAST Block++```typescript+/* ❌ cache_control not on last block (silently fails) */+const response = await anthropic.messages.create({+ model: 'claude-sonnet-4-5-20250929',+ messages: [+ {+ role: 'user',+ content: [+ { type: 'text', text: longDocument, cache_control: { type: 'ephemeral' } }, // Wrong position!+ { type: 'text', text: 'Summarize this' },+ ],+ },+ ],+})++/* ✅ cache_control MUST be on LAST content block */+const response = await anthropic.messages.create({+ model: 'claude-sonnet-4-5-20250929',+ messages: [+ {+ role: 'user',+ content: [+ { type: 'text', text: longDocument },+ { type: 'text', text: 'Summarize this', cache_control: { type: 'ephemeral' } }, // Correct!+ ],+ },+ ],+})+```++## Streaming Errors Occur Mid-Stream++```typescript+/* ❌ Only checking initial response */+const stream = await anthropic.messages.stream({...})+// No error handling...++/* ✅ Errors happen AFTER initial 200 response */+const stream = await anthropic.messages.stream({...})+stream.on('error', (error) => {+ console.error('Stream error:', error)+})+for await (const event of stream) {+ // Process events...+}+```++## Structured Outputs (v0.69.0+)++```typescript+/* ✅ New structured outputs feature */+const response = await anthropic.messages.create({+ model: 'claude-sonnet-4-5-20250929',+ max_tokens: 1024,+ messages: [{ role: 'user', content: 'Extract data' }],+ response_format: {+ type: 'json_schema',+ json_schema: {+ name: 'extraction',+ schema: { /* JSON Schema */ },+ },+ },+}, {+ headers: { 'anthropic-beta': 'structured-outputs-2025-11-13' },+})+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `claude-3.5-sonnet` | `claude-sonnet-4-5-20250929` |+| `claude-3.7-sonnet` | `claude-sonnet-4-5-20250929` |+| cache_control on first block | cache_control on LAST block |+| No stream error handler | Add `stream.on('error', ...)` |+| Extended thinking on Haiku | Only Sonnet 4.5 and Opus 4 support it |diff --git a/skills/cloudflare-agents/rules/cloudflare-agents.md b/skills/cloudflare-agents/rules/cloudflare-agents.mdnew file mode 100644index 00000000..0e5fbf4c--- /dev/null+++ b/skills/cloudflare-agents/rules/cloudflare-agents.md@@ -0,0 +1,110 @@+---+paths: "**/*.ts", "**/*agent*.ts", wrangler.jsonc+---++# Cloudflare Agents Corrections++## Do You Need Agents? (80% Don't)++```typescript+/* Most apps just need AI SDK directly */+// Simple chat = AI SDK+// Stateful multi-turn = Cloudflare Agents++/* Use Agents when you need: */+// - Persistent state across sessions+// - WebSocket real-time chat+// - Scheduled tasks from AI+// - Complex multi-step workflows+```++## SQLite in First Migration (Same as DOs)++```typescript+/* ❌ Cannot add SQLite later */+migrations: [+ { tag: 'v1' },+ { tag: 'v2', new_sqlite_classes: ['MyAgent'] } // Too late!+]++/* ✅ Must be in v1 */+migrations: [+ { tag: 'v1', new_sqlite_classes: ['MyAgent'] }+]+```++## MUST Export Agent Class++```typescript+/* ❌ "Binding not found" */+class MyAgent extends Agent { }++/* ✅ Export the class */+export class MyAgent extends Agent { }+```++## Authenticate in Worker BEFORE Agent++```typescript+/* ❌ Auth inside agent (too late) */+class MyAgent extends Agent {+ async onConnect() {+ if (!authenticated) throw new Error('Unauthorized')+ }+}++/* ✅ Auth in Worker before creating agent */+export default {+ async fetch(request, env) {+ const user = await authenticate(request)+ if (!user) return new Response('Unauthorized', { status: 401 })++ // Now create agent with authenticated user+ return env.AGENT.get(env.AGENT.idFromName(user.id)).fetch(request)+ }+}+```++## Workers AI SSE Parsing++```typescript+/* ❌ Expecting automatic parsing */+const stream = await env.AI.run('@cf/meta/llama-3-8b', { stream: true })++/* ✅ Manual SSE parsing required */+const reader = stream.getReader()+const decoder = new TextDecoder()+while (true) {+ const { done, value } = await reader.read()+ if (done) break+ const text = decoder.decode(value)+ // Parse SSE format: data: {...}\n\n+ for (const line of text.split('\n')) {+ if (line.startsWith('data: ')) {+ const json = JSON.parse(line.slice(6))+ // Process json.response+ }+ }+}+```++## Global Instance Naming++```typescript+/* ⚠️ Same name = same agent globally */+const id = env.AGENT.idFromName('user-123')+// Anyone with 'user-123' accesses same agent!++/* ✅ Use unique, unpredictable names */+const id = env.AGENT.idFromName(`user:${userId}:${sessionId}`)+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Agents for simple chat | AI SDK directly |+| SQLite in later migration | First migration (`v1`) |+| Auth inside agent | Auth in Worker first |+| Auto SSE parsing | Manual TextDecoder + line parsing |+| Simple `idFromName` | Include user-specific prefix |diff --git a/skills/cloudflare-browser-rendering/rules/cloudflare-browser-rendering.md b/skills/cloudflare-browser-rendering/rules/cloudflare-browser-rendering.mdnew file mode 100644index 00000000..b4684392--- /dev/null+++ b/skills/cloudflare-browser-rendering/rules/cloudflare-browser-rendering.md@@ -0,0 +1,101 @@+---+paths: "**/*.ts", "**/*browser*.ts", "**/*puppeteer*.ts", "**/*playwright*.ts"+---++# Cloudflare Browser Rendering Corrections++## MUST Pass env.MYBROWSER to launch()++```typescript+/* ❌ "Browser binding not passed" error */+import puppeteer from '@cloudflare/puppeteer'+const browser = await puppeteer.launch()++/* ✅ Pass the binding */+import puppeteer from '@cloudflare/puppeteer'+const browser = await puppeteer.launch(env.MYBROWSER)+```++## XPath Not Supported++```typescript+/* ❌ Security risk, not supported */+await page.$x('//button[@class="submit"]')++/* ✅ Use CSS selectors or page.evaluate() */+await page.$('button.submit')+// OR+await page.evaluate(() => {+ return document.evaluate(+ '//button[@class="submit"]',+ document,+ null,+ XPathResult.FIRST_ORDERED_NODE_TYPE,+ null+ ).singleNodeValue+})+```++## disconnect() vs close()++```typescript+/* ❌ close() terminates session */+await browser.close() // Session ends++/* ✅ disconnect() keeps session alive */+ctx.waitUntil(browser.disconnect()) // Session reusable+```++## Use Tabs, Not Multiple Browsers++```typescript+/* ❌ Multiple browser instances */+const browser1 = await puppeteer.launch(env.MYBROWSER)+const browser2 = await puppeteer.launch(env.MYBROWSER)++/* ✅ Use multiple tabs in one browser */+const browser = await puppeteer.launch(env.MYBROWSER)+const page1 = await browser.newPage()+const page2 = await browser.newPage()+```++## Playwright Requires compatibility_date++```typescript+/* ✅ Playwright v1.55 GA (Sept 2025) */+// wrangler.jsonc:+{+ "compatibility_date": "2025-09-15" // Required for Playwright+}+```++## Session Reuse Pattern++```typescript+/* ✅ Reuse sessions for performance */+const sessionId = await env.MYBROWSER.sessions.create({ keep_alive: 60000 })+const browser = await puppeteer.connect(env.MYBROWSER, sessionId)++// Later requests can reconnect+const browser = await puppeteer.connect(env.MYBROWSER, existingSessionId)+```++## Browser Timeout++```typescript+/* ⚠️ Default 60 second timeout */+// For longer tasks, set keep_alive+const browser = await puppeteer.launch(env.MYBROWSER, {+ keep_alive: 300000, // 5 minutes+})+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `puppeteer.launch()` no args | `puppeteer.launch(env.MYBROWSER)` |+| `page.$x()` XPath | CSS selectors or `page.evaluate()` |+| `browser.close()` | `ctx.waitUntil(browser.disconnect())` |+| Multiple browsers | Multiple tabs in one browser |+| Playwright without date | Add `compatibility_date: "2025-09-15"` |diff --git a/skills/cloudflare-d1/rules/cloudflare-d1.md b/skills/cloudflare-d1/rules/cloudflare-d1.mdnew file mode 100644index 00000000..92a9de89--- /dev/null+++ b/skills/cloudflare-d1/rules/cloudflare-d1.md@@ -0,0 +1,83 @@+---+paths: "**/*.ts", "**/*.sql", wrangler.jsonc, wrangler.toml+---++# Cloudflare D1 Corrections++## No BEGIN TRANSACTION in Migrations++```sql+/* ❌ Will cause conflicts */+BEGIN TRANSACTION;+CREATE TABLE users (...);+COMMIT;++/* ✅ D1 handles transactions automatically */+CREATE TABLE users (...);+```++## Use null, Not undefined++```typescript+/* ❌ Causes D1_TYPE_ERROR */+await db.prepare('INSERT INTO users (name, bio) VALUES (?, ?)')+ .bind('John', undefined)+ .run()++/* ✅ Use null for optional values */+await db.prepare('INSERT INTO users (name, bio) VALUES (?, ?)')+ .bind('John', null)+ .run()+```++## Always Use .prepare().bind()++```typescript+/* ❌ SQL injection vulnerability */+await db.exec(`SELECT * FROM users WHERE id = ${userId}`)++/* ✅ Use prepared statements */+await db.prepare('SELECT * FROM users WHERE id = ?')+ .bind(userId)+ .first()+```++## Batch Large Inserts++```typescript+/* ❌ Statement too long (>128KB) */+await db.exec(`INSERT INTO items VALUES ${thousands_of_rows}`)++/* ✅ Batch into 100-250 rows */+for (const batch of chunks(rows, 100)) {+ await db.batch(+ batch.map(row =>+ db.prepare('INSERT INTO items VALUES (?, ?)').bind(row.a, row.b)+ )+ )+}+```++## Use .batch() for Multiple Queries++```typescript+/* ❌ Multiple round trips */+await db.prepare('SELECT * FROM users').all()+await db.prepare('SELECT * FROM posts').all()++/* ✅ Single round trip */+const [users, posts] = await db.batch([+ db.prepare('SELECT * FROM users'),+ db.prepare('SELECT * FROM posts'),+])+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `BEGIN TRANSACTION` in migrations | Remove it (D1 auto-handles) |+| `undefined` in bind | `null` |+| String interpolation in SQL | `.prepare().bind()` |+| Multiple separate queries | `.batch([...])` |+| Single large INSERT | Chunk into batches of 100-250 |diff --git a/skills/cloudflare-durable-objects/rules/cloudflare-durable-objects.md b/skills/cloudflare-durable-objects/rules/cloudflare-durable-objects.mdnew file mode 100644index 00000000..e1d9afa0--- /dev/null+++ b/skills/cloudflare-durable-objects/rules/cloudflare-durable-objects.md@@ -0,0 +1,102 @@+---+paths: "**/*.ts", "**/*durable*.ts", wrangler.jsonc+---++# Cloudflare Durable Objects Corrections++## MUST Export Class from Worker++```typescript+/* ❌ "Binding not found" error */+class MyDO extends DurableObject {+ // ...+}+// Missing export!++/* ✅ Export the class */+export class MyDO extends DurableObject {+ // ...+}+export default { fetch: handler } // Also export default+```++## SQLite: new_sqlite_classes in FIRST Migration++```typescript+/* ❌ Cannot add SQLite to existing class */+// migrations: [+// { tag: 'v1' },+// { tag: 'v2', new_sqlite_classes: ['MyDO'] } // Too late!+// ]++/* ✅ Must be in v1 migration */+// wrangler.jsonc:+{+ "durable_objects": {+ "bindings": [{ "name": "MY_DO", "class_name": "MyDO" }]+ },+ "migrations": [+ { "tag": "v1", "new_sqlite_classes": ["MyDO"] } // First migration!+ ]+}+```++## WebSocket Hibernation: Use ctx.acceptWebSocket++```typescript+/* ❌ Manual accept breaks hibernation */+webSocketPair[1].accept()++/* ✅ Use context method for hibernation support */+this.ctx.acceptWebSocket(webSocket)+```++## In-Memory State Lost on Hibernation++```typescript+/* ❌ State cleared after ~10s idle */+class MyDO extends DurableObject {+ userData = {} // Lost on hibernation!+}++/* ✅ Persist WebSocket metadata */+this.ctx.acceptWebSocket(ws)+ws.serializeAttachment({ userId, roomId })++// Retrieve on wake:+const { userId } = ws.deserializeAttachment()+```++## Use Alarms, Not setTimeout++```typescript+/* ❌ setTimeout prevents hibernation */+setTimeout(() => this.cleanup(), 60000)++/* ✅ Use alarms API */+await this.ctx.storage.setAlarm(Date.now() + 60000)++async alarm() {+ await this.cleanup()+}+```++## Always Call super() First++```typescript+/* ✅ Required in constructor */+constructor(ctx: DurableObjectState, env: Env) {+ super(ctx, env) // Must be first!+ // Then your initialization...+}+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Class not exported | Add `export class MyDO` |+| SQLite in later migration | Move to first migration (`v1`) |+| `ws.accept()` | `this.ctx.acceptWebSocket(ws)` |+| Instance properties for state | `serializeAttachment()` for WebSocket data |+| `setTimeout` | `setAlarm()` |diff --git a/skills/cloudflare-hyperdrive/rules/cloudflare-hyperdrive.md b/skills/cloudflare-hyperdrive/rules/cloudflare-hyperdrive.mdnew file mode 100644index 00000000..7cd90f82--- /dev/null+++ b/skills/cloudflare-hyperdrive/rules/cloudflare-hyperdrive.md@@ -0,0 +1,95 @@+---+paths: "**/*.ts", wrangler.jsonc+---++# Cloudflare Hyperdrive Corrections++## nodejs_compat REQUIRED++```typescript+/* ❌ "No such module 'node:*'" error */+// Missing compatibility flag++/* ✅ Add to wrangler.jsonc */+{+ "compatibility_flags": ["nodejs_compat"]+}+```++## Connection Cleanup: Use waitUntil++```typescript+/* ❌ Blocks response */+export default {+ async fetch(request, env, ctx) {+ const client = new Client(env.HYPERDRIVE.connectionString)+ await client.connect()+ const result = await client.query('SELECT * FROM users')+ await client.end() // Blocks!+ return Response.json(result.rows)+ }+}++/* ✅ Non-blocking cleanup with waitUntil */+export default {+ async fetch(request, env, ctx) {+ const client = new Client(env.HYPERDRIVE.connectionString)+ await client.connect()+ const result = await client.query('SELECT * FROM users')+ ctx.waitUntil(client.end()) // Non-blocking!+ return Response.json(result.rows)+ }+}+```++## Pool Max: 5 Connections++```typescript+/* ❌ Too many connections */+const pool = new Pool({+ connectionString: env.HYPERDRIVE.connectionString,+ max: 10, // Workers limit is 6 total!+})++/* ✅ Max 5 connections */+const pool = new Pool({+ connectionString: env.HYPERDRIVE.connectionString,+ max: 5, // Leave room for other connections+})+```++## mysql2: Disable eval++```typescript+/* ❌ "eval() disallowed" error */+import mysql from 'mysql2/promise'+const conn = await mysql.createConnection(env.HYPERDRIVE.connectionString)++/* ✅ Disable eval for Workers */+import mysql from 'mysql2/promise'+const conn = await mysql.createConnection({+ uri: env.HYPERDRIVE.connectionString,+ disableEval: true, // Required!+})+```++## Use Prepared Statements++```typescript+/* ✅ Better caching with prepared statements */+const result = await client.query(+ 'SELECT * FROM users WHERE id = $1',+ [userId]+)+// Hyperdrive caches prepared statement plans+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Missing `nodejs_compat` | Add to `compatibility_flags` |+| `await client.end()` | `ctx.waitUntil(client.end())` |+| `max: 10` in pool | `max: 5` (Workers limit) |+| mysql2 without config | Add `disableEval: true` |+| String interpolation | Use prepared statements with `$1` params |diff --git a/skills/cloudflare-images/rules/cloudflare-images.md b/skills/cloudflare-images/rules/cloudflare-images.mdnew file mode 100644index 00000000..c5486df4--- /dev/null+++ b/skills/cloudflare-images/rules/cloudflare-images.md@@ -0,0 +1,93 @@+---+paths: "**/*.ts", "**/*image*.ts"+---++# Cloudflare Images Corrections++## Direct Creator Upload: Backend Only++```typescript+/* ❌ Calling from browser */+fetch('https://api.cloudflare.com/client/v4/accounts/.../images/v2/direct_upload', {+ headers: { 'Authorization': `Bearer ${apiToken}` } // Exposed!+})++/* ✅ Call from backend, send URL to frontend */+// Backend:+const response = await fetch(+ `https://api.cloudflare.com/client/v4/accounts/${accountId}/images/v2/direct_upload`,+ { method: 'POST', headers: { 'Authorization': `Bearer ${apiToken}` } }+)+const { result } = await response.json()+return Response.json({ uploadURL: result.uploadURL })++// Frontend uses the uploadURL+```++## Use multipart/form-data, Field Named "file"++```typescript+/* ❌ Wrong content type or field name */+const formData = new FormData()+formData.append('image', file) // Wrong field name!++/* ✅ Field MUST be named "file" */+const formData = new FormData()+formData.append('file', file) // Correct!++// Let browser set Content-Type (includes boundary)+await fetch(uploadURL, { method: 'POST', body: formData })+```++## Flexible Variants + Signed URLs Incompatible++```typescript+/* ❌ Cannot use together */+// Flexible variants with requireSignedURLs=true++/* ✅ Use named variants for private images */+// Create named variant in dashboard+// Use: /cdn-cgi/imagedelivery/{hash}/{imageId}/myVariant+```++## AI Face Cropping (August 2025)++```typescript+/* ✅ New gravity=face parameter */+const url = `https://imagedelivery.net/${hash}/${imageId}/w=300,h=300,gravity=face,zoom=1.2`+// GPU-based RetinaFace detection+// zoom: 0.5 (zoomed out) to 2.0 (zoomed in)+```++## Avoid Request Loops++```typescript+/* ❌ Error 9403: request loop */+// Worker fetching its own URL++/* ✅ Use binding directly or external URL */+const image = await env.IMAGES.get(imageId)+// OR fetch from external source+```++## Always Validate Server-Side++```typescript+/* ❌ Trusting client validation */+if (file.type.startsWith('image/')) { /* upload */ }++/* ✅ Validate on server */+const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif']+const contentType = request.headers.get('content-type')+// Also check file magic bytes if needed+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Direct upload from browser | Backend generates URL, frontend uploads |+| Field name 'image' | Field name 'file' |+| Flexible + signed URLs | Named variants for private images |+| Fetching own Worker URL | Use binding or external URL |+| Client-only validation | Always validate server-side |diff --git a/skills/cloudflare-kv/rules/cloudflare-kv.md b/skills/cloudflare-kv/rules/cloudflare-kv.mdnew file mode 100644index 00000000..f133e837--- /dev/null+++ b/skills/cloudflare-kv/rules/cloudflare-kv.md@@ -0,0 +1,91 @@+---+paths: "**/*.ts", wrangler.jsonc, wrangler.toml+---++# Cloudflare KV Corrections++## Rate Limit: 1 Write Per Second Per Key++```typescript+/* ❌ 429 error - too many writes to same key */+for (const item of items) {+ await env.KV.put('counter', String(count++))+}++/* ✅ Consolidate writes or use different keys */+// Option 1: Single write+await env.KV.put('counter', String(finalCount))++// Option 2: Different keys+await env.KV.put(`counter:${Date.now()}`, value)+```++## returnMetadata Changed to Enum++```typescript+/* ❌ Old boolean syntax */+await env.KV.get(key, { returnMetadata: true })++/* ✅ New enum syntax (V2) */+await env.KV.get(key, { returnMetadata: 'all' })+// Options: 'all' | 'indexed' | 'none'+```++## cacheTtl Minimum 60 Seconds++```typescript+/* ❌ Error: TTL too low */+await env.KV.get(key, { cacheTtl: 30 })++/* ✅ Minimum 60 seconds */+await env.KV.get(key, { cacheTtl: 60 })+```++## Check list_complete for Pagination++```typescript+/* ❌ Wrong pagination check */+const result = await env.KV.list()+if (result.keys.length === 0) { /* done */ }++/* ✅ Use list_complete flag */+let cursor: string | undefined+do {+ const result = await env.KV.list({ cursor })+ // Process result.keys...+ cursor = result.list_complete ? undefined : result.cursor+} while (cursor)+```++## Use Bulk Operations++```typescript+/* ❌ Multiple operations (counts against limits) */+await env.KV.get('key1')+await env.KV.get('key2')+await env.KV.get('key3')++/* ✅ Bulk operations (counts as 1) */+// For writes, use batch in wrangler or Workers KV API+// Max 10,000 keys per bulk operation+```++## Eventual Consistency (~60 seconds)++```typescript+/* ⚠️ Reads may be stale for ~60 seconds globally */+await env.KV.put('key', 'value')+const value = await env.KV.get('key') // May return old value!++/* For strong consistency, use Durable Objects instead */+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Multiple writes to same key | Consolidate or use different keys |+| `returnMetadata: true` | `returnMetadata: 'all'` |+| `cacheTtl < 60` | Minimum 60 seconds |+| `keys.length === 0` for pagination | Check `list_complete` flag |+| Strong consistency needs | Use Durable Objects |diff --git a/skills/cloudflare-mcp-server/rules/cloudflare-mcp-server.md b/skills/cloudflare-mcp-server/rules/cloudflare-mcp-server.mdnew file mode 100644index 00000000..6e40c1cd--- /dev/null+++ b/skills/cloudflare-mcp-server/rules/cloudflare-mcp-server.md@@ -0,0 +1,117 @@+---+paths: "**/*.ts", "**/*mcp*.ts", wrangler.jsonc+---++# Cloudflare MCP Server Corrections++## #1 Failure: Base Path Mismatch++```typescript+/* ❌ Server and client paths don't match */+// Server:+app.get('/sse', (c) => mcp.serveSSE('/sse').fetch(c.req.raw, c.env))++// Client config:+{ "url": "https://worker.dev/mcp" } // Wrong path!++/* ✅ Test with curl, match exactly */+// 1. Test: curl https://worker.dev/sse+// 2. Use same URL in client config+{ "url": "https://worker.dev/sse" }+```++## MUST Export McpAgent Class++```typescript+/* ❌ "Binding not found" error */+class MyMcpAgent extends McpAgent { }++/* ✅ Export the class */+export class MyMcpAgent extends McpAgent { }+```++## Use startsWith for Path Matching++```typescript+/* ❌ Exact match breaks sub-paths */+if (pathname === '/sse') { }++/* ✅ Use startsWith */+if (pathname.startsWith('/sse')) { }+```++## Add OPTIONS Handler for CORS++```typescript+/* ❌ Browser clients blocked by CORS preflight */+app.get('/sse', handler)++/* ✅ Handle OPTIONS for browser clients */+app.options('/sse', (c) => {+ return new Response(null, {+ headers: {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',+ 'Access-Control-Allow-Headers': 'Content-Type',+ },+ })+})+app.get('/sse', handler)+```++## OAuth Redirect URIs Must Match++```typescript+/* ❌ Works in dev, fails after deploy */+// OAuth configured for localhost+// Deployed to worker.dev++/* ✅ Update ALL OAuth URLs after deployment */+// 1. Update OAuth provider settings+// 2. Update client config+// 3. Test with curl before integrating+```++## WebSocket State: Use Storage++```typescript+/* ❌ Instance properties lost on hibernation */+class MyAgent extends McpAgent {+ userData = {} // Lost!+}++/* ✅ Use this.state.storage */+class MyAgent extends McpAgent {+ async saveData(data) {+ await this.state.storage.put('userData', data)+ }+ async getData() {+ return await this.state.storage.get('userData')+ }+}+```++## Durable Objects Migration Required++```jsonc+/* ✅ wrangler.jsonc */+{+ "durable_objects": {+ "bindings": [{ "name": "MCP_AGENT", "class_name": "MyMcpAgent" }]+ },+ "migrations": [+ { "tag": "v1", "new_classes": ["MyMcpAgent"] }+ ]+}+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Different server/client paths | Test with curl, use exact URL |+| Class not exported | Add `export class MyMcpAgent` |+| `pathname === '/sse'` | `pathname.startsWith('/sse')` |+| Missing CORS | Add OPTIONS handler |+| Instance properties | Use `this.state.storage` |+| Missing migration | Add to wrangler.jsonc migrations |diff --git a/skills/cloudflare-queues/rules/cloudflare-queues.md b/skills/cloudflare-queues/rules/cloudflare-queues.mdnew file mode 100644index 00000000..7e7ef6d2--- /dev/null+++ b/skills/cloudflare-queues/rules/cloudflare-queues.md@@ -0,0 +1,94 @@+---+paths: "**/*.ts", wrangler.jsonc, wrangler.toml+---++# Cloudflare Queues Corrections++## CRITICAL: Configure Dead Letter Queue++```typescript+/* ❌ Messages PERMANENTLY DELETED after max_retries */+// No DLQ configured...++/* ✅ Always configure DLQ in production */+// wrangler.jsonc:+{+ "queues": {+ "consumers": [{+ "queue": "my-queue",+ "dead_letter_queue": "my-queue-dlq", // Required!+ "max_retries": 3+ }]+ }+}+```++## Message Size Limit: 128KB++```typescript+/* ❌ Message too large */+await env.QUEUE.send({ largeData: megabytesOfData })++/* ✅ Store large data in R2, send reference */+const key = `data/${crypto.randomUUID()}`+await env.BUCKET.put(key, largeData)+await env.QUEUE.send({ dataRef: key })+```++## Explicit Ack for Non-Idempotent Operations++```typescript+/* ❌ Entire batch retried if one fails */+async queue(batch, env) {+ for (const msg of batch.messages) {+ await processMessage(msg) // If one fails, all retry+ }+}++/* ✅ Explicit ack for DB writes, payments, API calls */+async queue(batch, env) {+ for (const msg of batch.messages) {+ try {+ await processMessage(msg)+ msg.ack() // Explicit acknowledgment+ } catch (error) {+ msg.retry({ delaySeconds: 60 * Math.pow(2, msg.attempts - 1) })+ }+ }+}+```++## Don't Assume FIFO Ordering++```typescript+/* ❌ Relying on message order */+// Messages may arrive out of order++/* ✅ Include timestamp/sequence if order matters */+await env.QUEUE.send({+ data: payload,+ timestamp: Date.now(),+ sequence: getNextSequence(),+})+```++## Throughput Limit: 5,000 msg/s++```typescript+/* ✅ Use sendBatch with delays for high throughput */+const batches = chunks(messages, 100)+for (const batch of batches) {+ await env.QUEUE.sendBatch(batch)+ await new Promise(r => setTimeout(r, 100)) // Throttle+}+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| No DLQ configured | Add `dead_letter_queue` in wrangler.jsonc |+| Large message body | Store in R2, send reference |+| No explicit ack | Use `msg.ack()` for non-idempotent ops |+| Assuming FIFO order | Include timestamp/sequence |+| High-volume sends | Use `sendBatch()` with throttling |diff --git a/skills/cloudflare-r2/rules/cloudflare-r2.md b/skills/cloudflare-r2/rules/cloudflare-r2.mdnew file mode 100644index 00000000..73b14aad--- /dev/null+++ b/skills/cloudflare-r2/rules/cloudflare-r2.md@@ -0,0 +1,84 @@+---+paths: "**/*.ts", wrangler.jsonc, wrangler.toml+---++# Cloudflare R2 Corrections++## Always Set Content-Type++```typescript+/* ❌ Files download as binary */+await env.BUCKET.put('image.jpg', imageData)++/* ✅ Set httpMetadata.contentType */+await env.BUCKET.put('image.jpg', imageData, {+ httpMetadata: { contentType: 'image/jpeg' },+})+```++## Multipart Upload Limits++```typescript+/* ❌ Part too small or too large */+// Parts < 5MB or > 100MB will fail++/* ✅ Keep parts between 5MB and 100MB */+const PART_SIZE = 10 * 1024 * 1024 // 10MB recommended+```++## Presigned URLs: Never Expose Keys++```typescript+/* ❌ Keys in frontend */+const s3 = new S3Client({+ credentials: { accessKeyId, secretAccessKey }, // In browser!+})++/* ✅ Generate presigned URLs server-side only */+// Worker generates URL, sends to client+const presignedUrl = await generatePresignedUrl(key, { expiresIn: 3600 })+return new Response(JSON.stringify({ uploadUrl: presignedUrl }))+```++## Batch Delete Limit++```typescript+/* ❌ More than 1000 keys */+await env.BUCKET.delete(arrayOf2000Keys)++/* ✅ Chunk into batches of 1000 */+for (const batch of chunks(keys, 1000)) {+ await env.BUCKET.delete(batch)+}+```++## Use head() for Metadata++```typescript+/* ❌ Downloads entire object */+const obj = await env.BUCKET.get(key)+const size = obj?.size++/* ✅ Use head() to get metadata without body */+const head = await env.BUCKET.head(key)+const size = head?.size+```++## Conditional Operations++```typescript+/* ✅ Prevent accidental overwrites */+await env.BUCKET.put(key, data, {+ onlyIf: { etagDoesNotMatch: '*' }, // Only if doesn't exist+})+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Missing `contentType` | Set `httpMetadata.contentType` |+| Part size outside 5-100MB | Use 10MB chunks |+| Credentials in browser | Generate presigned URLs server-side |+| Deleting >1000 keys | Batch into chunks of 1000 |+| `get()` for metadata only | Use `head()` |diff --git a/skills/cloudflare-turnstile/rules/cloudflare-turnstile.md b/skills/cloudflare-turnstile/rules/cloudflare-turnstile.mdnew file mode 100644index 00000000..dd4e92f9--- /dev/null+++ b/skills/cloudflare-turnstile/rules/cloudflare-turnstile.md@@ -0,0 +1,95 @@+---+paths: "**/*.ts", "**/*.tsx", "**/*turnstile*.ts"+---++# Cloudflare Turnstile Corrections++## Server-Side Validation MANDATORY++```typescript+/* ❌ SECURITY VULNERABILITY - client-only validation */+// Frontend gets token, sends to your API+// API trusts token without verification++/* ✅ ALWAYS call Siteverify API */+async function verifyTurnstile(token: string, env: Env): Promise<boolean> {+ const response = await fetch(+ 'https://challenges.cloudflare.com/turnstile/v0/siteverify',+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ secret: env.TURNSTILE_SECRET_KEY,+ response: token,+ }),+ }+ )+ const result = await response.json()+ return result.success === true+}+```++## Siteverify: POST Only, Not GET++```typescript+/* ❌ GET not supported (unlike reCAPTCHA) */+fetch(`https://challenges.cloudflare.com/turnstile/v0/siteverify?secret=...&response=...`)++/* ✅ Must use POST */+fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {+ method: 'POST',+ body: new URLSearchParams({ secret, response: token }),+})+```++## Token Expires in 5 Minutes++```typescript+/* ⚠️ Tokens have 300 second TTL */+// User completes challenge+// Token valid for 5 minutes only+// After that, siteverify returns success: false++/* ✅ Verify immediately after form submission */+```++## Never Expose Secret Key++```typescript+/* ❌ Secret in frontend */+const TURNSTILE_SECRET = 'xxx' // In client code!++/* ✅ Secret only in backend environment */+// .dev.vars or wrangler secret+// Access via env.TURNSTILE_SECRET_KEY+```++## Test Keys for Development++```typescript+/* ✅ Dummy keys for testing */+// Site key (always passes): 1x00000000000000000000AA+// Site key (always fails): 2x00000000000000000000AB+// Site key (forces challenge): 3x00000000000000000000FF++// Secret key (always passes): 1x0000000000000000000000000000000AA+// Secret key (always fails): 2x0000000000000000000000000000000AB+```++## CSP Configuration Required++```typescript+/* ✅ Allow Turnstile iframe in CSP */+// frame-src: https://challenges.cloudflare.com+// script-src: https://challenges.cloudflare.com+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Client-only validation | ALWAYS call Siteverify API server-side |+| GET request to Siteverify | POST with URLSearchParams body |+| Secret key in frontend | Keep in backend env only |+| Production keys in dev | Use dummy test keys |+| Missing CSP | Allow challenges.cloudflare.com |diff --git a/skills/cloudflare-vectorize/rules/cloudflare-vectorize.md b/skills/cloudflare-vectorize/rules/cloudflare-vectorize.mdnew file mode 100644index 00000000..08200443--- /dev/null+++ b/skills/cloudflare-vectorize/rules/cloudflare-vectorize.md@@ -0,0 +1,94 @@+---+paths: "**/*.ts", "**/*vector*.ts", wrangler.jsonc+---++# Cloudflare Vectorize Corrections++## V2: Mutations Are Now Async++```typescript+/* ❌ Expecting synchronous insert */+await env.VECTORIZE.insert([{ id: '1', values: [...] }])+// Assuming it's immediately queryable...++/* ✅ Mutations return mutationId, are async */+const { mutationId } = await env.VECTORIZE.insert([+ { id: '1', values: [...], metadata: { title: 'Doc' } }+])+// May take a moment to be queryable+```++## returnMetadata is Now Enum++```typescript+/* ❌ Old boolean syntax */+const results = await env.VECTORIZE.query(vector, {+ returnMetadata: true, // Error!+})++/* ✅ New enum syntax */+const results = await env.VECTORIZE.query(vector, {+ returnMetadata: 'all', // 'all' | 'indexed' | 'none'+})+```++## Create Metadata Indexes BEFORE Inserting++```typescript+/* ❌ Vectors added before index won't be filterable */+await env.VECTORIZE.insert([{ id: '1', values, metadata: { category: 'A' } }])+// Then creating index... too late!++/* ✅ Create index first, then insert */+// 1. Create index in dashboard or wrangler+// 2. Then insert vectors+await env.VECTORIZE.insert([{ id: '1', values, metadata: { category: 'A' } }])+// Now filtering works+```++## Match Embedding Dimensions++```typescript+/* ❌ Dimension mismatch */+// Index: 768 dimensions+// Embedding: 1536 dimensions (OpenAI default)++/* ✅ Match dimensions exactly */+// BGE-base: 768 dimensions+// OpenAI text-embedding-3-small: 1536 dimensions+// OpenAI text-embedding-3-large: 3072 dimensions++// Create index matching your embedding model:+// wrangler vectorize create my-index --dimensions=768 --metric=cosine+```++## Filter Size Limit++```typescript+/* ❌ Filter exceeds 2048 bytes */+const results = await env.VECTORIZE.query(vector, {+ filter: { tags: veryLongArrayOfTags }, // May exceed limit+})++/* ✅ Simplify filters */+const results = await env.VECTORIZE.query(vector, {+ filter: { category: 'tech' }, // Keep filters simple+})+```++## V1 Deprecation++```typescript+/* ⚠️ Cannot create new V1 indexes after December 2024 */+// Migrate existing V1 indexes to V2+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Synchronous mutations | Handle async with `mutationId` |+| `returnMetadata: true` | `returnMetadata: 'all'` |+| Index after insert | Create metadata indexes BEFORE inserting |+| Mismatched dimensions | Match embedding model to index dimensions |+| Complex filters | Keep filters under 2048 bytes |diff --git a/skills/cloudflare-workers-ai/rules/cloudflare-workers-ai.md b/skills/cloudflare-workers-ai/rules/cloudflare-workers-ai.mdnew file mode 100644index 00000000..d9b467eb--- /dev/null+++ b/skills/cloudflare-workers-ai/rules/cloudflare-workers-ai.md@@ -0,0 +1,97 @@+---+paths: "**/*.ts", wrangler.jsonc+---++# Cloudflare Workers AI Corrections++## max_tokens Breaking Change (April 2025)++```typescript+/* ⚠️ max_tokens now correctly defaults to 256 */+// Before April 2025: max_tokens was ignored+// After: Actually enforced, default 256++/* ✅ Always set max_tokens explicitly */+const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {+ prompt: 'Write a story',+ max_tokens: 1024, // Set explicitly!+})+```++## BGE Embeddings Pooling Change (April 2025)++```typescript+/* ❌ mean pooling not backwards compatible */+const result = await env.AI.run('@cf/baai/bge-base-en-v1.5', {+ text: 'Hello',+ pooling: 'mean', // Changed behavior!+})++/* ✅ Use cls pooling */+const result = await env.AI.run('@cf/baai/bge-base-en-v1.5', {+ text: 'Hello',+ pooling: 'cls', // Recommended+})+```++## Always Use Streaming for Text++```typescript+/* ❌ Buffering issues with large responses */+const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {+ prompt: 'Write a long story',+})++/* ✅ Use streaming to prevent buffering */+const stream = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {+ prompt: 'Write a long story',+ stream: true,+})+return new Response(stream, {+ headers: { 'Content-Type': 'text/event-stream' },+})+```++## Manual SSE Parsing Required++```typescript+/* ✅ Parse SSE format manually */+const stream = await env.AI.run(model, { prompt, stream: true })+const reader = stream.getReader()+const decoder = new TextDecoder()++while (true) {+ const { done, value } = await reader.read()+ if (done) break+ const chunk = decoder.decode(value)+ // Format: data: {"response":"text"}\n\n+ for (const line of chunk.split('\n')) {+ if (line.startsWith('data: ') && line !== 'data: [DONE]') {+ const { response } = JSON.parse(line.slice(6))+ // Use response text+ }+ }+}+```++## Model Deprecations (October 2025)++```typescript+/* ❌ Older models deprecated */+'@cf/meta/llama-2-7b-chat' // Deprecated++/* ✅ Use current models */+'@cf/meta/llama-3.1-8b-instruct' // Text+'@cf/meta/llama-3.2-11b-vision' // Vision+'@cf/baai/bge-base-en-v1.5' // Embeddings+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| No `max_tokens` set | Always set explicitly |+| `pooling: 'mean'` for BGE | `pooling: 'cls'` |+| Non-streaming for text | Always use `stream: true` |+| Auto SSE parsing | Manual TextDecoder + line parsing |+| Llama 2 models | Llama 3.1/3.2 models |diff --git a/skills/cloudflare-workflows/rules/cloudflare-workflows.md b/skills/cloudflare-workflows/rules/cloudflare-workflows.mdnew file mode 100644index 00000000..2f2c633d--- /dev/null+++ b/skills/cloudflare-workflows/rules/cloudflare-workflows.md@@ -0,0 +1,94 @@+---+paths: "**/*.ts", "**/*workflow*.ts", wrangler.jsonc+---++# Cloudflare Workflows Corrections++## I/O MUST Be Inside step.do()++```typescript+/* ❌ I/O outside step context */+async run(event, step) {+ const data = await fetch('https://api.example.com') // Error!+ await step.do('process', async () => {+ return processData(data)+ })+}++/* ✅ All I/O inside step.do() */+async run(event, step) {+ const data = await step.do('fetch', async () => {+ const res = await fetch('https://api.example.com')+ return res.json()+ })+ await step.do('process', async () => {+ return processData(data)+ })+}+```++## Only JSON-Serializable Values++```typescript+/* ❌ Functions, symbols, undefined not allowed */+await step.do('bad', async () => {+ return {+ callback: () => {}, // Error!+ data: undefined, // Error!+ }+})++/* ✅ Return only JSON-serializable values */+await step.do('good', async () => {+ return {+ status: 'complete',+ data: null, // Use null instead of undefined+ }+})+```++## NonRetryableError MUST Have Message++```typescript+/* ❌ Empty message behaves differently in dev vs prod */+throw new NonRetryableError('') // Buggy!++/* ✅ Always provide message */+throw new NonRetryableError('Invalid credentials')+throw new NonRetryableError('Validation failed: missing email')+```++## step.sleep() Doesn't Count Toward Limit++```typescript+/* ✅ Sleep doesn't count against 1,024 step limit */+await step.sleep('wait', '1 hour')+// This is free - use liberally for delays+```++## Use catch for Optional Steps++```typescript+/* ✅ Graceful degradation */+let enrichedData = null+try {+ enrichedData = await step.do('enrich', async () => {+ return await callOptionalAPI()+ })+} catch {+ // Continue without enrichment+}+await step.do('process', async () => {+ return process(data, enrichedData)+})+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| fetch() outside step | Move inside `step.do()` |+| Returning functions/undefined | Return JSON-serializable only |+| `NonRetryableError('')` | Include descriptive message |+| Worrying about sleep limits | `step.sleep()` is unlimited |+| All-or-nothing steps | Use try/catch for optional steps |diff --git a/skills/fastmcp/rules/fastmcp.md b/skills/fastmcp/rules/fastmcp.mdnew file mode 100644index 00000000..b47f46de--- /dev/null+++ b/skills/fastmcp/rules/fastmcp.md@@ -0,0 +1,120 @@+---+paths: "**/*.py", "**/*mcp*.py"+---++# FastMCP Corrections++This project uses **fastmcp>=2.13.1**.++## Module-Level Server Export Required++```python+# ❌ Server inside function (Cloud can't find it)+def create_server():+ mcp = FastMCP("my-server")+ return mcp++# ✅ Module-level export+mcp = FastMCP("my-server")++def my_tool():+ pass+```++## Resource URI: Include Scheme++```python+# ❌ Missing scheme[email protected]("users")+def get_users():+ pass++# ✅ Include scheme prefix[email protected]("data://users")+def get_users():+ pass+[email protected]("user://{user_id}")+def get_user(user_id: str):+ pass+```++## Resource Params Must Match Template++```python+# ❌ Parameter name mismatch[email protected]("user://{user_id}")+def get_user(id: str): # Wrong param name!+ pass++# ✅ Names must match exactly[email protected]("user://{user_id}")+def get_user(user_id: str): # Matches template+ pass+```++## v2.13.0: Lifespan Is Per-Server-Instance++```python+# ⚠️ Breaking change in v2.13.0+# Lifespan now runs once per server instance, not per session++# ✅ Use for server-wide initialization+async def lifespan(context):+ db = await init_database()+ yield {"db": db}+ await db.close()+```++## FastAPI: Pass Lifespan++```python+# ❌ Database never initializes+app = FastAPI()++# ✅ Pass MCP lifespan to FastAPI+app = FastAPI(lifespan=mcp.lifespan)+```++## Production Storage Backend++```python+# ❌ Memory storage (data lost on restart)+# Default behavior++# ✅ Use persistent storage in production+from fastmcp.storage import DiskStore+from fastmcp.security import FernetEncryptionWrapper++storage = FernetEncryptionWrapper(+ DiskStore("/data/mcp"),+ key=os.getenv("ENCRYPTION_KEY")+)+```++## OAuth: Enable Consent Screen++```python+# ❌ Security vulnerability (confused deputy attack)+auth = OAuthProxy(...)++# ✅ Enable consent screen+auth = OAuthProxy(+ ...,+ enable_consent_screen=True # Required for security!+)+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Server inside function | Module-level `mcp = FastMCP()` |+| `@mcp.resource("users")` | `@mcp.resource("data://users")` |+| Mismatched param names | Match function params to URI template |+| Per-session lifespan | Per-server lifespan (v2.13.0+) |+| Missing FastAPI lifespan | `FastAPI(lifespan=mcp.lifespan)` |+| Memory storage in prod | DiskStore or RedisStore |+| No consent screen | `enable_consent_screen=True` |diff --git a/skills/google-gemini-api/rules/google-gemini-api.md b/skills/google-gemini-api/rules/google-gemini-api.mdnew file mode 100644index 00000000..ab50872e--- /dev/null+++ b/skills/google-gemini-api/rules/google-gemini-api.md@@ -0,0 +1,96 @@+---+paths: "**/*.ts", "**/*.tsx", "**/*gemini*.ts", package.json+---++# Google Gemini API Corrections++Claude's training may reference the deprecated SDK. This project uses **@google/genai v1.30+**.++## CRITICAL: SDK Migration++```typescript+/* ❌ DEPRECATED - Sunset November 30, 2025 */+import { GoogleGenerativeAI } from '@google/generative-ai'+const genAI = new GoogleGenerativeAI(apiKey)+const model = genAI.getGenerativeModel({ model: 'gemini-pro' })++/* ✅ CURRENT SDK */+import { GoogleGenAI } from '@google/genai'+const ai = new GoogleGenAI({ apiKey })+const response = await ai.models.generateContent({+ model: 'gemini-2.5-flash',+ contents: 'Hello',+})+```++## Context Window Correction++```typescript+/* ❌ Common misconception */+// "Gemini 2.5 has 2M token context"++/* ✅ Actual limits */+// Gemini 2.5 Pro/Flash: 1,048,576 input tokens (NOT 2M!)+// Gemini 1.5 Pro had 2M - this was reduced in 2.5+// Output limit: 65,536 tokens (all 2.5 models)+```++## Thinking Is Always Enabled (2.5)++```typescript+/* ❌ Trying to disable thinking */+const response = await ai.models.generateContent({+ model: 'gemini-2.5-flash',+ contents: 'Hello',+ thinkingConfig: { enabled: false }, // Not possible!+})++/* ✅ Thinking is always on for 2.5 models */+// Can only adjust budget/level, not disable+const response = await ai.models.generateContent({+ model: 'gemini-2.5-flash',+ contents: 'Hello',+ thinkingConfig: { thinkingBudget: 1024 }, // Adjust, not disable+})+```++## Context Caching Requires Explicit Version++```typescript+/* ❌ Will fail for caching */+const cache = await ai.caches.create({+ model: 'gemini-2.5-flash', // Generic name+ contents: [...],+})++/* ✅ Use explicit version for caching */+const cache = await ai.caches.create({+ model: 'gemini-2.5-flash-001', // Explicit version required+ contents: [...],+})+```++## Current Model Names (2025)++```typescript+/* ❌ Old/incorrect names */+'gemini-pro' // Old+'gemini-1.5-pro' // Use 2.5 instead++/* ✅ Current models */+'gemini-3-pro-preview' // Latest (Nov 2025 preview)+'gemini-2.5-pro' // Stable+'gemini-2.5-flash' // Fast+'gemini-2.5-flash-lite' // Lightweight+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `@google/generative-ai` | `@google/genai` |+| `GoogleGenerativeAI` class | `GoogleGenAI` class |+| 2M context window | 1,048,576 tokens (Gemini 2.5) |+| Disabling thinking | Adjust `thinkingBudget` instead |+| `gemini-pro` | `gemini-2.5-pro` or `gemini-2.5-flash` |+| Generic model for caching | Explicit version (e.g., `gemini-2.5-flash-001`) |diff --git a/skills/google-gemini-embeddings/rules/google-gemini-embeddings.md b/skills/google-gemini-embeddings/rules/google-gemini-embeddings.mdnew file mode 100644index 00000000..56917cd8--- /dev/null+++ b/skills/google-gemini-embeddings/rules/google-gemini-embeddings.md@@ -0,0 +1,86 @@+---+paths: "**/*embed*.ts", "**/*vector*.ts", "**/*.ts"+---++# Google Gemini Embeddings Corrections++Claude's training may miss task type requirements.++## Task Type REQUIRED for Quality++```typescript+/* ❌ Missing task type (10-30% quality loss) */+const result = await ai.models.embedContent({+ model: 'gemini-embedding-001',+ content: 'Hello world',+})++/* ✅ Always specify task type */+const result = await ai.models.embedContent({+ model: 'gemini-embedding-001',+ content: 'Hello world',+ taskType: 'RETRIEVAL_DOCUMENT', // Required!+})+```++## RAG: Different Task Types for Query vs Document++```typescript+/* ❌ Same task type for both (breaks retrieval) */+// Indexing documents+embed(doc, { taskType: 'RETRIEVAL_QUERY' }) // Wrong!++// Querying+embed(query, { taskType: 'RETRIEVAL_QUERY' })++/* ✅ Use RETRIEVAL_DOCUMENT for docs, RETRIEVAL_QUERY for queries */+// Indexing documents+embed(doc, { taskType: 'RETRIEVAL_DOCUMENT' })++// Querying+embed(query, { taskType: 'RETRIEVAL_QUERY' })+```++## Available Task Types++```typescript+// Choose based on use case:+'RETRIEVAL_QUERY' // User search queries+'RETRIEVAL_DOCUMENT' // Documents being indexed+'SEMANTIC_SIMILARITY' // Comparing text similarity+'CLUSTERING' // Grouping similar items+'CLASSIFICATION' // Categorizing text+'CODE_RETRIEVAL_QUERY' // Code search queries+'QUESTION_ANSWERING' // Q&A systems+'FACT_VERIFICATION' // Fact checking+```++## Dimension Matching++```typescript+/* ❌ Dimension mismatch with vector store */+// Vectorize index: 768 dimensions+// Embedding: default 3072 dimensions++/* ✅ Match dimensions to your vector store */+const result = await ai.models.embedContent({+ model: 'gemini-embedding-001',+ content: 'Hello',+ taskType: 'RETRIEVAL_DOCUMENT',+ outputDimensionality: 768, // Match your index!+})++// Recommended dimensions:+// 768 - Fast, good for most use cases+// 1536 - Balance of speed and quality+// 3072 - Maximum quality (default)+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Missing `taskType` | Always specify task type |+| Same task type for query & doc | `RETRIEVAL_QUERY` for queries, `RETRIEVAL_DOCUMENT` for docs |+| Default dimensions | Match `outputDimensionality` to your vector index |+| `text-embedding-*` model | `gemini-embedding-001` |diff --git a/skills/hono-routing/rules/hono-routing.md b/skills/hono-routing/rules/hono-routing.mdnew file mode 100644index 00000000..a3efdc5f--- /dev/null+++ b/skills/hono-routing/rules/hono-routing.md@@ -0,0 +1,121 @@+---+paths: "**/*.ts", "**/*.tsx", "**/*route*.ts", "**/*api*.ts"+---++# Hono Routing Corrections++Claude's training may suggest Express patterns. This project uses **Hono v4**.++## Response: c.json(), Not res.send()++```typescript+/* ❌ Express pattern */+app.get('/api/users', (req, res) => {+ res.send({ users })+ res.json({ users })+})++/* ✅ Hono pattern */+app.get('/api/users', (c) => {+ return c.json({ users })+ // Also: c.text(), c.html(), c.body()+})+```++## Middleware: MUST await next()++```typescript+/* ❌ Breaks middleware chain */+app.use(async (c, next) => {+ console.log('Before')+ next() // Missing await!+ console.log('After')+})++/* ✅ Always await next() */+app.use(async (c, next) => {+ console.log('Before')+ await next() // Required!+ console.log('After')+})+```++## Params: c.req.param(), Not req.params++```typescript+/* ❌ Express pattern */+app.get('/users/:id', (req) => {+ const id = req.params.id+})++/* ✅ Hono pattern */+app.get('/users/:id', (c) => {+ const id = c.req.param('id')+ // Or get all: c.req.param()+})+```++## Validation: Use Validator Middleware++```typescript+/* ❌ Raw request access */+app.post('/users', async (c) => {+ const body = await c.req.json() // No validation!+})++/* ✅ Use validator middleware */+import { zValidator } from '@hono/zod-validator'+import { z } from 'zod'++const schema = z.object({ name: z.string(), email: z.string().email() })++app.post('/users', zValidator('json', schema), (c) => {+ const body = c.req.valid('json') // Type-safe and validated!+})+```++## Error Handling: HTTPException++```typescript+/* ❌ Plain Error doesn't set status */+throw new Error('Not found')++/* ✅ Use HTTPException */+import { HTTPException } from 'hono/http-exception'+throw new HTTPException(404, { message: 'User not found' })+```++## RPC: Export Route, Not App++```typescript+/* ❌ Exporting entire app causes IDE slowdown */+export type AppType = typeof app++/* ✅ Export specific route groups */+const userRoutes = app.get('/users', handler).post('/users', handler)+export type UserRoutes = typeof userRoutes+```++## Type Variables for c.set/c.get++```typescript+/* ❌ No type safety */+c.set('user', user)+const user = c.get('user') // any++/* ✅ Define Variables type */+type Variables = { user: User }+const app = new Hono<{ Variables: Variables }>()+c.set('user', user) // Type-checked+const user = c.get('user') // User type+```++## Quick Fixes++| Express pattern | Hono equivalent |+|----------------|-----------------|+| `res.send()` / `res.json()` | `c.json()` / `c.text()` |+| `req.params.id` | `c.req.param('id')` |+| `req.body` | `c.req.valid('json')` with validator |+| `next()` | `await next()` |+| `throw new Error()` | `throw new HTTPException(status)` |diff --git a/skills/openai-agents/rules/openai-agents.md b/skills/openai-agents/rules/openai-agents.mdnew file mode 100644index 00000000..cfbdc640--- /dev/null+++ b/skills/openai-agents/rules/openai-agents.md@@ -0,0 +1,80 @@+---+paths: "**/*agent*.ts", "**/*agent*.tsx", "**/*.ts"+---++# OpenAI Agents SDK Corrections++Claude's training may reference older patterns. This project uses **@openai/agents v0.2.1**.++## Zod Schema Must Be Inline++```typescript+/* ❌ Imported schema causes type errors (GitHub #188) */+import { mySchema } from './schemas'+const tool = { parameters: mySchema }++/* ✅ Define inline */+const tool = {+ parameters: z.object({+ location: z.string().describe('City name'),+ }),+}+```++## MCP Tracing Required++```typescript+/* ❌ "No existing trace found" error */+const result = await agent.run()++/* ✅ Initialize tracing first */+import { initializeTracing } from '@openai/agents'+initializeTracing()+const result = await agent.run()+```++## Prevent Infinite Loops (MaxTurnsExceeded)++```typescript+/* ❌ Default maxTurns often too low */+const agent = new Agent({ tools })++/* ✅ Increase maxTurns and improve instructions */+const agent = new Agent({+ tools,+ maxTurns: 20, // Increase from default+ instructions: 'Complete the task, then return final_answer tool',+})+```++## Voice Agent Handoffs++```typescript+/* ❌ Cannot change voice/model during handoff */+handoff({ voice: 'different-voice', model: 'gpt-4o' })++/* ✅ Voice and model must match original agent */+handoff({ voice: originalVoice, model: 'gpt-4o-realtime-preview' })+```++## Never Send API Key to Browser++```typescript+/* ❌ Security vulnerability */+const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })+// Sending to frontend...++/* ✅ Generate ephemeral tokens server-side */+const session = await client.realtime.sessions.create({ model: 'gpt-4o-realtime-preview' })+// Send session.client_secret.value to frontend (expires in 60s)+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| Imported Zod schemas | Define schemas inline |+| Missing tracing | Call `initializeTracing()` |+| Agent loops forever | Increase `maxTurns`, improve instructions |+| Changing voice in handoff | Keep voice/model consistent |+| API key in browser | Use ephemeral session tokens |diff --git a/skills/openai-api/rules/openai-api.md b/skills/openai-api/rules/openai-api.mdnew file mode 100644index 00000000..effa1a9c--- /dev/null+++ b/skills/openai-api/rules/openai-api.md@@ -0,0 +1,103 @@+---+paths: "**/*.ts", "**/*.tsx", "**/*openai*.ts"+---++# OpenAI API Corrections++Claude's training may reference older patterns. This project uses **[email protected]**.++## GPT-5.1 Reasoning Defaults Changed++```typescript+/* ❌ GPT-5.1 defaults to reasoning_effort: 'none' (different from GPT-5!) */+const response = await openai.chat.completions.create({+ model: 'gpt-5.1',+ messages: [...],+})++/* ✅ Explicitly set reasoning_effort */+const response = await openai.chat.completions.create({+ model: 'gpt-5.1',+ messages: [...],+ reasoning_effort: 'medium', // Required for reasoning+})+```++## Temperature Not Supported on GPT-5++```typescript+/* ❌ Will fail on GPT-5/GPT-5.1 */+const response = await openai.chat.completions.create({+ model: 'gpt-5',+ temperature: 0.7, // Not supported!+})++/* ✅ Use reasoning_effort instead, or fall back to GPT-4o */+const response = await openai.chat.completions.create({+ model: 'gpt-5',+ reasoning_effort: 'medium',+})++// For temperature control, use GPT-4o:+const response = await openai.chat.completions.create({+ model: 'gpt-4o',+ temperature: 0.7,+})+```++## Current Model Names (2025)++```typescript+/* ❌ Deprecated models */+'gpt-3.5-turbo' // Deprecated+'gpt-4' // Deprecated++/* ✅ Current models */+'gpt-5.1' // Latest (Nov 2025)+'gpt-5' // Previous flagship+'gpt-5-mini' // Cost-efficient+'gpt-5-nano' // Lightweight+'gpt-4o' // Still supported, has temperature+```++## Streaming SSE Parsing++```typescript+/* ❌ Missing error handling */+for await (const chunk of stream) {+ console.log(chunk.choices[0].delta.content)+}++/* ✅ Handle [DONE] signal and errors */+for await (const chunk of stream) {+ if (chunk.choices[0]?.finish_reason === 'stop') break+ const content = chunk.choices[0]?.delta?.content+ if (content) process.stdout.write(content)+}+```++## DALL-E 3 Single Image Only++```typescript+/* ❌ n > 1 not supported */+const response = await openai.images.generate({+ model: 'dall-e-3',+ n: 4, // Error!+})++/* ✅ DALL-E 3 only supports n: 1 */+const response = await openai.images.generate({+ model: 'dall-e-3',+ n: 1,+})+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `temperature` on GPT-5 | `reasoning_effort` |+| `gpt-3.5-turbo` or `gpt-4` | `gpt-5.1`, `gpt-5`, or `gpt-4o` |+| `n: 4` with DALL-E 3 | `n: 1` (only supported value) |+| Missing stream error handling | Check `finish_reason` and `[DONE]` |+| Image URLs for storage | Use `response_format: 'b64_json'` (URLs expire 1hr) |diff --git a/skills/openai-assistants/rules/openai-assistants.md b/skills/openai-assistants/rules/openai-assistants.mdnew file mode 100644index 00000000..f94bb099--- /dev/null+++ b/skills/openai-assistants/rules/openai-assistants.md@@ -0,0 +1,72 @@+---+paths: "**/*assistant*.ts", "**/*.ts"+---++# OpenAI Assistants API - DEPRECATED++**⚠️ SUNSET H1 2026** - Use `openai-responses` skill for new projects.++## Migration Required++```typescript+/* ❌ Assistants API (deprecated) */+const assistant = await openai.beta.assistants.create({...})+const thread = await openai.beta.threads.create()+const run = await openai.beta.threads.runs.create(thread.id, {...})++/* ✅ Use Responses API instead */+const response = await openai.responses.create({+ model: 'gpt-5',+ input: 'Hello',+ conversation_id: existingConversationId, // Optional: for stateful+})+```++## If Maintaining Existing Code++### Thread Already Has Active Run++```typescript+/* ❌ Will fail if run already active */+await openai.beta.threads.runs.create(threadId, { assistant_id })++/* ✅ Cancel existing run first */+const runs = await openai.beta.threads.runs.list(threadId)+const activeRun = runs.data.find(r => r.status === 'in_progress')+if (activeRun) {+ await openai.beta.threads.runs.cancel(threadId, activeRun.id)+}+await openai.beta.threads.runs.create(threadId, { assistant_id })+```++### Vector Store Must Be Ready++```typescript+/* ❌ Using vector store before ready */+const vectorStore = await openai.beta.vectorStores.create({...})+// Immediately using...++/* ✅ Poll until completed */+let vs = await openai.beta.vectorStores.create({...})+while (vs.status !== 'completed') {+ await new Promise(r => setTimeout(r, 1000))+ vs = await openai.beta.vectorStores.retrieve(vs.id)+}+```++## v1 → v2 Changes++| v1 | v2 |+|----|-----|+| Max 20 files for file search | Max 10,000 files |+| 32k char instructions | 256k char instructions |+| retrieval tool | file_search tool |++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| New Assistants project | Responses API (`openai-responses` skill) |+| `retrieval` tool | `file_search` tool (v2) |+| No run cancellation | Cancel active runs before creating new |+| Immediate vector store use | Poll until `status: 'completed'` |diff --git a/skills/openai-responses/rules/openai-responses.md b/skills/openai-responses/rules/openai-responses.mdnew file mode 100644index 00000000..25cf2306--- /dev/null+++ b/skills/openai-responses/rules/openai-responses.md@@ -0,0 +1,104 @@+---+paths: "**/*.ts", "**/*.tsx", "**/*openai*.ts"+---++# OpenAI Responses API Corrections++Claude's training may reference Chat Completions. This project uses **Responses API**.++## Key Differences from Chat Completions++```typescript+/* ❌ Chat Completions pattern */+const response = await openai.chat.completions.create({+ model: 'gpt-5',+ messages: [{ role: 'system', content: '...' }, { role: 'user', content: '...' }],+})+const text = response.choices[0].message.content++/* ✅ Responses API pattern */+const response = await openai.responses.create({+ model: 'gpt-5',+ input: 'Hello',+ instructions: '...', // replaces system message+})+const text = response.output_text // helper property+```++## System Role → Developer Role++```typescript+/* ❌ Chat Completions system role */+messages: [{ role: 'system', content: 'You are helpful' }]++/* ✅ Responses API uses 'developer' or instructions */+instructions: 'You are helpful'+// OR in input array:+input: [{ role: 'developer', content: 'You are helpful' }]+```++## Stateful Conversations++```typescript+/* ❌ Managing history manually */+const messages = [...history, newMessage]++/* ✅ Use conversation_id for automatic state */+// First message+const response = await openai.responses.create({+ model: 'gpt-5',+ input: 'Hello',+})+const conversationId = response.conversation_id++// Subsequent messages - history managed automatically+const response2 = await openai.responses.create({+ model: 'gpt-5',+ input: 'Follow up question',+ conversation_id: conversationId, // Preserves context+})+```++## Conversation Expiration++```typescript+/* ⚠️ Conversations expire after 90 days */+// Verify conversation exists before using+try {+ const response = await openai.responses.create({+ model: 'gpt-5',+ input: 'Hello',+ conversation_id: oldConversationId,+ })+} catch (error) {+ // Conversation expired - start new one+ const response = await openai.responses.create({+ model: 'gpt-5',+ input: 'Hello',+ })+}+```++## Cost Tracking++```typescript+/* ⚠️ Responses API has additional costs */+// Cost = input + output + tools + stored conversations++/* Disable storage if not needed */+const response = await openai.responses.create({+ model: 'gpt-5',+ input: 'Hello',+ store: false, // Don't persist conversation+})+```++## Quick Fixes++| Chat Completions | Responses API |+|-----------------|---------------|+| `/v1/chat/completions` | `/v1/responses` |+| `messages` | `input` |+| `role: 'system'` | `role: 'developer'` or `instructions` |+| `choices[0].message.content` | `output_text` |+| Manual history | `conversation_id` |diff --git a/skills/react-hook-form-zod/rules/react-hook-form-zod.md b/skills/react-hook-form-zod/rules/react-hook-form-zod.mdnew file mode 100644index 00000000..886f291d--- /dev/null+++ b/skills/react-hook-form-zod/rules/react-hook-form-zod.md@@ -0,0 +1,138 @@+---+paths: "**/*.tsx", "**/*form*.ts", "**/*.ts"+---++# React Hook Form + Zod Corrections++## ALWAYS Set defaultValues++```typescript+/* ❌ Causes uncontrolled→controlled warning */+const { register } = useForm<FormData>({+ resolver: zodResolver(schema),+ // No defaultValues!+})++/* ✅ Always provide defaultValues */+const { register } = useForm<FormData>({+ resolver: zodResolver(schema),+ defaultValues: {+ name: '',+ email: '',+ age: undefined, // or appropriate default+ },+})+```++## useFieldArray: Use field.id as Key++```typescript+/* ❌ Using index causes infinite re-renders */+{fields.map((field, index) => (+ <input key={index} {...register(`items.${index}.name`)} />+))}++/* ✅ Use field.id */+{fields.map((field, index) => (+ <input key={field.id} {...register(`items.${index}.name`)} />+))}+```++## Controller: MUST Spread {...field}++```typescript+/* ❌ Field doesn't update */+<Controller+ name="status"+ control={control}+ render={({ field }) => (+ <Select value={field.value} onChange={field.onChange} />+ )}+/>++/* ✅ Spread all field props */+<Controller+ name="status"+ control={control}+ render={({ field }) => (+ <Select {...field} />+ )}+/>+```++## Nested Error Access++```typescript+/* ❌ May crash on undefined */+errors.address.street.message++/* ✅ Use optional chaining */+errors.address?.street?.message+```++## Server Validation Required++```typescript+/* ❌ Security vulnerability - client only */+const onSubmit = (data) => {+ await api.post('/users', data) // No server validation!+}++/* ✅ Validate on BOTH client and server */+// Client: useForm with zodResolver+// Server:+app.post('/users', async (c) => {+ const result = schema.safeParse(await c.req.json())+ if (!result.success) {+ return c.json({ errors: result.error.flatten() }, 400)+ }+})+```++## Show Server Errors with setError++```typescript+/* ✅ Display server validation errors */+const onSubmit = async (data) => {+ const response = await api.post('/users', data)+ if (!response.ok) {+ const { errors } = await response.json()+ // Set field-specific errors+ Object.entries(errors).forEach(([field, message]) => {+ setError(field, { message })+ })+ }+}+```++## Zod Refinement: Include path++```typescript+/* ❌ Error shows on form, not field */+const schema = z.object({+ password: z.string(),+ confirm: z.string(),+}).refine(d => d.password === d.confirm, {+ message: "Passwords don't match",+})++/* ✅ Include path for field placement */+const schema = z.object({+ password: z.string(),+ confirm: z.string(),+}).refine(d => d.password === d.confirm, {+ message: "Passwords don't match",+ path: ['confirm'], // Error shows on confirm field+})+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| No `defaultValues` | Always provide `defaultValues: { field: '' }` |+| `key={index}` in useFieldArray | `key={field.id}` |+| Partial field props | Spread `{...field}` |+| `errors.a.b.message` | `errors.a?.b?.message` |+| Client-only validation | Validate on server too |+| Missing refinement path | Add `path: ['fieldName']` |diff --git a/skills/zustand-state-management/rules/zustand-state-management.md b/skills/zustand-state-management/rules/zustand-state-management.mdnew file mode 100644index 00000000..c90fface--- /dev/null+++ b/skills/zustand-state-management/rules/zustand-state-management.md@@ -0,0 +1,130 @@+---+paths: "**/*.ts", "**/*.tsx", "**/*store*.ts", "**/*state*.ts"+---++# Zustand v5 Corrections++Claude's training may reference v4 patterns. This project uses **Zustand v5**.++## TypeScript: Double Parentheses Required++```typescript+/* ❌ v4 syntax (breaks middleware types) */+const useStore = create<MyState>((set) => ({+ count: 0,+ increment: () => set((s) => ({ count: s.count + 1 })),+}))++/* ✅ v5 syntax: create<T>()(...) */+const useStore = create<MyState>()((set) => ({+ count: 0,+ increment: () => set((s) => ({ count: s.count + 1 })),+}))+```++## Persist: Import from Middleware++```typescript+/* ❌ Wrong import */+import { persist, createJSONStorage } from 'zustand'++/* ✅ Import from middleware */+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'++const useStore = create<MyState>()(+ persist(+ (set) => ({ /* ... */ }),+ {+ name: 'my-store',+ storage: createJSONStorage(() => localStorage),+ }+ )+)+```++## Selectors: Don't Create Objects++```typescript+/* ❌ Creates new object every render (infinite re-renders) */+const { count, increment } = useStore((s) => ({+ count: s.count,+ increment: s.increment,+}))++/* ✅ Option 1: Select separately */+const count = useStore((s) => s.count)+const increment = useStore((s) => s.increment)++/* ✅ Option 2: Use shallow comparator */+import { useShallow } from 'zustand/shallow'+const { count, increment } = useStore(+ useShallow((s) => ({ count: s.count, increment: s.increment }))+)+```++## Next.js Hydration Mismatch++```typescript+/* ❌ "Text content does not match" error */+// Persist reads localStorage on client, not server++/* ✅ Add hydration check */+interface MyState {+ count: number+ _hasHydrated: boolean+ setHasHydrated: (state: boolean) => void+}++const useStore = create<MyState>()(+ persist(+ (set) => ({+ count: 0,+ _hasHydrated: false,+ setHasHydrated: (state) => set({ _hasHydrated: state }),+ }),+ {+ name: 'my-store',+ onRehydrateStorage: () => (state) => {+ state?.setHasHydrated(true)+ },+ }+ )+)++// In component:+const hasHydrated = useStore((s) => s._hasHydrated)+if (!hasHydrated) return <Loading />+```++## Slices Pattern: Explicit Types++```typescript+/* ✅ Complex but necessary for middleware */+import { StateCreator } from 'zustand'++interface BearSlice {+ bears: number+ addBear: () => void+}++const createBearSlice: StateCreator<+ BearSlice & FishSlice, // Combined state+ [],+ [],+ BearSlice // This slice+> = (set) => ({+ bears: 0,+ addBear: () => set((s) => ({ bears: s.bears + 1 })),+})+```++## Quick Fixes++| If Claude suggests... | Use instead... |+|----------------------|----------------|+| `create<T>((set) => ...)` | `create<T>()((set) => ...)` |+| Import persist from 'zustand' | Import from 'zustand/middleware' |+| Object in selector | Select separately or use `useShallow` |+| Next.js hydration error | Add `_hasHydrated` pattern |+| Simple slices types | Use explicit `StateCreator` types |