mcpField
F
fullstack-debugger

fullstack-debugger

github.com/curiositech开发257233 次安装2 天前更新
代码仓库

关于 fullstack-debugger

fullstack-debugger 是面向使用 Next.js 15、Cloudflare Workers、Supabase 和边缘部署的开发者的调试技能。它按证据逐层定位故障,并指导验证修复结果。

主要功能

  1. 01按复现到验证的流程排查
  2. 02诊断浏览器、服务端和数据库
  3. 03提供构建与类型检查命令
  4. 04排查 RLS、CORS、认证和缓存
  5. 05报告根因并验证修复

适用场景

  1. 01调查 Next.js 构建失败
  2. 02诊断 Supabase RLS 或认证问题
  3. 03检查 Cloudflare Worker 健康状态与 CORS
  4. 04追踪水合、缓存或部署故障

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/curiositech/some_claude_skills --skill fullstack-debugger

安装后在 Claude Code 中输入/fullstack-debugger确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

.claude-plugin/
plugin.json
references/
debug-decision-tree.md
error-patterns.md
scripts/
check-cors.sh
check-rls.js
diagnose.sh
inspect-cache.sh

详细介绍

全栈调试器

适用于现代 Web 技术栈的专家级调试器:Next.js 15、Cloudflare Workers、Supabase 和边缘部署。采用系统化、以证据为依据的故障排查方式。

激活触发条件

在以下情况下激活:“debug”、“not working”、“broken”、“error”、“500 error”、“401”、“403”、“cache issue”、“CORS error”、“RLS policy”、“auth not working”、“blank page”、“hydration error”、“build failed”、“worker not responding”

**不适用于:**功能开发 → 语言技能 | 架构设计 → system-architect | 性能优化 → performance-engineer

调试理念

1. REPRODUCE → Can you make it fail consistently?
2. ISOLATE   → Which layer is broken?
3. EVIDENCE  → What do logs/network/state show?
4. HYPOTHESIZE → What could cause this?
5. TEST      → Validate one hypothesis at a time
6. FIX       → Minimal change that resolves issue
7. VERIFY    → Confirm fix doesn't break other things

架构层

┌─────────────────────────────────────────────────────────────┐
│                    DEBUGGING LAYERS                         │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Layer 1: Browser/Client                                    │
│  ├── Console errors, network tab, React DevTools           │
│  ├── localStorage/sessionStorage state                     │
│  └── React Query cache state                               │
│                                                             │
│  Layer 2: Next.js Application                              │
│  ├── Server components vs client components                │
│  ├── Build output and static generation                    │
│  ├── API routes (if any)                                   │
│  └── Hydration mismatches                                  │
│                                                             │
│  Layer 3: Cloudflare Workers                               │
│  ├── Worker logs (wrangler tail)                           │
│  ├── KV cache state                                        │
│  ├── CORS headers                                          │
│  └── Rate limiting                                         │
│                                                             │
│  Layer 4: Supabase                                         │
│  ├── Auth state and JWT tokens                             │
│  ├── RLS policies (most common issue!)                     │
│  ├── Database queries and indexes                          │
│  └── Realtime subscriptions                                │
│                                                             │
│  Layer 5: External APIs                                    │
│  ├── Third-party service availability                      │
│  ├── API rate limits                                       │
│  └── Response format changes                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

快速诊断命令

一次检查所有内容
# Run from next-app/ directory
echo "=== Build Check ===" && npm run build 2>&1 | tail -20
echo "=== TypeScript ===" && npx tsc --noEmit 2>&1 | head -20
echo "=== Lint ===" && npm run lint 2>&1 | head -20
echo "=== Git Status ===" && git status --short
Supabase RLS 诊断
# Check if RLS is blocking queries (most common issue!)
node -e "
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(
  'YOUR_SUPABASE_URL',
  'YOUR_ANON_KEY'
);

async function diagnose() {
  // Test as anonymous user
  const { data, error, count } = await supabase
    .from('YOUR_TABLE')
    .select('*', { count: 'exact' })
    .limit(5);

  console.log('Error:', error);
  console.log('Count:', count);
  console.log('Sample:', data);
}
diagnose();
"
Worker 健康检查
# Check if workers are responding
curl -s -o /dev/null -w "%{http_code}" https://YOUR-WORKER.workers.dev/health

# Check CORS headers
curl -s -D - -o /dev/null -H "Origin: https://yoursite.com" \
  https://YOUR-WORKER.workers.dev/api/endpoint | grep -iE "(access-control|x-)"

# Stream worker logs
cd workers/your-worker && npx wrangler tail
缓存检查
# Check Cloudflare KV cache
npx wrangler kv:key list --namespace-id=YOUR_NAMESPACE_ID | head -20

