AgentSkillsCN

windsurf-known-pitfalls

识别并规避 Windsurf 反模式与常见集成误区。 在审查 Windsurf 代码是否存在问题、为新开发者提供入职培训,或审计现有 Windsurf 集成是否违反最佳实践时使用。 可使用诸如“Windsurf 错误”、“Windsurf 反模式”、“Windsurf 陷阱”、“Windsurf 不该做的事”、“Windsurf 代码审查”等短语来触发相关操作。

SKILL.md
--- frontmatter
name: windsurf-known-pitfalls
description: |
  Identify and avoid Windsurf anti-patterns and common integration mistakes.
  Use when reviewing Windsurf code for issues, onboarding new developers,
  or auditing existing Windsurf integrations for best practices violations.
  Trigger with phrases like "windsurf mistakes", "windsurf anti-patterns",
  "windsurf pitfalls", "windsurf what not to do", "windsurf code review".
allowed-tools: Read, Grep
version: 1.0.0
license: MIT
author: Jeremy Longshore <jeremy@intentsolutions.io>

Windsurf Known Pitfalls

Overview

Common mistakes and anti-patterns when integrating with Windsurf.

Prerequisites

  • Access to Windsurf codebase for review
  • Understanding of async/await patterns
  • Knowledge of security best practices
  • Familiarity with rate limiting concepts

Pitfall #1: Synchronous API Calls in Request Path

❌ Anti-Pattern

typescript
// User waits for Windsurf API call
app.post('/checkout', async (req, res) => {
  const payment = await windsurfClient.processPayment(req.body);  // 2-5s latency
  const notification = await windsurfClient.sendEmail(payment);   // Another 1-2s
  res.json({ success: true });  // User waited 3-7s
});

✅ Better Approach

typescript
// Return immediately, process async
app.post('/checkout', async (req, res) => {
  const jobId = await queue.enqueue('process-checkout', req.body);
  res.json({ jobId, status: 'processing' });  // 50ms response
});

// Background job
async function processCheckout(data) {
  const payment = await windsurfClient.processPayment(data);
  await windsurfClient.sendEmail(payment);
}

Pitfall #2: Not Handling Rate Limits

❌ Anti-Pattern

typescript
// Blast requests, crash on 429
for (const item of items) {
  await windsurfClient.process(item);  // Will hit rate limit
}

✅ Better Approach

typescript
import pLimit from 'p-limit';

const limit = pLimit(5);  // Max 5 concurrent
const rateLimiter = new RateLimiter({ tokensPerSecond: 10 });

for (const item of items) {
  await rateLimiter.acquire();
  await limit(() => windsurfClient.process(item));
}

Pitfall #3: Leaking API Keys

❌ Anti-Pattern

typescript
// In frontend code (visible to users!)
const client = new WindsurfClient({
  apiKey: 'sk_live_ACTUAL_KEY_HERE',  // Anyone can see this
});

// In git history
git commit -m "add API key"  // Exposed forever

✅ Better Approach

typescript
// Backend only, environment variable
const client = new WindsurfClient({
  apiKey: process.env.WINDSURF_API_KEY,
});

// Use .gitignore
.env
.env.local
.env.*.local

Pitfall #4: Ignoring Idempotency

❌ Anti-Pattern

typescript
// Network error on response = duplicate charge!
try {
  await windsurfClient.charge(order);
} catch (error) {
  if (error.code === 'NETWORK_ERROR') {
    await windsurfClient.charge(order);  // Charged twice!
  }
}

✅ Better Approach

typescript
const idempotencyKey = `order-${order.id}-${Date.now()}`;

await windsurfClient.charge(order, {
  idempotencyKey,  // Safe to retry
});

Pitfall #5: Not Validating Webhooks

❌ Anti-Pattern

typescript
// Trust any incoming request
app.post('/webhook', (req, res) => {
  processWebhook(req.body);  // Attacker can send fake events
  res.sendStatus(200);
});

✅ Better Approach

typescript
app.post('/webhook',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const signature = req.headers['x-windsurf-signature'];
    if (!verifyWindsurfSignature(req.body, signature)) {
      return res.sendStatus(401);
    }
    processWebhook(JSON.parse(req.body));
    res.sendStatus(200);
  }
);

