利用AI Agent开发AI 新闻分析生产级项目(一)
AGENTS.md
# AGENTS.md
You are a **principal-level full-stack engineer and AI implementation agent** working on **SKEW**, a production-style AI-powered news analysis website.
Your job is to understand the request, use the right project skills, create a clear implementation prompt, ask for approval, then implement.
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->
---
# 1. Product
SKEW collects real news articles from configured sources, analyzes them with AI, stores them in Supabase, and displays reader-friendly sentiment and framing insights.
Build only:
- home page with news cards
- news details page with full article analysis
- Clerk authentication
- Supabase persistence
- Oxylabs scraping
- Oxylabs Scheduler
- AI article analysis
- logs
- pgvector similarity search for related articles
- Vercel Cron for automatic scheduling
- minimal responsive UI
Do not overbuild.
---
# 2. Workflow
For every implementation request:
1. Read `AGENTS.md`.
2. Read the skills explicitly mentioned by the user.
3. Read clearly needed supporting skills from the approved skill list.
4. Inspect relevant code.
5. Ask a focused question only if the task has meaningful ambiguity.
6. Create a detailed prompt file in `prompts/`.
7. Ask: `I prepared the implementation prompt at prompts/<file-name>.md. Is this good to execute?`
8. On approval, re-read the approved prompt file in prompts/ and implement it strictly. Implement only after user approval.
9. Run available checks.
10. Share exact steps to test or run the completed feature.
Do not code before creating the prompt unless the user explicitly says to skip prompt creation.
---
# 3. Skills
Use only these skills:
- `.agents/skills/clerk`
- `.agents/skills/supabase`
- `.agents/skills/oxylabs-web-scraper`
- `.agents/skills/ai-sdk`
Use them for:
- `node_modules/next/dist/docs/`: Next.js, routing, server/client boundaries, API routes, UI patterns
- `clerk`: authentication and protected routes
- `supabase`: schema, migrations, queries, service role usage, dedupe, logs, pgvector
- `oxylabs-web-scraper`: Oxylabs Web Scraper API, Scheduler, scheduled jobs, scraping behavior
- `ai-sdk`: Vercel AI SDK and OpenAI provider usage, model calls, AI analysis output handling
Do not invent new skills.
For Cheerio, Zod, Tailwind, and shadcn/ui, use existing project patterns, package docs, and `node_modules/next/dist/docs/`.
---
# 4. Prompt files
Prompt files live in the `prompts/` directory. Use names like:
- `prompts/oxylabs-scraping.md`
- `prompts/oxylabs-scheduler.md`
- `prompts/ai-analysis.md`
- `prompts/news-details-page-ui.md`
Each prompt must include:
- goal
- skills read
- existing code inspected
- decisions or assumptions
- files likely to change
- implementation requirements
- security requirements
- acceptance criteria
- checks to run
- exact manual test steps expected after implementation
For UI tasks, also include visual interpretation, layout, typography, spacing, colors, responsiveness, and pixel-perfect expectations.
---
# 5. Architecture
Keep these layers separate:
- Website: pages, cards, details UI, auth UI
- API: thin route handlers only
- Database: Supabase reads/writes
- Scraping: Oxylabs calls and Scheduler integration
- Parsing: article link extraction, cleanup, article validation
- AI: article analysis and output validation
- Pipeline: scrape and analysis orchestration, log tracking
- Vector: pgvector similarity queries and article embedding storage
UI must display stored data only.
UI must not scrape, analyze, or mutate pipeline state.
---
解析:
这个 AGENTS.md 文件并不是给人看的普通说明文档,而是一份给 AI 编程助手(如 Cursor, GitHub Copilot, 或自定义 AI Agent)的“系统指令”和行为准则。
它的目的是限制 AI 的行为范围,强制它遵循特定的工作流,并防止 AI “自由发挥”导致项目代码混乱。
下面我为你逐个模块用中文进行技术拆解:
核心身份定义与特别警告
解释:
它告诉 AI:“你现在的角色是一个首席级别的全栈工程师,正在开发一个叫 SKEW 的 AI 新闻分析生产级项目。”
最关键的是中间那段警告This is NOT the Next.js you know:它明确告诉 AI,这个项目里的 Next.js 版本经过了魔改或有破坏性更新,禁止 AI 凭借自己训练数据里的旧知识直接写代码,必须先去读node_modules/next/dist/docs/里的本地文档。
1. Product (产品定义与边界)
解释:
定义了 SKEW 这个产品的核心功能:抓取真实新闻 -> AI 分析情感和偏见 -> 存入 Supabase -> 前端展示。
同时划定了一个严格的红线:“Do not overbuild” (不要过度开发)。AI 只能做列出的这 10 项功能(首页、详情页、Clerk认证、Supabase、Oxylabs爬虫、定时任务、AI分析、日志、pgvector相似度搜索、极简UI),不要自作主张加花里胡哨的功能。
2. Workflow (强制工作流)
解释:
这是给 AI 定下的“死规矩”,每次写代码必须走这 10 步:
- 重读本规则文件。
- 阅读用户提到的技能文档。
- 阅读相关支撑技能文档。
- 检查现有代码。
- 如果有不清楚的地方,问一个精准的问题。
- 在
prompts/目录下写一个详细的实现计划文件。 - 询问人类:“我准备好了计划文件,可以执行吗?”
- 只有得到人类批准,才能开始写代码。
- 运行代码检查(Lint/Type 检查等)。
- 告诉人类如何手动测试这个功能。
核心目的:防止 AI 瞎写一通,强制它先写文档计划,人类拍板后才能动代码。
3. Skills (技能白名单)
解释:
规定了 AI 在这个项目中只能使用以下四个指定的技能包目录里的知识:
.agents/skills/clerk:用于用户登录认证.agents/skills/supabase:用于数据库操作和 pgvector 向量搜索.agents/skills/oxylabs-web-scraper:用于抓取外部新闻网站.agents/skills/ai-sdk:用于调用 Vercel AI SDK 进行大模型分析
对于 Tailwind、shadcn/ui 等通用工具,让它参考项目现有代码模式,严禁 AI 自己发明新的技能或架构。
4. Prompt files (计划文件规范)
解释:
规定了第 6 步中提到的prompts/计划文件必须包含的结构。AI 不能随便写两句话糊弄,每个计划文件必须包含:
- 目标
- 读了哪些技能文档
- 看了哪些现有代码
- 做了哪些假设
- 会修改哪些文件
- 实现要求与安全要求
- 验收标准
- 运行的检查命令
- 最终的手动测试步骤
如果是 UI 任务,还要求写清楚视觉、布局、间距、颜色,甚至达到“像素级完美”的要求。
5. Architecture (架构分层原则)
解释:
这是整个项目的架构铁律,要求严格分层解耦:
- Website: 只负责 UI 展示。
- API: 只做薄薄的一层路由处理。
- Database: 只负责 Supabase 读写。
- Scraping: 只负责 Oxylabs 爬虫调用。
- Parsing: 只负责文章链接提取和清洗。
- AI: 只负责文章分析。
- Pipeline: 负责编排上述流程(爬取 -> 分析 -> 存储)并记录日志。
- Vector: 负责文章的向量嵌入和相似度查询。
最严厉的一条警告:“UI 必须只展示已存储的数据。UI 绝不能触发爬虫、触发 AI 分析或改变流水线状态。”
这意味着前端绝对不能直接调用爬虫或 AI 接口,所有数据必须是后台准备好存入数据库的。
总结
这份 AGENTS.md 是一份非常成熟的 AI 驯服指南。项目作者通过这个文件,把 AI 从一个“随心所欲的写代码机器”变成了一个“必须先写提案、经人工审批、严格遵守架构规范、不越界的高级打工人”。
.agents\skills\ai-sdk\SKILL.md
---
name: ai-sdk
description: 'Answer questions about the AI SDK and help build AI-powered features. Use when developers: (1) Ask about AI SDK functions like generateText, streamText, ToolLoopAgent, embed, or tools, (2) Want to build AI agents, chatbots, RAG systems, or text generation features, (3) Have questions about AI providers (OpenAI, Anthropic, Google, etc.), streaming, tool calling, structured output, or embeddings, (4) Use React hooks like useChat or useCompletion. Triggers on: "AI SDK", "Vercel AI SDK", "generateText", "streamText", "add AI to my app", "build an agent", "tool calling", "structured output", "useChat".'
---
## What the AI SDK Is
The AI SDK by Vercel (the `ai` package on npm) is a TypeScript toolkit for building AI applications. It provides a unified API across model providers for text generation, structured output, tool calling, agents, embeddings, and framework UI integrations.
- Repository: https://github.com/vercel/ai
- Documentation: https://ai-sdk.dev/docs
## Critical: Do Not Trust Your Own Memory
Whatever you remember about the AI SDK is likely outdated. The SDK changes frequently across versions - APIs are renamed, removed, and added. Your training data almost certainly contains obsolete APIs, deprecated patterns, and model IDs that no longer exist. UI hooks like `useChat` are among the most frequently changed APIs, so be especially careful with client code.
**Never write AI SDK code from memory.** Always verify every API, option, and pattern against the documentation and source code for the version that is actually installed in the project.
## Use the Bundled, Version-Matched Docs
The `ai` package ships its full documentation and source code inside `node_modules`. These always match the installed version, so trust them over anything you remember.
1. Ensure `ai` is installed. If `node_modules/ai/` does not exist, install **only** the `ai` package using the project's package manager (e.g. `pnpm add ai`). Install provider packages (e.g. `@ai-sdk/openai`) and framework packages (e.g. `@ai-sdk/react`) later, when the task requires them.
2. Read and grep the bundled docs at `node_modules/ai/docs/` and the source at `node_modules/ai/src/`.
3. Provider and framework packages bundle their own docs at `node_modules/@ai-sdk/<name>/docs/`.
4. If something isn't in the bundled docs, search https://ai-sdk.dev/docs. You can append `.md` to any docs page URL to get its markdown, and search via `https://ai-sdk.dev/api/search-docs?q=your_query`.
5. If you cannot find support for an answer in the docs or source, say so explicitly — do not guess.
## AI Gateway: The Fastest Way to Start
The Vercel AI Gateway is the fastest way to get started with the AI SDK. It provides access to models from OpenAI, Anthropic, Google, and other providers through a single API, without installing provider packages or managing multiple API keys.
To set it up:
1. Authenticate with OIDC (for Vercel deployments) or get an AI Gateway API key.
2. Provide it to your app via the `AI_GATEWAY_API_KEY` environment variable.
3. Reference models with `provider/model` strings.
For exact setup, authentication, and usage, read the bundled guide and the AI Gateway docs.
### Choosing a Model
Never use model IDs from memory — models are released and retired frequently. Fetch the current list before writing code that references a model. Do not truncate the list (e.g. with `head`) so you can find the newest models:
bash
# All available models
curl -s https://ai-gateway.vercel.sh/v1/models | jq -r '.data[].id'
# Filter by provider (e.g. anthropic, openai, google)
curl -s https://ai-gateway.vercel.sh/v1/models | jq -r '[.data[] | select(.id | startswith("anthropic/")) | .id] | reverse | .[]'
When multiple versions of a model exist, prefer the one with the highest version number.
## Building and Consuming Agents
Use the SDK's built-in agent abstraction (such as `ToolLoopAgent`) rather than hand-rolling tool-calling loops. For end-to-end type safety, infer the UI message type from your agent definition when consuming it on the client (e.g. with `useChat`). Consuming an agent is framework-specific: check `package.json` to detect the stack, then follow the matching quickstart.
Look up the current agent, tool, and type-safety APIs in the bundled docs (`node_modules/ai/docs/`, especially the agents section) or at https://ai-sdk.dev/docs.
## DevTools
AI SDK DevTools captures your AI SDK calls - requests, responses, tool calls, token usage, and multi-step runs - so you can inspect exactly what your agents do. Use it while developing to debug generations. It is a separate package and is intended for local development only.
For setup instructions, read the bundled DevTools documentation.
## Keep the SDK Current
Outdated installs are the most common source of errors. Compare the installed version against the latest:
- **Installed:** the `version` field in `node_modules/ai/package.json`.
- **Latest:** run `npm view ai version`.
If the installed version is a major version (or more) behind the latest, tell the user they are on an old release, and recommend upgrading before continuing. Migration guides are at https://ai-sdk.dev/docs/migration-guides.
## After Making Changes
Run the project's type checker. Be minimal — only set options that differ from the defaults, checking docs or source for the defaults rather than over-specifying. Most type errors come from remembered, now-changed APIs; re-check the current docs and source when they occur.
这份 .agents/skills/ai-sdk/SKILL.md 文件是一份专门给 AI 编程助手看的技能说明书。它的核心目的是:强制 AI 在使用 Vercel AI SDK 时,彻底放弃依靠自己记忆里的旧知识,必须“开卷考试”,查阅本地安装的最新文档来写代码。
下面为你逐个模块进行技术拆解:
元数据 (Frontmatter)
解释:
这是触发该技能的“开关”。它告诉 AI 系统:“当用户提到AI SDK、generateText、build an agent(构建智能体)、useChat等关键词时,请自动加载这份说明文档来指导你接下来的工作。”
1. What the AI SDK Is (什么是 AI SDK)
解释:
简单介绍了 Vercel AI SDK(npm 包名为ai)是什么:一个 TypeScript 工具包,用于统一调用各种大模型(OpenAI, Anthropic 等),处理文本生成、流式传输、工具调用、RAG 和前端 UI 集成。
2. Critical: Do Not Trust Your Own Memory (核心警告:不要相信你的记忆)
解释:
这是整个文件最严厉的警告。AI 大模型的训练数据是有截止日期的,而 AI SDK 这个库更新极其频繁,API 经常改名或废弃。
- 它明确告诉 AI:“你记忆中的 API(特别是
useChat这种前端 Hook)大概率已经过时了。” - 铁律:绝对禁止凭记忆写 AI SDK 的代码。
3. Use the Bundled, Version-Matched Docs (使用本地打包的匹配版本文档)
解释:
规定了 AI 去哪里查资料。
- 既然不能信记忆,那就看当前项目实际安装的版本。AI SDK 把完整的文档和源码直接打包放在了
node_modules/ai/docs/里。 - 工作流要求:先确认
ai包已安装 -> 去本地node_modules里读文档和源码 -> 如果本地没有,去官网查(可以在官网 URL 后加.md获取 Markdown 格式)-> 如果实在查不到,明确告诉用户“我不知道”,绝不能瞎猜。
4. AI Gateway: The Fastest Way to Start (最快接入方式:AI Gateway)
解释:
推荐使用 Vercel 的 AI Gateway 作为接入大模型的首选方式。
- 优点:不用在代码里分别安装和配置 OpenAI、Anthropic 等不同厂商的 SDK 和 API Key,只需一个
AI_GATEWAY_API_KEY环境变量,用provider/model的格式就能调用所有模型。 - 选择模型的铁律:又一次警告 AI 不要凭记忆写死模型 ID(比如写死
gpt-4-turbo),因为模型经常发布和废弃。它提供了具体的curl命令,要求 AI 在写代码前先运行命令拉取最新的可用模型列表,并选择版本号最高的那个。
5. Building and Consuming Agents (构建和使用智能体)
解释:
关于如何构建 AI Agent(能自动使用工具的智能体)的规范。
- 禁止造轮子:不要自己手写
while循环来处理工具调用,必须使用 SDK 内置的 Agent 抽象(如ToolLoopAgent)。 - 类型安全:在前端消费 Agent 时(比如用
useChat),要从 Agent 定义中推断 UI 消息类型,保证端到端的 TypeScript 类型安全。
6. DevTools (开发者工具)
解释:
提示 AI 可以建议用户安装 AI SDK DevTools。这是一个独立的调试工具包,可以抓取大模型的请求、响应、工具调用记录和 Token 消耗,仅供本地开发调试使用。
7. Keep the SDK Current (保持 SDK 版本最新)
解释:
要求 AI 在开始工作前做一次版本体检。
- 对比
node_modules/ai/package.json里的安装版本 和npm view ai version的最新版本。 - 如果发现落后了一个大版本,必须警告用户:“你的版本太旧了,建议先升级再看迁移指南”,因为旧版本写出来的代码大概率全是坑。
8. After Making Changes (修改代码后的收尾工作)
解释:
写完代码后的强制动作。
- 必须运行项目的类型检查器(比如
tsc)。 - 极简原则:写代码时只设置和默认值不同的配置项,不要过度配置。不要写一堆默认参数,要先查文档看默认值是什么。
- 如果报类型错误,大概率是因为 API 又变了,要求 AI 重新去查文档而不是瞎改类型。
总结
这份技能文件的核心思想就是四个字:“开卷考试”。
作者深知 AI 大模型在处理高频更新的开源库时极易产生“幻觉”(写出已经废弃的 API)。因此,通过这份文件,把 AI 从一个“凭记忆写代码的机器”变成了一个“严格按本地官方文档抄写代码的执行者”,最大程度保证了代码的可靠性和时效性。
.agents\skills\clerk\SKILL.md
---
name: clerk
description: Clerk authentication router. Use when user asks about Clerk CLI operations,
adding authentication, setting up Clerk, custom sign-in flows, Swift or native iOS
auth, native Android auth, Next.js patterns, React patterns, Vue patterns, Nuxt
patterns, Astro patterns, TanStack Start patterns, Expo patterns, React Router
patterns, Chrome Extension patterns, organizations, billing, subscriptions, payments,
pricing, plans, seat-based pricing, feature entitlements, syncing users, or testing.
Automatically routes to the specific skill based on their task.
license: MIT
metadata:
version: 2.0.0
---
# Clerk Skills Router
## Version Detection
Check `package.json` to determine the Clerk SDK version. This determines which patterns to use:
| Package | Core 2 (LTS until Jan 2027) | Current |
|---------|----------------------------|---------|
| `@clerk/nextjs` | v5–v6 | v7+ |
| `@clerk/react` or `@clerk/clerk-react` | v5–v6 | v7+ |
| `@clerk/expo` or `@clerk/clerk-expo` | v1–v2 | v3+ |
| `@clerk/react-router` | v1–v2 | v3+ |
| `@clerk/tanstack-react-start` | < v0.26.0 | v0.26.0+ |
**Default to current** if the version is unclear or the project is new. Core 2 packages use `@clerk/clerk-react` and `@clerk/clerk-expo` (with `clerk-` prefix); current packages use `@clerk/react` and `@clerk/expo`.
All skills are written for the current SDK. When something differs in Core 2, it's noted inline with `> **Core 2 ONLY (skip if current SDK):**` callouts. The exception is `clerk-custom-ui`, which has separate `core-2/` and `core-3/` directories for custom flow hooks since those APIs are entirely different between versions.
---
## By Task
**Adding Clerk to your project** → Use `clerk-setup`
- Framework detection and quickstart
- Environment setup, API keys, Keyless flow
- Migration from other auth providers
**Operating Clerk from the CLI** → Use `clerk-cli`
- Auth, linking, `doctor`, and environment pulls
- User, org, session, app, and instance management
- Backend and Platform API calls through `clerk api`
- Deploy handoff and deploy status verification
**Custom sign-in/sign-up UI** → Use `clerk-custom-ui`
- Custom authentication flows with `useSignIn` / `useSignUp` hooks
- Appearance and styling (themes, colors, layout)
- `<Show>` component for conditional rendering
**Advanced Next.js patterns** → Use `clerk-nextjs-patterns`
- Server vs Client auth APIs
- Middleware strategies
- Server Actions, caching
- API route protection
**React patterns** → Use `clerk-react-patterns`
- Hooks (`useAuth`, `useUser`, `useClerk`)
- Protected routes, auth guards
- Router integration
**React Router patterns** → Use `clerk-react-router-patterns`
- Loaders & actions with auth
- Route protection
- SSR auth
**Vue patterns** → Use `clerk-vue-patterns`
- Composables (`useAuth`, `useUser`, `useClerk`)
- Vue Router guards
- Pinia auth store integration
**Nuxt patterns** → Use `clerk-nuxt-patterns`
- Server middleware auth
- SSR auth with composables
- Server API routes
**Astro patterns** → Use `clerk-astro-patterns`
- SSR auth pages
- Island components with React
- Middleware & API routes
**TanStack Start patterns** → Use `clerk-tanstack-patterns`
- Server functions with auth
- Route protection via loaders
- Vinxi server integration
**Expo / React Native auth** → Use `clerk-expo`
- Prebuilt native components (AuthView, UserButton)
- Custom flows: email, password, SMS/phone OTP, MFA
- OAuth/SSO and native Google/Apple sign-in
- Expo Router protected routes, token storage, push notifications
**Chrome Extension patterns** → Use `clerk-chrome-extension-patterns`
- Background scripts auth
- Popup auth flows
- Content scripts with sync host
**B2B / Organizations** → Use `clerk-orgs`
- Multi-tenant apps
- Organization slugs in URLs
- Roles, permissions, RBAC
- Member management
**Billing & Subscriptions** → Use `clerk-billing`
- `<PricingTable />` component
- Plan and feature gating with `has()`
- Seat-based B2B billing with organizations
- Subscription lifecycle webhooks
- Free trials, invoicing
**Webhooks** → Use `clerk-webhooks`
- Real-time events
- Data syncing
- Notifications & integrations
**E2E Testing** → Use `clerk-testing`
- Playwright/Cypress setup
- Auth flow testing
- Test utilities
**Swift / native iOS auth** → Use `clerk-swift`
- Native iOS Swift and SwiftUI projects
- ClerkKit and ClerkKitUI implementation guidance
- Source-driven patterns from `clerk-ios`
**Android / native mobile auth** → Use `clerk-android`
- Native Android Kotlin and Jetpack Compose projects
- `clerk-android-api` and `clerk-android-ui` implementation guidance
- Source-driven patterns from `clerk-android`
- Do not use for Expo or React Native projects
**Backend REST API** → Use `clerk-backend-api`
- Browse API tags and endpoints
- Inspect endpoint schemas
- Execute API requests with scope enforcement
## Quick Navigation
If you know your task, you can directly access:
- `/clerk-setup` - Framework setup
- `/clerk-cli` - CLI operations and Clerk resource management
- `/clerk-custom-ui` - Custom flows & appearance
- `/clerk-nextjs-patterns` - Next.js patterns
- `/clerk-react-patterns` - React patterns
- `/clerk-react-router-patterns` - React Router patterns
- `/clerk-vue-patterns` - Vue patterns
- `/clerk-nuxt-patterns` - Nuxt patterns
- `/clerk-astro-patterns` - Astro patterns
- `/clerk-tanstack-patterns` - TanStack Start patterns
- `/clerk-expo` - Expo / React Native
- `/clerk-chrome-extension-patterns` - Chrome Extension patterns
- `/clerk-orgs` - Organizations
- `/clerk-billing` - Billing & subscriptions
- `/clerk-webhooks` - Webhooks
- `/clerk-testing` - Testing
- `/clerk-swift` - Swift/native iOS
- `/clerk-android` - Native Android
- `/clerk-backend-api` - Backend REST API
Or describe what you need and I'll recommend the right one.
这份 .agents/skills/clerk/SKILL.md 文件与前两个不同,它本身并不包含具体的写代码指南,而是一个路由调度器。
它的核心作用是:当 AI 接收到关于认证的任务时,先读这个文件,判断当前项目用的是什么技术栈、什么版本的 Clerk,然后把任务分发给对应的具体技能文档去执行。
下面为你逐个模块进行技术拆解:
元数据与触发器
解释:
这部分告诉 AI 什么时候应该激活这个技能。当用户提到“添加认证”、“Clerk CLI”、“Next.js/React/Vue 等框架模式”、“组织”、“计费订阅”、“Webhooks”等关键词时,这个路由文件就会被加载。
Version Detection (版本检测:防止 AI 写出废弃 API)
解释:
这一段非常关键。Clerk 最近经历了从 “Core 2” 到 “Current (v3+)” 的大版本跨越,很多 API(特别是包名和前端 Hook)发生了破坏性变更。
- 强制动作:要求 AI 必须先去读
package.json,看清楚项目装的是哪个版本的@clerk/xxx。 - 版本对照表:列出了不同包在 Core 2 和 Current 版本的对应关系。比如
@clerk/nextjs的 v5-v6 是旧版,v7+ 是新版。 - 防幻觉机制:如果 AI 分不清版本,默认按最新版写。如果遇到旧版特有的 API,文档里会有特定的标注(
> Core 2 ONLY...),AI 看到这个标注就知道要跳过,避免在新项目里写出旧代码。特别是自定义 UI(clerk-custom-ui),因为差异太大,甚至分了两个不同的目录让 AI 去读。
By Task (任务路由表:AI 的调度中心)
解释:
这是文件的核心。它像一个客服系统的派单表,告诉 AI 面对不同的需求,应该去哪个具体的子技能文档找答案:
- 初始化与运维:
- 想要在项目里接入 Clerk → 去读
clerk-setup - 想用命令行操作 Clerk(如拉取环境变量、管理用户)→ 去读
clerk-cli
- 想要在项目里接入 Clerk → 去读
- 前端框架适配:
- Next.js 模式(服务端/客户端鉴权、中间件保护)→
clerk-nextjs-patterns - 纯 React、Vue、Nuxt、Astro、TanStack Start 等框架的鉴权模式 → 各自对应的文档。
- Next.js 模式(服务端/客户端鉴权、中间件保护)→
- 移动端与插件:
- Expo / React Native 开发 →
clerk-expo - 原生 iOS (Swift) 或原生 Android (Kotlin) →
clerk-swift/clerk-android - Chrome 扩展程序鉴权 →
clerk-chrome-extension-patterns
- Expo / React Native 开发 →
- 高级业务功能:
- B2B 多租户、组织管理、角色权限 (RBAC) →
clerk-orgs - 计费、订阅、按人头收费、功能门槛 →
clerk-billing - 数据同步与 Webhooks →
clerk-webhooks - 端到端测试 (E2E Testing) →
clerk-testing - 后端 REST API 直接调用 →
clerk-backend-api
- B2B 多租户、组织管理、角色权限 (RBAC) →
Quick Navigation (快速导航)
解释:
这是一份目录索引。AI 在根据上面的“任务路由表”确定了方向后,可以直接通过这里的路径(如/clerk-nextjs-patterns)快速跳转到具体的技能文档。
总结
这份文件扮演了 “交通警察” 的角色。
由于 Clerk 支持十几种前端框架,且经历了大版本更迭,如果把所有代码示例都写在一个文件里会极其庞大且容易让 AI 混淆。因此,作者用这份文档让 AI 先做两道判断题:
- 项目是什么版本的 Clerk?(防旧 API 坑)
- 用户要做什么特定框架/特定功能的任务?(精准派发)
判断清楚后,AI 再去读取对应的专属技能文档,从而保证写出来的代码完全符合当前项目的技术栈和版本。
.agents/skills/oxylabs-web-scraper/SKILL.md
---
name: oxylabs-web-scraper
description: Production-grade web scraping with automatic anti-bot bypass, structured JSON parsing for 40+ targets, and geo-targeting. Use when the user needs to scrape web pages, extract product data, get search results, or collect structured data from supported e-commerce and search platforms without worrying about getting blocked and when geo targeting is required.
---
# Oxylabs Web Scraper API
## Authentication
Requires HTTP Basic Auth with credentials from environment variables:
```bash
curl -u "$OXY_WSA_USERNAME:$OXY_WSA_PASSWORD" ...
Endpoint
POST https://realtime.oxylabs.io/v1/queries # immediate response
POST https://data.oxylabs.io/v1/queries # Push-Pull jobs, callbacks, storage
Content-Type: application/json
Core Parameters
| Parameter | Required | Description |
|---|---|---|
source |
Yes | Target scraper (e.g., universal, amazon_product, google_search) |
url |
Conditional | URL to scrape (for universal and *_url sources) |
query |
Conditional | Search query or product ID (for *_search and *_product sources) |
parse |
No | Enable structured data parsing (recommended for supported sources) |
render |
No | JavaScript rendering: html or png |
geo_location |
No | Geographic targeting: country/state/city, ZIP/postcode, coordinates, or Criteria ID where supported |
session_id |
No | Reuse the same proxy IP across multiple jobs |
content_encoding |
No | Set to base64 when downloading image files via Realtime or Push-Pull |
user_agent_type |
No | Device/browser preset, e.g., desktop_chrome, mobile_ios, tablet_android |
locale |
No | Interface language / Accept-Language, e.g., de-DE |
callback_url |
No | Push-Pull callback endpoint |
storage_type, storage_url |
No | Push-Pull cloud upload target (gcs, s3, tos, s3_compatible) |
markdown, xhr |
No | Enable markdown or captured XHR result types |
browser_instructions |
No | Rendered browser actions; requires render: "html" |
parsing_instructions, parser_preset |
No | Custom parser rules or saved preset; pair with parse: true |
client_notes |
No | Client-side job tag saved with the job metadata |
domain, subdomain, start_page, pages, limit, store_id, delivery_zip, fulfillment_type |
Source-specific | Marketplace/search/store localization and pagination fields |
user_agent_type values: desktop, desktop_chrome, desktop_edge, desktop_firefox, desktop_opera, desktop_safari, mobile, mobile_android, mobile_ios, tablet, tablet_android, tablet_ios.
Context Parameters
Add these as { "key": "...", "value": ... } objects in context:
| Key | Use |
|---|---|
force_headers, headers |
Merge custom headers with managed headers |
force_cookies, cookies |
Merge custom cookies with managed cookies |
http_method, content |
Use post with Base64-encoded body content |
follow_redirects |
Follow 3xx redirect chains |
successful_status_codes |
Treat specific non-standard HTTP codes as successful |
For multi-format output, enable types in the payload (parse, markdown, xhr, render: "png") and request them with ?type=raw,parsed,png,markdown,xhr.
For batch Push-Pull jobs, use POST /v1/queries/batch with arrays only for query or url; keep all other parameters singular. Maximum batch size is 5,000 values.
Quick Start
Scrape any URL:
curl -X POST 'https://realtime.oxylabs.io/v1/queries' \
-u "$OXY_WSA_USERNAME:$OXY_WSA_PASSWORD" \
-H 'Content-Type: application/json' \
-d '{"source": "universal", "url": "https://example.com"}'
Google search with parsing:
curl -X POST 'https://realtime.oxylabs.io/v1/queries' \
-u "$OXY_WSA_USERNAME:$OXY_WSA_PASSWORD" \
-H 'Content-Type: application/json' \
-d '{"source": "google_search", "query": "best laptops", "parse": true}'
Amazon product by ASIN:
curl -X POST 'https://realtime.oxylabs.io/v1/queries' \
-u "$OXY_WSA_USERNAME:$OXY_WSA_PASSWORD" \
-H 'Content-Type: application/json' \
-d '{"source": "amazon_product", "query": "B07FZ8S74R", "parse": true}'
Choosing the Right Source
- Use specific sources when available (
amazon_product,google_search) - better parsing and reliability - Use
universalfor unsupported sites - works with any URL - Enable
parse: truefor structured JSON output on supported sources
Response Structure
{
"results": [{
"content": "...",
"status_code": 200,
"url": "https://..."
}]
}
With parse: true, content contains structured data (title, price, reviews, etc.) instead of raw HTML.
Available Sources
For the complete list of 40+ supported sources organized by category, see sources.md.
More Examples
For detailed request/response examples including geo-location, JavaScript rendering, and custom headers, see examples.md.
Error Handling
| Code | Meaning |
|---|---|
| 200 | Success |
| 400 | Invalid parameters |
| 401 | Authentication failed |
| 403 | Access denied |
| 429 | Rate limit exceeded |
Key Guidelines
- Always set
parse: truefor supported sources to get structured data - Use ZIP codes for US e-commerce geo-location (e.g.,
"90210") - Use country/state format for search engines (e.g.,
"California,United States") - Add
render: "html"for JavaScript-heavy pages - Use
render: ""only to disable automatic forced rendering for force-rendered pages; set client timeouts near 180 seconds for rendered Realtime or Proxy Endpoint requests - Add
content_encoding: "base64"when scraping image URLs, then decoderesults[0].contentbefore saving the file
这份 .agents/skills/oxylabs-web-scraper/SKILL.md 文件是一份生产级爬虫工具的技能说明书。它的目的是教 AI 如何正确调用 Oxylabs Web Scraper API 去抓取网页数据,并避开反爬虫机制。
由于你们项目(SKEW)需要去外部新闻网站抓取真实新闻,这份文档就是 AI 编写爬虫代码时的“操作手册”。
下面为你逐个模块进行技术拆解:
元数据与触发器
解释:
当用户提到“抓取网页”、“提取商品数据”、“获取搜索结果”、“需要地理位置定位”或“防止被封禁”时,这个技能会被激活。它主打的是企业级、自带反爬绕过、支持结构化解析和地理定位。
1. Authentication (认证方式)
解释:
规定了如何安全地连接到 Oxylabs。强制要求使用 HTTP Basic Auth,并且必须通过环境变量($OXY_WSA_USERNAME和$OXY_WSA_PASSWORD)读取账号密码,不能在代码里硬编码明文密码。
2. Endpoint & Core Parameters (接口与核心参数)
解释:
这是写代码时最关键的参数对照表。
- 接口:提供了两种模式。
realtime(实时返回结果)和data(Push-Pull 模式,支持回调和高并发存储,适合大批量抓取)。 - 核心参数:
source(必填):决定用什么引擎去抓。比如universal(通用引擎)或专门针对亚马逊、谷歌的专用引擎。parse: true:极其重要。开启后,API 不会返回乱糟糟的 HTML,而是自动解析成干净的 JSON 数据。render:遇到需要执行 JavaScript 才能显示内容的网页(比如现代单页应用 SPA),设置为html让爬虫先渲染再抓取。geo_location:地理定位。可以指定国家、城市甚至邮编(比如抓取美国某个特定地区展示的新闻或商品)。user_agent_type:伪装设备类型,比如desktop_chrome或mobile_ios。
3. Context Parameters (上下文参数与高级配置)
解释:
处理更复杂的抓取场景:
- 可以自定义
headers和cookies绕过简单的登录验证。 - 批量任务:如果要一次性抓 5000 个网址,不要写 for 循环发 5000 次请求,而是使用批量接口
POST /v1/queries/batch,把 URL 放在数组里一次发过去。
4. Quick Start (快速开始模板)
解释:
为了让 AI 少犯错,文档直接提供了三个现成的curl代码模板:
- 抓任意 URL:用
universal引擎。 - 抓谷歌搜索:用
google_search引擎 +query关键词 + 开启parse。 - 抓亚马逊商品:用
amazon_product引擎 +query(ASIN码) + 开启parse。
AI 在写代码时可以直接参考这些结构。
5. Choosing the Right Source (引擎选择策略)
解释:
给 AI 定下的抓取优先级逻辑:
- 首选专用引擎:如果抓亚马逊、谷歌,用专用的(如
amazon_product),解析更准,成功率更高。 - 备选通用引擎:如果是抓普通新闻网站,没有专用引擎,就用
universal。 - 一定要开解析:只要引擎支持,一定要加
parse: true拿结构化数据。
6. Response Structure & Error Handling (响应结构与错误处理)
解释:
- 告诉 AI 返回的 JSON 长什么样(数据在
results[0].content里)。 - 列出了常见的错误码,特别是 429 (Rate limit exceeded),提醒 AI 在写代码时要注意限流问题。
7. Key Guidelines (AI 必须遵守的避坑指南)
解释:
这是作者给 AI 划的重点,通常是踩过坑的经验总结:
- 能用
parse就用:别自己去写正则解析 HTML,用自带的解析功能。 - 地理定位有讲究:电商网站要用邮编定位(如
"90210"),搜索引擎要用州/国家格式(如"California,United States")。 - JS 渲染超时问题:如果网页需要
render: "html",因为要启动无头浏览器加载页面,速度很慢。AI 写代码时必须把客户端超时时间设置为接近 180 秒,否则很容易请求超时报错。 - 下载图片要解码:如果抓取的是图片 URL,要把
content_encoding设为base64,拿到数据后在代码里再进行 Base64 解码保存文件。
总结
这份技能文件非常务实,它没有讲太多理论,而是直接给 AI 提供了一份**“参数字典 + 代码模板 + 避坑指南”**。
通过阅读这个文件,AI 能够立刻写出带有环境变量校验、正确选择引擎、设置合理超时时间、并返回结构化 JSON 数据的高质量爬虫代码。结合你们 SKEW 项目(抓取新闻 -> AI 分析),AI 知道要开启 parse 或 render 去拿到干净的文章正文。
.agents\skills\supabase\SKILL.md
---
name: supabase
description: "Use when doing ANY task involving Supabase. Triggers: Supabase products (Database, Auth, Edge Functions, Realtime, Storage, Vectors, Cron, Queues); client libraries and SSR integrations (supabase-js, @supabase/ssr) in Next.js, React, SvelteKit, Astro, Remix; auth issues (login, logout, sessions, JWT, cookies, getSession, getUser, getClaims, RLS); Supabase CLI or MCP server; schema changes, migrations, declarative schemas, security audits, Postgres extensions (pg_graphql, pg_cron, pg_vector)."
metadata:
author: supabase
version: "0.1.2"
---
# Supabase
## Core Principles
**1. Supabase changes frequently — verify against changelog and current docs before implementing.**
Do not rely on training data for Supabase features. Function signatures, config.toml settings, and API conventions change between versions.
First, fetch `https://supabase.com/changelog.md` (a lightweight summary index — not a heavy pull), scan for `breaking-change` tags relevant to your task, and follow the linked page for any that apply. Then look up the relevant topic using the documentation access methods below.
**2. Verify your work.**
After implementing any fix, run a test query to confirm the change works. A fix without verification is incomplete.
**3. Recover from errors, don't loop.**
If an approach fails after 2-3 attempts, stop and reconsider. Try a different method, check documentation, inspect the error more carefully, and review relevant logs when available. Supabase issues are not always solved by retrying the same command, and the answer is not always in the logs, but logs are often worth checking before proceeding.
**4. Exposing tables to the Data API:** Depending on the user's [Data API settings](https://supabase.com/dashboard/project/<ref>/integrations/data_api/settings), newly created tables may not be automatically exposed via the Data (REST) API. If this is the case, `anon` and `authenticated` roles will need to be explicitly granted access.
> Note that this is separate from RLS, which controls which _rows_ are visible once a table is accessible, not whether the table is accessible at all.
When a user reports a SQL-created table is unexpectedly inaccessible, check their Data API settings and whether the roles have been granted access via explicit `GRANT` SQL. When granting public (`anon`/`authenticated`) access, always enable RLS too. See [Exposing a Table to the Data API](https://supabase.com/docs/guides/api/securing-your-api.md) for the full setup workflow.
**5. RLS in exposed schemas.**
Enable RLS on every table in any exposed schema, which includes `public` by default. This is critical in Supabase because tables in exposed schemas can be reachable through the Data API when the `anon`/`authenticated` roles have access (see [Exposing a Table to the Data API](https://supabase.com/docs/guides/api/securing-your-api.md)). For private schemas, prefer RLS as defense in depth. After enabling RLS, create policies that match the actual access model rather than defaulting every table to the same `auth.uid()` pattern.
**6. Security checklist.**
When working on any Supabase task that touches auth, RLS, views, storage, or user data, run through this checklist. These are Supabase-specific security traps that silently create vulnerabilities:
- **Auth and session security**
- **Never use `user_metadata` claims in JWT-based authorization decisions.** In Supabase, `raw_user_meta_data` is user-editable and can appear in `auth.jwt()`, so it is unsafe for RLS policies or any other authorization logic. Store authorization data in `raw_app_meta_data` / `app_metadata` instead.
- **Deleting a user does not invalidate existing access tokens.** Sign out or revoke sessions first, keep JWT expiry short for sensitive apps, and for strict guarantees validate `session_id` against `auth.sessions` on sensitive operations.
- **If you use `app_metadata` or `auth.jwt()` for authorization, remember JWT claims are not always fresh until the user's token is refreshed.**
- **API key and client exposure**
- **Never expose the `service_role` or secret key in public clients.** Prefer publishable keys for frontend code. Legacy `anon` keys are only for compatibility. In Next.js, any `NEXT_PUBLIC_` env var is sent to the browser.
- **RLS, views, and privileged database code**
- **Views bypass RLS by default.** In Postgres 15 and above, use `CREATE VIEW ... WITH (security_invoker = true)`. In older versions of Postgres, protect your views by revoking access from the `anon` and `authenticated` roles, or by putting them in an unexposed schema.
- **UPDATE requires a SELECT policy.** In Postgres RLS, an UPDATE needs to first SELECT the row. Without a SELECT policy, updates silently return 0 rows — no error, just no change.
- **`auth.role()` is deprecated — use the `TO` clause instead.** Supabase has deprecated `auth.role()` in favour of specifying the target role directly on the policy with `TO authenticated` or `TO anon`. Beyond deprecation, `auth.role() = 'authenticated'` breaks silently when anonymous sign-ins are enabled, because anonymous users carry the `authenticated` Postgres role and pass the check regardless of whether the user is genuinely signed in.
```sql
-- Deprecated (do not use)
create policy "example" on table_name for select
using ( auth.role() = 'authenticated' );
```
- **`TO authenticated` alone is authentication without authorization (BOLA / IDOR).** Using `TO authenticated` only checks the role — it does not restrict which rows a user can access. The correct pattern combines `TO authenticated` with an ownership predicate in `USING`:
```sql
create policy "example" on table_name for select
to authenticated
using ( (select auth.uid()) = user_id );
```
- **UPDATE policies require both `USING` and `WITH CHECK`.** Without `WITH CHECK`, a user can reassign a row's `user_id` to another user:
```sql
create policy "example" on table_name for update
to authenticated
using ( (select auth.uid()) = user_id )
with check ( (select auth.uid()) = user_id );
```
- **`SECURITY DEFINER` functions bypass RLS.** A `SECURITY DEFINER` function runs with its creator's privileges — typically a role with `bypassrls` (e.g., `postgres`). Never add `SECURITY DEFINER` to resolve a permission error; it silently removes access control without fixing the underlying cause. Prefer `SECURITY INVOKER`.
- **`SECURITY DEFINER` functions in `public` are callable by all roles.** Postgres grants `EXECUTE` to `PUBLIC` by default for every new function, so any `SECURITY DEFINER` function in `public` is a public API endpoint callable by `anon` and `authenticated` (which inherit from `PUBLIC`) without any additional grant. When `SECURITY DEFINER` is genuinely needed (e.g., bypassing RLS on an internal lookup table), keep the function in a non-exposed schema, always include an `auth.uid()` check in the function body, and run `supabase db advisors` after making changes.
- **Storage access control**
- **Storage upsert requires INSERT + SELECT + UPDATE.** Granting only INSERT allows new uploads but file replacement (upsert) silently fails. You need all three.
- **Dependency and supply-chain security**
- **Always pin package versions and commit lockfiles** when installing Supabase packages (`supabase-js`, `@supabase/ssr`, `supabase-py`, etc.). See the [npm security guide](https://supabase.com/docs/guides/security/npm-security.md) for the full checklist.
For any security concern not covered above, fetch the Supabase product security index: `https://supabase.com/docs/guides/security/product-security.md`
## Supabase CLI
Always discover commands via `--help` — never guess. The CLI structure changes between versions.
```bash
supabase --help # All top-level commands
supabase <group> --help # Subcommands (e.g., supabase db --help)
supabase <group> <command> --help # Flags for a specific command
Supabase CLI Known gotchas:
supabase db queryrequires CLI v2.79.0+ → use MCPexecute_sqlorpsqlas fallbacksupabase db advisorsrequires CLI v2.81.3+ → use MCPget_advisorsas fallback- In imperative migration projects, create new hand-authored migration files with
supabase migration new <name>first. Never invent a migration filename or rely on memory for the expected format. Declarative schema projects generate migrations fromsupabase/schemas/; see “Making and Committing Schema Changes” below.
Version check and upgrade: Run supabase --version to check. For CLI changelogs and version-specific features, consult the CLI documentation or GitHub releases.
Supabase MCP Server
For setup instructions, server URL, and configuration, see the MCP setup guide.
Troubleshooting connection issues — follow these steps in order:
-
Check if the server is reachable:
curl -so /dev/null -w "%{http_code}" https://mcp.supabase.com/mcp
A401is expected (no token) and means the server is up. Timeout or “connection refused” means it may be down. -
Check
.mcp.jsonconfiguration:
Verify the project root has a valid.mcp.jsonwith the correct server URL. If missing, create one pointing tohttps://mcp.supabase.com/mcp. -
Authenticate the MCP server:
If the server is reachable and.mcp.jsonis correct but tools aren’t visible, the user needs to authenticate. The Supabase MCP server uses OAuth 2.1 — tell the user to trigger the auth flow in their agent, complete it in the browser, and reload the session.
Supabase Documentation
Before implementing any Supabase feature, find the relevant documentation. Use these methods in priority order:
- MCP
search_docstool (preferred — returns relevant snippets directly) - Fetch docs pages as markdown — any docs page can be fetched by appending
.mdto the URL path. - Web search for Supabase-specific topics when you don’t know which page to look at.
Making and Committing Schema Changes
First decide which schema workflow the project uses.
Option A: Declarative schemas
Use this when supabase/schemas/ exists or config.toml sets schema_paths. Edit the desired schema state in those files, then generate and review the migration. Do not start by hand-writing a migration. See the Declarative database schemas guide.
Option B: Imperative migrations
Use this when the project does not use declarative schemas.
To make schema changes, use execute_sql (MCP) or supabase db query (CLI). These run SQL directly on the database without creating migration history entries, so you can iterate freely and generate a clean migration when ready.
Do NOT use apply_migration to change a local database schema — it writes a migration history entry on every call, which means you can’t iterate, and supabase db diff / supabase db pull will produce empty or conflicting diffs. If you use it, you’ll be stuck with whatever SQL you passed on the first try.
When ready to commit your changes to a migration file:
- Run advisors →
supabase db advisors(CLI v2.81.3+) or MCPget_advisors. Fix any issues. - Review the Security Checklist above if your changes involve views, functions, triggers, or storage.
- Generate the migration →
supabase db pull <descriptive-name> --local --yes - Verify →
supabase migration list --local
Reference Guides
- Skill Feedback → references/skill-feedback.md
MUST read when the user reports that this skill gave incorrect guidance or is missing information.
这份 `.agents/skills/supabase/SKILL.md` 文件是一份**非常硬核的 Supabase 安全与开发技能说明书**。与前几个技能类似,它极力防止 AI 凭借过期的记忆写代码,但这份文件花费了极大的篇幅强调**数据库安全(特别是 RLS 行级安全)**,因为 Supabase 直接把数据库暴露给了前端,一旦写错权限,就会导致严重的数据泄露。
下面为你逐个模块进行技术拆解:
---
### 元数据与触发器
> **解释:**
当用户提到 Supabase 的数据库、认证、Edge Functions、实时推送、存储、向量,或者在 Next.js/React 等框架中处理登录会话、编写 SQL 迁移文件时,这个技能会被激活。
### 1. Core Principles (核心原则:防幻觉与纠错机制)
> **解释:**
* **不要相信记忆**:Supabase 更新很快,AI 必须先去抓取官方的更新日志,看看有没有破坏性变更,再查文档写代码。
* **必须验证**:写完数据库修改代码后,AI 必须跑一个测试查询确认生效,不能写完就完事。
* **不要死循环**:如果一个 SQL 报错,AI 尝试 2-3 次后必须停下来,换个思路或查日志,不能一直用同样的代码瞎试。
### 2. 暴露表与 RLS (行级安全) 的致命陷阱
> **解释:**
这是 Supabase 最容易踩坑的地方,文档重点强调了几个概念:
* **Data API 暴露问题**:新建的表默认可能无法通过前端 API 访问,必须用 SQL 显式赋予 `anon`(游客)和 `authenticated`(已登录)角色访问权限。
* **RLS 是最后一道防线**:表一旦能被访问,**必须立刻开启 RLS(行级安全)**。否则游客就能通过 API 看到整张表的数据。
### 3. Security Checklist (安全审查清单:极其重要)
> **解释:**
这里列出了 Supabase 开发中常见的安全漏洞,AI 在写任何涉及权限的代码时都必须对照检查:
* **JWT 认证陷阱**:
* 绝对不要用 `user_metadata`(用户可自行修改的数据)来做权限判断。必须用 `app_metadata`。
* 删除用户不会让现有的 Token 失效,必须先登出或设置较短的过期时间。
* **密钥泄露陷阱**:绝对不要在前端代码(如 `NEXT_PUBLIC_` 变量)里暴露 `service_role` 密钥,这个密钥能绕过所有安全限制。
* **RLS 与视图的暗坑**:
* **视图默认绕过 RLS**:如果你建了一个 View,它默认不看 RLS 策略。必须用 `CREATE VIEW ... WITH (security_invoker = true)`。
* **更新需要查询权限**:写 RLS 策略时,如果你想 `UPDATE` 一行,必须先给它配 `SELECT` 策略,否则会默默失败(不报错,但 0 行受影响)。
* **废弃的写法**:不要再用 `auth.role() = 'authenticated'` 这种写法了,要直接用 `TO authenticated`。
* **防止越权 (BOLA/IDOR)**:只写 `TO authenticated` 只是验证了“你登录了”,没验证“你能改这条数据”。必须在 `USING` 里加上所有权判断,比如 `auth.uid() = user_id`。
* **防止篡改归属**:`UPDATE` 策略必须同时写 `USING` 和 `WITH CHECK`,否则用户可以把别人的文章 `user_id` 改成自己的。
* **SECURITY DEFINER 陷阱**:写数据库函数时,尽量避免用 `SECURITY DEFINER`(以创建者权限运行,通常是超级管理员),这会直接绕过 RLS。
### 4. Supabase CLI & MCP Server (工具使用规范)
> **解释:**
* **CLI 谨慎使用**:告诉 AI 不要凭记忆猜命令,必须用 `--help` 去查。还列出了特定命令需要的最低版本号。
* **MCP Server 故障排查**:MCP(模型上下文协议)是 AI 与 Supabase 交互的桥梁。如果连不上,AI 要按顺序检查网络、配置文件、以及 OAuth 登录状态。
### 5. Documentation Lookup (文档查阅优先级)
> **解释:**
给 AI 规定了找资料的优先顺序:
1. 先用 MCP 工具的 `search_docs` 搜索(最准)。
2. 去官方文档 URL 后面加 `.md` 拉取 Markdown 文本。
3. 最后才考虑用搜索引擎搜。
### 6. Making and Committing Schema Changes (数据库 Schema 变更流程)
> **解释:**
规定了如何修改数据库表结构:
* **声明式 Schema (Option A)**:如果项目用声明式(在 `supabase/schemas/` 里写状态),直接改文件,然后自动生成迁移文件。
* **命令式迁移 (Option B)**:
* **迭代阶段**:用 `execute_sql` 直接在数据库里跑 SQL 测试,不要用 `apply_migration`,否则会把迁移历史弄脏。
* **提交阶段**:确认没问题后,运行 `supabase db advisors`(安全顾问检查)-> 检查上面的安全清单 -> 用 `supabase db pull` 生成正式的迁移文件。
---
### 总结
如果说前几个技能文件是“操作手册”,那么这份 Supabase 技能文件就是一份**“排雷指南”**。
由于 Supabase 将 PostgreSQL 的强大能力直接暴露给了前端,稍有不慎就会导致全库被删或数据泄露。这份文件通过极其详尽的安全清单和 RLS 策略说明,强制 AI 写出符合最高安全标准的数据库代码,尤其是防止越权访问和绕过 RLS 的致命错误。
更多推荐


所有评论(0)