# Get specific cached value
npx wrangler kv:key get --namespace-id=YOUR_NAMESPACE_ID "cache:key"

# Clear a cached item
npx wrangler kv:key delete --namespace-id=YOUR_NAMESPACE_ID "cache:key"

常见问题及解决方案

1. RLS 策略阻止数据访问(最常见!)

症状:

  • 查询返回空数组,但没有错误
  • 在 Supabase 控制台中正常,但在应用中不行
  • 某些用户可以使用,其他用户不行

诊断:

-- In Supabase SQL Editor
-- Check what policies exist
SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual
FROM pg_policies
WHERE tablename = 'your_table';

-- Test as anonymous user
SET ROLE anon;
SELECT * FROM your_table LIMIT 5;
RESET ROLE;

-- Test as authenticated user
SET ROLE authenticated;
SET request.jwt.claims = '{"sub": "user-uuid-here"}';
SELECT * FROM your_table LIMIT 5;
RESET ROLE;

常见修复方法:

-- Allow public read access
CREATE POLICY "Allow public read" ON your_table
  FOR SELECT USING (true);

-- Allow authenticated users to read
CREATE POLICY "Allow authenticated read" ON your_table
  FOR SELECT TO authenticated USING (true);

-- Allow users to read their own data
CREATE POLICY "Users read own data" ON your_table
  FOR SELECT USING (auth.uid() = user_id);
2. CORS 错误

症状:

  • “Access to fetch blocked by CORS policy”
  • 在 Postman 中正常,但在浏览器中不行
  • 预检请求失败

诊断:

# Check what CORS headers are returned
curl -s -D - -o /dev/null \
  -H "Origin: https://yoursite.com" \
  -H "Access-Control-Request-Method: POST" \
  -X OPTIONS \
  https://your-worker.workers.dev/api/endpoint

在 Cloudflare Worker 中修复:

// In your worker
const corsHeaders = {
  'Access-Control-Allow-Origin': '*', // Or specific domain
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};

// Handle preflight
if (request.method === 'OPTIONS') {
  return new Response(null, { headers: corsHeaders });
}

// Add to all responses
return new Response(data, {
  headers: { ...corsHeaders, 'Content-Type': 'application/json' }
});
3. Auth 状态未持久化

症状:

  • 用户已登录,但刷新后显示为已登出
  • 本地 Auth 正常,但在生产环境中不行
  • 会话随机消失

诊断:

// In browser console
console.log('Session:', await supabase.auth.getSession());
console.log('User:', await supabase.auth.getUser());
console.log('LocalStorage:', Object.keys(localStorage).filter(k => k.includes('supabase')));

常见修复方法:

  • 检查 Supabase URL 是否匹配(http 与 https、末尾斜杠)
  • 确认 Supabase Auth 设置中的站点 URL
  • 检查 Cookie 是否被阻止(Safari、无痕模式)
  • 确保 AuthContext 包裹了所有需要 Auth 的组件
4. 水合不匹配

症状:

  • “Hydration failed because the initial UI does not match”
  • 页面加载时内容闪烁
  • 服务端与客户端的内容不同

诊断:

// Temporarily add to suspect component
useEffect(() => {
  console.log('Client render:', document.body.innerHTML.slice(0, 500));
}, []);

常见修复方法:

// Use client-only rendering for dynamic content
'use client';
import { useState, useEffect } from 'react';

function DynamicContent() {
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  if (!mounted) return null; // or skeleton
  return <div>{/* dynamic content */}</div>;
}
5. Worker 未部署

症状:

  • 部署命令成功,但变更未生效
  • 仍在运行旧代码
  • 新旧行为间歇性交替出现

诊断:

# Check deployment status
npx wrangler deployments list

# View current worker code
npx wrangler deployments view

# Check for multiple environments
npx wrangler whoami

修复方法:

# Force redeploy
npx wrangler deploy --force

# Clear Cloudflare cache
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"purge_everything":true}'
6. TypeScript 缓存幽灵问题

症状:

  • 错误引用已删除或已更改的代码
  • 类型与当前代码不匹配
  • 现有文件却出现“Cannot find module”错误

修复方法:

# Nuclear option - clear all caches
rm -rf .next node_modules/.cache tsconfig.tsbuildinfo
npm run build

# Or just TypeScript cache
rm -rf node_modules/.cache/typescript
npx tsc --build --clean
7. 静态导出问题

症状:

  • “Error: Page X couldn't be rendered statically”
  • 动态路由在静态导出时失败
  • 部署后 API 路由无法使用

诊断:

# Check next.config for output mode
grep -A5 "output:" next.config.ts

# Find dynamic components
grep -r "useSearchParams\|usePathname\|cookies()\|headers()" src/

修复方法:

// For components using dynamic APIs
export const dynamic = 'force-dynamic';
// or wrap in Suspense with fallback

