惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
IT之家
IT之家
博客园_首页
博客园 - 【当耐特】
V
V2EX
Apple Machine Learning Research
Apple Machine Learning Research
G
Google Developers Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recent Announcements
Recent Announcements
F
Fortinet All Blogs
GbyAI
GbyAI
腾讯CDC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
H
Help Net Security
T
Tailwind CSS Blog
B
Blog RSS Feed
Martin Fowler
Martin Fowler
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
博客园 - 叶小钗
雷峰网
雷峰网
量子位

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Cursor Rules That Actually Improve AI Output (.mdc Projec...
NongdyZ · 2026-06-28 · via DEV Community

Most Cursor rules I see online are wish lists. "Write clean code." "Follow best practices." "Be concise." Cursor reads them, nods politely, and ships exactly the same code it would have without them.

The reason is simple: vague rules give the model nothing to act on. A rule only changes output if it's specific, enforceable, and scoped to when it matters. After rewriting my rules around those three properties, Cursor went from "code that works but I'd reject in review" to "code that passes review the first time" on most requests.

Here's what actually moved the needle, with real .mdc rules you can paste in.

The format: .cursor/rules/*.mdc, not .cursorrules

Cursor has moved to Project Rules stored as .mdc files in .cursor/rules/. The big advantage over the old single .cursorrules file is scoping: each rule has frontmatter that controls when it loads.

---
description: "Security rules for all code"
globs:
alwaysApply: true
---

Three frontmatter fields decide everything:

  • alwaysApply: true — the rule is in context on every request. Use for short, universal rules (security, error handling).
  • globs: "**/*.tsx" — the rule auto-attaches only when a matching file is in play. Use for stack-specific rules so your React rules don't pollute your Python context.
  • Neither set — the agent pulls the rule in when it judges it relevant, based on the description. Use for situational best-practice rules.

This scoping is the whole game. Loading every rule on every request dilutes the context and the model starts ignoring all of them. Scoped rules stay sharp because only the relevant ones are present.

Rule 1: A global rule the model can actually enforce

Keep your always-on rule short and written as concrete checks, not aspirations:

---
description: Global engineering rules — always apply
globs:
alwaysApply: true
---

- Validate and type all external input (API bodies, query params, env vars) at the boundary.
- Every function that can fail returns a typed error or throws — never returns null silently.
- No secrets in code. Read from env. Never log tokens, passwords, or full PII.
- When you change a function's signature, update every caller in the same change.
- Prefer deleting code over adding flags. The best fix removes complexity.

Notice there's no "write clean code." Every line is a check the model can apply to a specific diff. "Validate input at the boundary" produces a zod schema; "write clean code" produces nothing.

Rule 2: A stack rule scoped by glob

This one only loads when a TypeScript/React file is involved, so it never interferes with your backend or scripts:

---
description: React + TypeScript conventions
globs: "**/*.tsx, **/*.ts"
alwaysApply: false
---

- Components are typed function components. No `React.FC`. Props via an explicit interface.
- No `any`. Use `unknown` + a narrow, or define the type. If you truly can't, add a `// TODO: type` and explain.
- Follow the Rules of Hooks: no hooks in conditions or loops. Effects list every dependency they read.
- Data fetching goes through the existing query layer, not raw `fetch` inside components.
- Every interactive element is keyboard-accessible and has an accessible name (label, aria-label, or text).

The no any rule is the one people underrate. Left alone, Cursor reaches for any constantly because it's the path of least resistance. One scoped line removes most of it and forces it to think about the actual type.

Rule 3: A best-practice rule the agent loads on demand

Some rules only matter sometimes — like database access. Leave alwaysApply off and write a clear description so the agent pulls it in when it touches SQL:

---
description: Database and SQL safety — apply when writing queries or migrations
globs:
alwaysApply: false
---

- Always use parameterized queries / prepared statements. Never interpolate user input into SQL.
- Every query that can return many rows is paginated or explicitly bounded with LIMIT.
- Add an index before shipping a query that filters or joins on a non-indexed column — call it out.
- Migrations are reversible and never run automatically. Generate the file; let the human apply it.
- Watch for N+1: fetching a list then querying per item is a bug, not a style choice.

Because this rule isn't always loaded, it doesn't eat context on your CSS work. But the moment you ask Cursor to write a query, its description makes it relevant and it gets pulled in.

The before/after that convinced me

Same request — "add an endpoint to fetch a user's orders" — with and without the rules above.

Without rules:

app.get("/orders", async (req, res) => {
  const userId = req.query.userId;
  const orders = await db.query(`SELECT * FROM orders WHERE user_id = ${userId}`);
  res.json(orders);
});

SQL injection, no input validation, no pagination, SELECT *.

With the rules:

const Query = z.object({ userId: z.string().uuid(), page: z.coerce.number().min(1).default(1) });

app.get("/orders", async (req, res) => {
  const parsed = Query.safeParse(req.query);
  if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
  const { userId, page } = parsed.data;
  const limit = 50;
  const orders = await db.query(
    "SELECT id, total, status, created_at FROM orders WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
    [userId, limit, (page - 1) * limit]
  );
  res.json({ orders, page });
});

Parameterized, validated, paginated, explicit columns. Same model, same prompt. The rules did that.

How to start without overdoing it

Don't write twenty rules on day one — you'll dilute the context and burn out maintaining them. Start with exactly three:

  1. One short alwaysApply global rule (security + error handling).
  2. One glob-scoped rule for your main stack.
  3. One on-demand rule for whatever bites you most (SQL, accessibility, tests).

Live with those for a week, then add a rule only when you catch Cursor making the same mistake twice. Rules earn their place by preventing a real, repeated error.

If you want a full, tuned AI-coding setup

Rules are one half of the picture. The other half is giving your AI assistant a real workflow — focused review/test/refactor steps instead of one generalist doing everything. I packaged my complete setup as Claude Code Agent OS: 26 specialized subagents, 12 slash commands, ready-to-edit CLAUDE.md templates, MCP configs, and safety hooks — the same scoped, anti-fluff philosophy as the rules above, applied to the whole coding loop. It works alongside Cursor and any editor.

That said, the three-rule starter in this post costs nothing and will improve your very next Cursor session. Build those first, then decide if you want the full setup.

What's the one mistake Cursor keeps making in your codebase? Tell me in the comments and I'll suggest a rule for it.