You are a senior TypeScript engineer. Apply these rules without exception:
1. Never use `any`. Prefer `unknown` + a narrowing check.
2. Never use `@ts-ignore` to silence errors. Fix the underlying type.
3. Functions exposed as a public API must have explicit return types.
4. Use discriminated unions instead of optional fields when modeling state ("loading | success | error", not "{ data?, error? }").
5. Async functions return `Promise<Result<T, E>>` style when failure modes matter; throw only for programmer errors.
6. Don't reach into internal modules. If you need a type, export it from the module that owns it.
7. Tests use the real type — no `as any` casts in tests either.
放进 .cursorrules 或 Cursor 的 AI 规则设置,立刻减少 any/ignore 的拉低质量代码。
现代 React (2026) — Server Components 优先
CursorReact
When generating React code, follow these:
1. Default to Server Components. Add `'use client'` only when the component needs state, effects, browser APIs, or event handlers.
2. Data fetching happens in Server Components or route handlers, never via useEffect for initial load.
3. Use the React Compiler defaults — do NOT add `useMemo` / `useCallback` unless profiling shows a regression.
4. Prefer Suspense + ErrorBoundary over loading/error state in components.
5. For client state: useState for trivial, Zustand for cross-component. No Redux unless instructed.
6. Forms: react-hook-form + zod. Never controlled inputs for forms with more than 3 fields.
7. Server actions for mutations. Form posts to API routes only when actions don't fit.
8. No `React.FC`. Type props inline or with a named interface.
Generate code that respects Next.js App Router conventions:
1. Pages are server-rendered by default. Client components must be at leaf level — don't make a whole page client to use one useState.
2. `generateMetadata` lives in page.tsx or layout.tsx (server file). Read from a typed helper, not duplicated literals.
3. Route handlers in /api use Web Request/Response, not next/api. NextResponse.json for ergonomic returns.
4. Cookies / headers via 'next/headers' — async functions only.
5. ISR / revalidation via `revalidatePath` or `revalidateTag`, not deprecated unstable_cache APIs.
6. For loading UI use loading.tsx convention; for errors use error.tsx. Don't manually wrap with Suspense unless needed.
7. Server actions for mutations; pass through zod validation.
When writing Go code, follow these:
1. Errors are values. Return them. Wrap with %w when adding context: `fmt.Errorf("loading user %s: %w", id, err)`.
2. context.Context is always the first parameter for any IO or potentially long-running function.
3. No panics in library code. Panics belong to "this can never happen" assertions only.
4. Goroutines have lifetimes. Pass a context; respect cancellation. Never `go fn()` without thinking about who waits.
5. Interfaces are accept-the-interface, return-the-concrete. Define small interfaces at the consumer, not the provider.
6. Avoid generic abstractions until you have three concrete examples.
7. Tests use table-driven style with t.Run subtests for each case. Errors include the input that failed.
8. Embedding for "is-a" only; composition (named fields) for "has-a".
9. Don't use init() — make initialization explicit.
把 Go reviewer 默认要求成文化。放进 .windsurfrules。
现代 Python (3.12+) 规范
WindsurfPython
When writing Python, apply:
1. Type hints everywhere. Use the modern syntax: `list[str]` not `List[str]`, `X | None` not `Optional[X]`.
2. Prefer dataclasses or Pydantic models over dicts for structured data.
3. Use `pathlib.Path`, not `os.path`. Use `subprocess.run`, not shell strings.
4. Async functions need an async story end-to-end — no `asyncio.run` deep in business code.
5. Logging via the stdlib logging module with structured fields, not print().
6. f-strings everywhere, never `%` formatting or `.format()`.
7. Tests use pytest + pytest fixtures. Parametrize tables instead of for-loops.
8. Imports: stdlib, third-party, local — separated by blank lines. No wildcard imports.
9. Dependencies: pin in pyproject.toml; lock with uv or poetry.lock.
把 Windsurf 拉到 Python 3.12+ 现代写法,告别老式写法。
改之前先调查
Claude CodeGeneral
Before modifying code, follow this order:
1. Read the file you're about to change.
2. Grep for the function, class or symbol you're touching to understand callers.
3. If the change spans more than 2 files, write a quick plan (TodoWrite) before editing.
4. Verify your assumptions with concrete file:line citations. Don't say "I think it's in src/utils" — open it.
5. After editing, run type-check / lint / relevant tests. Don't claim success without running them.
6. If something fails, fix the root cause. Don't paper over with try/except or `as any`.
Never delete files, run `git reset --hard`, or force-push without explicit confirmation. Ask first.
保存为 Claude Code memory 或放进 CLAUDE.md。能阻止很多"代理盲改"的事故。
测试编写约定
Claude CodeGeneral
When writing or modifying tests:
1. Test the public API, not internals. If you need to test a private function, that's a smell — either extract it or test through the public surface.
2. One assert-per-test ideal. Multiple asserts only when they describe one behavior together.
3. Test names describe behavior: "returns null when input is empty", not "test_get_user_1".
4. No mocking what you don't own. If you're mocking your own ORM, write an integration test instead.
5. Snapshot tests for stable serialized outputs only. Never for changing UI markup — they rot.
6. Tests are deterministic. No `Date.now()`, `Math.random()`, network calls, or `setTimeout` without proper mocking.
7. The test file lives next to the implementation file (component.tsx ↔ component.test.tsx). Not in a far-away tests/ folder.
阻止生成的测试变成明天的维护噩梦。
提交与 PR 规范
Claude CodeGeneral
When asked to commit or open a PR:
1. Run `git status` and `git diff` first. Read the diff.
2. Group related changes into one commit; separate unrelated changes into separate commits. Never mix a refactor with a bug fix.
3. Commit message: first line is imperative ("Add X", "Fix Y"), <72 chars. Body explains *why*, not *what* — the diff shows what.
4. Never use `git add -A` or `git add .` — name files. Stops .env / secrets leaking into commits.
5. Never `--no-verify`, never `--force` without explicit instruction. If hooks fail, fix the issue.
6. PR description includes: what changed, why, how to test, screenshots if UI.
7. Do NOT push unless explicitly told to push.
放进 CLAUDE.md 或 Claude Code 项目记忆。
增量、可审查的修改
ClineGeneral
Work in small, reviewable steps:
1. Never produce a 500-line diff when 50 lines × 10 steps would do.
2. After each cohesive change, run the relevant test or type-check and report the result.
3. If a step fails, stop and ask before retrying. Do not silently retry with a slightly different approach.
4. Prefer "preview the change, then apply" — show the diff before writing files when the change is non-trivial.
5. State your assumptions explicitly. ("I'm assuming X, please confirm.")
6. When the user pushes back on an approach, do not double down. Adjust.
抑制 Cline 一口气产生巨大 diff 的倾向。
严守作用域
AiderGeneral
Stay strictly inside the requested scope:
1. If asked to fix one bug, fix that bug. Don't refactor surrounding code.
2. If asked to add one feature, add only that feature. Don't add "while I was here" improvements.
3. Don't reformat files you're editing. Whitespace-only diffs make code review hell.
4. Don't add dependencies without explicit confirmation. Reuse what's already in package.json / pyproject.toml.
5. Don't move files around. Don't rename symbols. Don't change unrelated tests.
6. Surface improvement suggestions as a list at the end of your reply, separate from the diff. Never silently apply them.
Aider 容易做"顺手"重构。这条规则阻止它。
现代 Swift (6.0+) 规范
CursorSwift
When generating Swift code:
1. Default to async/await. No completion-handler callbacks except when wrapping legacy APIs (use withCheckedThrowingContinuation).
2. UI / view-model classes are @MainActor unless there's a measured reason not to.
3. Mutable shared state lives in an actor, never in a plain class.
4. Honor Sendable strictly — don't disable the warning.
5. Prefer struct over class. Reach for class only when you need reference identity or inheritance.
6. Use Swift 6 macros (@Observable, @ObservableObject is legacy now).
7. Force-unwrap (`!`) is forbidden except in tests; use `guard` + fail explicitly.
8. SwiftUI: small composable views; @State / @Bindable / @Environment instead of monolithic @StateObject.
9. Tests with XCTest async APIs, not DispatchSemaphore wait.
把 Cursor 从仍默认的 Swift 4 时代写法拉到现代。
现代 Flutter 规范
CursorFlutter
When writing Flutter code:
1. State management: default to Riverpod 3 with @riverpod codegen. Don't use legacy provider package.
2. Widgets are const wherever possible — annotate explicitly.
3. Use Dart 3 patterns: sealed classes for state unions, switch expressions for exhaustive checks, records for tuples.
4. No setState in screens that have non-trivial logic — use a Notifier or ChangeNotifier.
5. Async UI states are AsyncValue<T> — handle loading/error/data explicitly.
6. Theme via ThemeData + Material 3. No hardcoded colors in widgets.
7. Tests: widget tests for UI, plain Dart tests for logic. Don't mix layers.
8. flutter_lints + custom_lint rules enforced; do not suppress without a comment explaining why.
阻止 Cursor 生成老式 StatefulWidget + Provider 写法。
现代 Rust 规范
CursorRust
When writing Rust code:
1. Use Result<T, E> + ? for fallible operations. Never unwrap() outside tests / main.rs prototypes.
2. Prefer enums + match for state. Avoid bool fields when an enum names the states clearly.
3. Borrow over clone. If you reach for .clone(), pause and consider lifetimes first.
4. Async: use tokio (most ecosystems). Mark async functions explicitly; don't hide them inside blocking calls.
5. Errors: thiserror for libraries, anyhow for binaries. Don't roll your own Error type per module.
6. Modules: small, focused; use mod.rs only when there's actual shared state.
7. Tests next to code: `#[cfg(test)] mod tests { ... }` inside the file under test.
8. cargo clippy --all-targets -- -D warnings is a passing-CI requirement; do not suppress warnings without explanation.
放进 Rust 项目的 .cursorrules,抑制 LLM 到处 .unwrap() 的倾向。
Vue 3 + Composition API + script setup
CursorGeneral
When writing Vue code:
1. Use `<script setup lang="ts">` exclusively. No Options API in new components.
2. Composition API: reactive() for objects, ref() for primitives. Don't mix patterns in the same component.
3. State management: Pinia. Avoid Vuex in new code.
4. Props are typed via `defineProps<{...}>()`. No runtime prop type definitions.
5. Emits are typed via `defineEmits<{...}>()`.
6. Composables (`useFoo()`) for any reusable logic. Don't inline complex state in component setup blocks.
7. Async data: VueUse `useAsyncState` or TanStack Query (Vue). Don't write your own loading/error tracking.
8. CSS: scoped styles by default; CSS Modules for shared classes; avoid global styles except for resets.
9. Vue Router 4: use `<script setup>` style of useRouter() / useRoute(); avoid mixins.
When writing Svelte 5 code:
1. Use runes ($state, $derived, $effect, $props) — the Svelte 5 standard. Do not use the legacy `let` reactivity from Svelte 4.
2. Props: `let { foo, bar } = $props()` — destructure once at the top of <script>.
3. Derived values: $derived, not $: assignments. Cleaner and more predictable.
4. Side effects: $effect, with explicit cleanup return. Don't use onMount + manual unsubscribe.
5. Stores: $state in shared modules; old writable() stores still work but $state is preferred for new code.
6. Snippets ({#snippet} / {@render}) replace slots for new component APIs.
7. SvelteKit: load() returns typed data; use server load when data is private, universal when it should hydrate.
8. CSS: scoped by default; use :global() sparingly.
多数模型仍输出 Svelte 4 写法。这条规则强制使用 Svelte 5 习惯。
现代 Kotlin 规范
CursorGeneral
When writing Kotlin code:
1. Prefer immutable data: `val` over `var`, `List<T>` over `MutableList<T>` for public APIs.
2. Use data classes for value-holding types; sealed classes / sealed interfaces for state hierarchies.
3. Coroutines: structured concurrency via coroutineScope, supervisorScope, viewModelScope. No GlobalScope.
4. Flow over LiveData / RxJava in new code.
5. Null safety: leverage smart casts; avoid !! except in genuinely impossible-null cases.
6. Extension functions: keep them in topic-named files (StringExt.kt); avoid grab-bag Util classes.
7. Tests: kotest or JUnit5 + kotlin.test. Use coroutine test rules for suspend tests.
8. Android: ViewModel + StateFlow; Jetpack Compose with @Composable functions; avoid AppCompatActivity bloat in new screens.
把 Cursor 从 Java 味的 Kotlin 拉到地道现代 Kotlin。
Tailwind CSS — 可读类名规范
CursorReact
When writing Tailwind code:
1. Group utility classes logically: layout → spacing → typography → color → state. Avoid random ordering.
2. Extract to a component when the same long class string appears 3+ times. Don't @apply inside CSS — extract a component instead.
3. Use design tokens from theme.extend (theme('colors.primary')) over arbitrary values (text-[#00aaff]) for brand consistency.
4. Use semantic variants (`data-[state=open]`, `peer-checked`) over JS class toggling when possible.
5. Responsive: mobile-first. Use sm:/md:/lg: prefixes additively, not replacements.
6. Dark mode: prefer dark: variant + theme tokens that have both light and dark values. Avoid conditionally rendering different markup.
7. Never use !important (`!` prefix) except in the rare CSS specificity override case — document why with a comment.
8. clsx or class-variance-authority for conditional classes; not template literal concatenation.
阻止 Tailwind 变成一面不可读的工具类墙。
Git 工作流规范
Claude CodeGeneral
Git rules:
1. Branch names: kebab-case, prefix with type (`feat/login-flow`, `fix/null-pointer`, `chore/upgrade-react`).
2. Commits: imperative mood subject ("Add user login"), ≤72 chars first line; body for "why".
3. One logical change per commit. Don't bundle a refactor with a bug fix.
4. Never `git push --force` to a shared branch. Use `--force-with-lease` if rewriting your own branch.
5. Rebase your branch onto main before opening a PR (`git fetch origin && git rebase origin/main`).
6. Resolve merge conflicts explicitly. Don't accept either side wholesale without reading.
7. Squash merge for small features (1-5 commits); rebase merge for cleanly-staged longer features.
8. Never commit secrets, .env, generated dist/build folders, or large binaries.
9. `git status` and `git diff` before every commit — read what you're about to ship.
阻止 Claude Code 犯 git 事故——错误的 push、squash 了别人的提交。
代码审查清单
Claude CodeGeneral
When reviewing code (yours or others'), check in this order:
1. **Correctness first.** Does it actually do what the PR says? Trace a key code path manually.
2. **Failure modes.** What happens when the network is down / the user is offline / the file is empty / the input is huge?
3. **Tests.** Are there tests for the happy path *and* at least one edge case? Tests that just assert the function exists don't count.
4. **Naming.** Could a junior reading this file in 6 months figure out what `processData()` does?
5. **Boundaries.** Are inputs validated at system boundaries (HTTP, file I/O, IPC)? Are outputs to other systems documented?
6. **Performance.** Any obvious N+1 queries, O(n^2) loops over real data, or sync I/O in async code?
7. **Security.** Any user input concatenated into SQL / HTML / shell? Secrets in logs? Auth bypass possibilities?
8. **Style.** Last priority — leave it to the formatter and linter.
Don't ask for changes you wouldn't make yourself. Don't approve "looks good" without doing the above.
需要 Claude Code 做严肃 code review 时放进 CLAUDE.md。
系统化调试方法
GeneralGeneral
When debugging an unexpected behavior, follow this order:
1. **Reproduce reliably.** If you can't reproduce, you're guessing. Pin down the exact steps.
2. **Read the actual error.** Not the summary — the full stack trace. Most "weird" errors are explicit about the problem.
3. **State your hypothesis explicitly.** "I think it's because X." Now design the cheapest experiment to falsify it.
4. **Verify your assumptions.** Print/log/inspect the values you think are true. The bug is usually where you didn't check.
5. **One change at a time.** Don't change three things and rerun — you can't tell which fixed it (or which made it worse).
6. **Bisect the change set.** If "it worked an hour ago," use git bisect or commit-by-commit revert.
7. **Look for the root cause, not just the symptom.** If a null pointer exception fires, *why* was it null? Patching the null check is a workaround, not a fix.
8. **Write a regression test.** Anything that broke once will break again.
通用调试方法——任何语言或工具都适用。
禁止偷偷加依赖
ClineGeneral
Dependency discipline:
1. Never add a new package, library, or framework without explicit user confirmation.
2. Before suggesting a dependency, check what's already installed (package.json / requirements.txt / Cargo.toml). Reuse > add.
3. If the user agrees to a new dependency, justify it briefly: "we don't have an HTTP client, axios is the standard choice" — not just "I'll install X."
4. Pin major versions; let minor/patch float (^1.2.3 in npm).
5. Prefer maintained, popular options over experimental packages. "Last commit 2019" is a no.
6. Never add a package to circumvent a build/lint error. Fix the underlying issue.
7. Document why a dependency was added in the commit message.
阻止代理偷偷加依赖——老项目维护痛苦的元凶之一。
有意识管理上下文窗口
Claude CodeGeneral
Context window management:
1. Don't read the entire codebase upfront. Grep / glob for what you need first, then read selectively.
2. After a major refactor or many tool calls, summarize what's been done in 2-3 sentences before continuing — it grounds the next steps.
3. If the conversation hits 80%+ of the context limit, save state to a file (NOTES.md, plan.md) and reference it instead of re-reading.
4. Delete or compact tool outputs that are no longer relevant (large file contents you've already analyzed).
5. Avoid pasting entire log files. Filter to the relevant lines first (grep ERROR / grep filename).
6. For multi-step tasks, write the plan as TodoWrite tasks first, then execute. Tasks survive context compaction better than chat history.
帮 Claude Code 在长会话中保持连贯,避免"忘记"之前做了什么。
注释规范:少写、写好
GeneralGeneral
Comment discipline:
1. Don't comment what the code does. Good naming + reading the code is enough.
2. Comment why: a constraint, a workaround for a bug, a non-obvious design decision.
3. Reference an issue tracker or commit hash when explaining a workaround ("workaround for #1234, fix when upstream merges PR").
4. Update comments when the code changes. A wrong comment is worse than no comment.
5. Avoid TODO without an owner or date. `// TODO(@alice, 2026-03): remove after migration` > `// TODO: fix later`.
6. Don't keep commented-out code. Version control is your archive.
7. For public APIs, document the contract (params, returns, errors thrown, side effects) — not the implementation.
8. JSDoc / docstrings only for exported symbols, not every internal helper.