// For generateStaticParams
export async function generateStaticParams() {
  return [{ slug: 'page1' }, { slug: 'page2' }];
}
8. 速率限制问题

症状:

  • 多次请求后出现 429 错误
  • 一开始正常,之后停止工作
  • 不同 IP 的行为不同

诊断:

# Check rate limit headers
curl -i https://your-worker.workers.dev/api/endpoint 2>&1 | grep -i ratelimit

# Check KV for rate limit keys
npx wrangler kv:key list --namespace-id=RATE_LIMIT_KV_ID | grep rate

修复方法:

# Clear rate limit for an IP
npx wrangler kv:key delete --namespace-id=RATE_LIMIT_KV_ID "rate:192.168.1.1"

# Adjust limits in wrangler.toml
RATE_LIMIT_REQUESTS = "100"
RATE_LIMIT_WINDOW = "3600"
9. 会议/地点数据问题

症状:

  • 某些区域找不到会议
  • 会议数据过时
  • 缓存显示错误数据

诊断:

# Check cache status for a location
curl -s -D - -o /dev/null \
  -H "Origin: https://yoursite.com" \
  "https://your-proxy.workers.dev/api/all?lat=45.52&lng=-122.68&radius=25" \
  | grep -iE "(x-cache|x-geohash|x-source)"

# Force cache refresh
curl -H "Origin: https://yoursite.com" \
  "https://your-proxy.workers.dev/warm"

# Check Supabase for meeting count
node -e "
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient('URL', 'KEY');
supabase.from('meetings').select('*', { count: 'exact', head: true })
  .then(({count}) => console.log('Total meetings:', count));
"
10. Cloudflare Pages 构建失败

症状:

  • 本地正常,但部署失败
  • 出现“Module not found”错误
  • 内存超限

诊断:

# Check build output locally
NODE_ENV=production npm run build 2>&1 | tee build.log

# Check for conditional imports
grep -r "require(" src/ --include="*.ts" --include="*.tsx"

# Check bundle size
npx next-bundle-analyzer

修复方法:

// next.config.ts - increase memory
module.exports = {
  experimental: {
    memoryBasedWorkersCount: true,
  },
  // Reduce bundle size
  webpack: (config) => {
    config.externals = [...(config.externals || []), 'sharp'];
    return config;
  }
};

调试脚本

scripts/diagnose.sh
#!/bin/bash
# Run all diagnostics

echo "=== Environment ==="
node -v && npm -v

echo "=== Dependencies ==="
npm ls --depth=0 2>&1 | grep -E "(UNMET|missing)"

echo "=== TypeScript ==="
npx tsc --noEmit 2>&1 | head -30

echo "=== Build ==="
npm run build 2>&1 | tail -30

echo "=== Workers ==="
for worker in workers/*/; do
  echo "Worker: $worker"
  (cd "$worker" && npx wrangler whoami 2>/dev/null)
done

echo "=== Supabase ==="
npx supabase status 2>/dev/null || echo "Supabase CLI not configured"
scripts/check-rls.js
// Check RLS policies are working correctly
const { createClient } = require('@supabase/supabase-js');

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
);

async function checkTable(table) {
  console.log(`\n=== Checking ${table} ===`);
  const { data, error, count } = await supabase
    .from(table)
    .select('*', { count: 'exact' })
    .limit(1);

  if (error) {
    console.log(`ERROR: ${error.message}`);
  } else {
    console.log(`OK: ${count} rows accessible`);
  }
}

// Check critical tables
['profiles', 'meetings', 'forum_posts', 'journal_entries'].forEach(checkTable);

验证清单

[ ] Can reproduce the issue consistently
[ ] Identified which layer is failing (client/Next/Worker/Supabase/API)
[ ] Checked browser console for errors
[ ] Checked network tab for failed requests
[ ] Checked worker logs (wrangler tail)
[ ] Verified RLS policies allow access
[ ] Tested with fresh browser/incognito
[ ] Cleared all caches (browser, React Query, KV, TS)
[ ] Checked environment variables match production
[ ] Verified CORS headers are correct
[ ] Tested on production URL (not just localhost)
[ ] Created minimal reproduction case

输出

调试时,请始终提供:

  1. 根本原因——具体出了什么问题
  2. 证据——能够证明问题的日志、错误或查询
  3. 修复方法——解决问题所需的最小代码变更
  4. 验证方式——如何确认问题已修复
  5. 预防措施——如何避免今后再次发生

可用工具

  • Read、Write、Edit——文件操作
  • Bash——运行命令、curl、wrangler
  • Grep、Glob——搜索代码库
  • WebFetch——测试端点
  • mcp__supabase__*——直接执行 Supabase 操作
  • mcp__playwright__*——用于 UI 测试的浏览器自动化

评论

支持 Markdown