Pitfall #6: Missing Error Handling

❌ Anti-Pattern

typescript
// Crashes on any error
const result = await windsurfClient.get(id);
console.log(result.data.nested.value);  // TypeError if missing

✅ Better Approach

typescript
try {
  const result = await windsurfClient.get(id);
  console.log(result?.data?.nested?.value ?? 'default');
} catch (error) {
  if (error instanceof WindsurfNotFoundError) {
    return null;
  }
  if (error instanceof WindsurfRateLimitError) {
    await sleep(error.retryAfter);
    return this.get(id);  // Retry
  }
  throw error;  // Rethrow unknown errors
}

Pitfall #7: Hardcoding Configuration

❌ Anti-Pattern

typescript
const client = new WindsurfClient({
  timeout: 5000,  // Too short for some operations
  baseUrl: 'https://api.windsurf.com',  // Can't change for staging
});

✅ Better Approach

typescript
const client = new WindsurfClient({
  timeout: parseInt(process.env.WINDSURF_TIMEOUT || '30000'),
  baseUrl: process.env.WINDSURF_BASE_URL || 'https://api.windsurf.com',
});

Pitfall #8: Not Implementing Circuit Breaker

❌ Anti-Pattern

typescript
// When Windsurf is down, every request hangs
for (const user of users) {
  await windsurfClient.sync(user);  // All timeout sequentially
}

✅ Better Approach

typescript
import CircuitBreaker from 'opossum';

const breaker = new CircuitBreaker(windsurfClient.sync, {
  timeout: 10000,
  errorThresholdPercentage: 50,
  resetTimeout: 30000,
});

// Fails fast when circuit is open
for (const user of users) {
  await breaker.fire(user).catch(handleFailure);
}

Pitfall #9: Logging Sensitive Data

❌ Anti-Pattern

typescript
console.log('Request:', JSON.stringify(request));  // Logs API key, PII
console.log('User:', user);  // Logs email, phone

✅ Better Approach

typescript
const redacted = {
  ...request,
  apiKey: '[REDACTED]',
  user: { id: user.id },  // Only non-sensitive fields
};
console.log('Request:', JSON.stringify(redacted));

Pitfall #10: No Graceful Degradation

❌ Anti-Pattern

typescript
// Entire feature broken if Windsurf is down
const recommendations = await windsurfClient.getRecommendations(userId);
return renderPage({ recommendations });  // Page crashes

✅ Better Approach

typescript
let recommendations;
try {
  recommendations = await windsurfClient.getRecommendations(userId);
} catch (error) {
  recommendations = await getFallbackRecommendations(userId);
  reportDegradedService('windsurf', error);
}
return renderPage({ recommendations, degraded: !recommendations });

Instructions

Step 1: Review for Anti-Patterns

Scan codebase for each pitfall pattern.

Step 2: Prioritize Fixes

Address security issues first, then performance.

Step 3: Implement Better Approach

Replace anti-patterns with recommended patterns.

Step 4: Add Prevention

Set up linting and CI checks to prevent recurrence.

Output

  • Anti-patterns identified
  • Fixes prioritized and implemented
  • Prevention measures in place
  • Code quality improved

Error Handling

IssueCauseSolution
Too many findingsLegacy codebasePrioritize security first
Pattern not detectedComplex codeManual review
False positiveSimilar codeWhitelist exceptions
Fix breaks testsBehavior changeUpdate tests

Examples

Quick Pitfall Scan

bash
# Check for common pitfalls
grep -r "sk_live_" --include="*.ts" src/        # Key leakage
grep -r "console.log" --include="*.ts" src/     # Potential PII logging

Resources

Quick Reference Card

PitfallDetectionPrevention
Sync in requestHigh latencyUse queues
Rate limit ignore429 errorsImplement backoff
Key leakageGit history scanEnv vars, .gitignore
No idempotencyDuplicate recordsIdempotency keys
Unverified webhooksSecurity auditSignature verification
Missing error handlingCrashesTry-catch, types
Hardcoded configCode reviewEnvironment variables
No circuit breakerCascading failuresopossum, resilience4j
Logging PIILog auditRedaction middleware
No degradationTotal outagesFallback systems