dotnet-claude-kit / rules
Cursor rule750 starsChanged 4 months agoMITView on GitHub
Auto-generated from the .claude/rules/ directory in dotnet-claude-kit. Do not edit this file directly. Update the individual rule files in .claude/rules/ and regenerate.
- Reads credentials
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository52 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/rules/agents.mdAGENTS.md
- .codex/AGENTS.mdAGENTS.md
- .opencode/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- api-versioningSkill
- arch-checkSkill
- architecture-advisorSkill
- aspireSkill
- authenticationSkill
- build-fixSkill
- cachingSkill
- checkpointSkill
- ci-cdSkill
- clean-architectureSkill
- code-reviewSkill
- configurationSkill
- container-publishSkill
- convention-learnerSkill
- dddSkill
- dependency-injectionSkill
- de-sloppifySkill
- dockerSkill
- dotnet-initSkill
- ef-coreSkill
- error-handlingSkill
- health-checkSkill
- httpclient-factorySkill
- instinct-systemSkill
- loggingSkill
- messagingSkill
- migrateSkill
- minimal-apiSkill
- modern-csharpSkill
- openapiSkill
- opentelemetrySkill
- outdatedSkill
- planSkill
- project-setupSkill
- project-structureSkill
- resilienceSkill
- scaffoldSkill
- scalarSkill
- security-scanSkill
- serilogSkill
- specSkill
- tddSkill
- testingSkill
- verifySkill
- vertical-sliceSkill
- workflow-masterySkill
- wrap-upSkill
The file
We split this dotnet-rules.md into the rules it gives an agent
12 rules. About 0 are common, 7 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈7
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 72
Module boundaries enforced through project references: Use integration events or shared contracts for cross-module communication.
- Very specific: line 79
Never hardcode secrets in source code: Use dotnet user-secrets for local dev, Azure Key Vault or env vars for deployed environments.
- Distinctive: line 81
Validate all external input at system boundaries: Use FluentValidation or built-in validation attributes.
- Distinctive: line 82
Parameterized queries always: Never string-concatenate SQL.
- Distinctive: line 93
Use Data Protection API for encrypting data at rest: Never roll your own encryption.
- Distinctive: line 118
No mocking frameworks for things you own: Use real or test implementations.
- Distinctive: line 157
Do not use try-catch for flow control: If you can predict the failure, return a Result.
- Very specific: line 191
MCP tools before file reading: Use find_symbol, find_references, get_public_api, get_type_hierarchy before reading source files.
- Very specific: line 194
Do not read entire files to find a single method: Use find_symbol first.
- Distinctive: line 201
Load relevant skills before starting work: Check AGENTS.md skill maps.
- Very specific: line 210
Pipe test output through
hooks/post-test-analyze.sh: when running test workflows, and act on its summary. - Very specific: line 231
If unsure about the latest version, suggest dotnet package search <name> or checking NuGet.org.
≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
.NET Development Rules (Cursor IDE)
Auto-generated from the
.claude/rules/directory in dotnet-claude-kit. Do not edit this file directly. Update the individual rule files in.claude/rules/and regenerate.
1. C# Coding Style
File Organization
- File-scoped namespaces always. Block-scoped namespaces waste indentation for zero benefit.
- One type per file. File name must match the type name exactly.
- Order members: constants, fields, constructors, properties, public methods, private methods.
Type Declarations
- Primary constructors for DI injection. Eliminates boilerplate field assignments.
// DO
public sealed class OrderService(IDbContext db, TimeProvider clock) { }
// DON'T
public class OrderService
{
private readonly IDbContext _db;
public OrderService(IDbContext db) { _db = db; }
}- Records for DTOs and value objects. Immutability, value equality, and
withexpressions for free.
public sealed record CreateOrderRequest(string ProductId, int Quantity);
public sealed record Money(decimal Amount, string Currency);sealedon classes not designed for inheritance. Enables JIT devirtualization and communicates intent.internalby default,publiconly when needed. Minimize the public API surface.
Expressions and Patterns
- Collection expressions over constructor calls.
List<int> ids = [1, 2, 3]; // DO
var ids = new List<int> { 1, 2, 3 }; // DON'T- Pattern matching over if-else chains. Switch expressions and
ispatterns are more readable and exhaustiveness-checked. varfor obvious types, explicit types when clarity matters.- Async suffix on all async methods (
GetOrderAsync, notGetOrder). - PascalCase for public members, types, namespaces, methods. camelCase for local variables and parameters.
- No
_prefix on private fields when using primary constructors.
2. Architecture
- Never assume an architecture -- use the architecture-advisor skill. Ask about team size, domain complexity, and deployment model before recommending Clean Architecture, VSA, DDD, or Modular Monolith.
- No repository pattern over EF Core.
DbContextis already a Unit of Work + Repository. Wrapping it adds indirection with no value.
// DO -- inject DbContext directly
public sealed class OrderService(AppDbContext db)
{
public Task<Order?> GetAsync(Guid id, CancellationToken ct) =>
db.Orders.FindAsync([id], ct).AsTask();
}
// DON'T -- generic repository wrapping EF
public interface IRepository<T> { Task<T?> GetByIdAsync(Guid id); }- Every endpoint group gets its own file implementing
IEndpointGroup. Never define endpoints in Program.cs. Useapp.MapEndpoints()for auto-discovery. Program.cs never changes when adding endpoints. - Feature folders over layer folders. Vertical slices keep related code together, reducing cross-cutting file changes.
- Dependency direction is inward. Domain depends on nothing. Application depends on Domain. Infrastructure depends on Application. Presentation depends on Application. Never reverse.
- Module boundaries enforced through project references. Use integration events or shared contracts for cross-module communication.
- Shared kernel contains only contracts, never business logic. Interfaces, DTOs, and integration events only.
3. Security
- Never hardcode secrets in source code. Use
dotnet user-secretsfor local dev, Azure Key Vault or env vars for deployed environments. - Never commit
.env,appsettings.Development.jsonwith real credentials, orcredentials.json. Add to.gitignore. - Validate all external input at system boundaries. Use FluentValidation or built-in validation attributes.
- Parameterized queries always. Never string-concatenate SQL. EF Core interpolation is parameterized and safe.
// DO (safe)
db.Database.SqlQuery<Order>($"SELECT * FROM Orders WHERE Id = {id}");
// DON'T (SQL injection)
db.Database.ExecuteSqlRaw("SELECT * FROM Orders WHERE Id = '" + id + "'");- Explicit
[Authorize]or[AllowAnonymous]on every endpoint. Ambiguous auth is a security hole. - HTTPS everywhere. Enforce HSTS in production, redirect HTTP to HTTPS.
- Use Data Protection API for encrypting data at rest. Never roll your own encryption.
- CORS: explicit origins only, never wildcard in production.
- Do not log PII at Information level or below. Production log aggregators are broadly accessible.
4. Testing
- Integration tests first.
WebApplicationFactory+ Testcontainers to test real HTTP pipelines against real databases. - No in-memory database for testing.
UseInMemoryDatabasehas different behavior from real providers. Use Testcontainers.
// DO -- real PostgreSQL via Testcontainers
public sealed class DatabaseFixture : IAsyncLifetime
{
private readonly PostgreSqlContainer _container = new PostgreSqlBuilder().Build();
public string ConnectionString => _container.GetConnectionString();
public Task InitializeAsync() => _container.StartAsync();
public Task DisposeAsync() => _container.DisposeAsync().AsTask();
}- AAA pattern with clear separation: Arrange, Act, Assert separated by blank lines.
- One assertion concept per test. Separate behaviors need separate tests.
- Test naming:
MethodName_Scenario_ExpectedResult. Clear, searchable, self-documenting. - Shared fixtures for expensive setup. Database containers, HTTP servers shared via
IClassFixture<T>orICollectionFixture<T>. - No mocking frameworks for things you own. Use real or test implementations. Reserve mocks for third-party boundaries.
- Test behavior, not implementation details. Assert on observable outcomes (HTTP response, database state, published event).
5. Performance
- Always propagate
CancellationTokenthrough the call chain. Dropped tokens mean cancelled requests continue burning resources.
// DO
public Task<Order?> GetOrderAsync(Guid id, CancellationToken ct) =>
db.Orders.FirstOrDefaultAsync(o => o.Id == id, ct);
// DON'T -- token silently ignored
public Task<Order?> GetOrderAsync(Guid id, CancellationToken ct) =>
db.Orders.FirstOrDefaultAsync(o => o.Id == id);- Async all the way. No
.Resultor.Wait(). Synchronously blocking on async code causes thread pool starvation and deadlocks. TimeProvideroverDateTime.Now/DateTime.UtcNow. Injectable and testable.
// DO
public sealed class AuditService(TimeProvider clock)
{
public DateTimeOffset Now => clock.GetUtcNow();
}IHttpClientFactoryovernew HttpClient(). Direct instantiation causes socket exhaustion under load.HybridCacheoverIMemoryCache/IDistributedCache. Stampede protection, L1+L2, tag-based invalidation out of the box.- Compiled queries for hot-path EF Core queries. Skips expression tree translation on every call.
ArrayPool<T>/MemoryPool<T>for buffer-heavy operations. Avoids GC pressure from frequent large allocations.ValueTask<T>overTask<T>for high-throughput paths that often complete synchronously.
6. Error Handling
- Result pattern for expected failures (not found, validation, conflict). Exceptions are expensive and hide control flow.
- Do not use try-catch for flow control. If you can predict the failure, return a Result.
- Typed error codes in your Result type:
NotFound,Validation,Conflict,Unauthorized. - ProblemDetails (RFC 9457) for all HTTP error responses. Industry standard format.
- No bare
Exceptioncatch unless at the application boundary (middleware/top-level handler). IExceptionHandlermiddleware for unhandled exceptions. Centralizes error logging and ProblemDetails conversion.- No catch-and-rethrow without adding context. Either handle it or let it propagate.
- Validate at system boundaries only. Internal code should trust validated data.
| Scenario | Approach |
| User input invalid | Result with Validation error |
| Entity not found | Result with NotFound error |
| Unhandled crash | IExceptionHandler middleware |
| External API failure | Catch specific exception, return Result |
| Concurrent update | Result with Conflict error |
7. Git Workflow
- Conventional commit prefixes:
feat:,fix:,refactor:,test:,docs:,chore:. - Commit body explains "why", not "what". The diff shows what changed.
- No vague messages like "fix bug" or "update code".
- Branch naming:
feature/,fix/,refactor/prefixes. - Atomic commits. One logical change per commit. Feature and its tests belong together.
- Never force-push to main or master.
- Never skip pre-commit hooks with
--no-verify. - Run verification before creating a PR.
/verifyordotnet build+dotnet test. - Keep PRs focused on a single concern. Split large changes into stacked PRs.
8. Agent & Tool Usage
- MCP tools before file reading. Use
find_symbol,find_references,get_public_api,get_type_hierarchybefore reading source files. get_project_graphbefore structural changes. Understand the dependency tree first.get_diagnosticsafter modifications. Faster and more structured than parsingdotnet buildoutput.- Do not read entire files to find a single method. Use
find_symbolfirst. - Subagents for parallel research and independent tasks. One task per subagent for focused execution.
- Route to specialist agents for domain-specific work (see AGENTS.md routing table).
- Sonnet for routine tasks (formatting, simple refactors, test generation, boilerplate).
- Opus for complex architecture decisions and multi-system analysis.
- Fable for the highest-stakes work (greenfield architecture for long-lived systems, problems that resisted Opus).
- Use model aliases (
fable,opus,sonnet,haiku), never pinned version IDs — aliases track the latest version. - Load relevant skills before starting work. Check AGENTS.md skill maps.
9. Hooks
- Auto-accept post-edit format hooks. They enforce consistent style automatically.
- Do not revert or undo formatting changes applied by hooks.
- Never skip pre-commit hooks. Investigate and fix the root cause when a hook blocks a commit.
- Pipe test output through
hooks/post-test-analyze.shwhen running test workflows, and act on its summary. - Do not interfere with hook configuration. See
hooks/README.mdfor which scripts run automatically vs manually. - Wait for post-scaffold-restore to complete after
.csprojchanges before building.
| Hook | Correct Response |
| Post-edit format | Accept the changes |
| Pre-commit failure | Fix the issue, commit again |
| Post-test-analyze | Read and act on insights |
| Post-scaffold-restore | Wait for completion before building |
10. Package Management
- Never hardcode NuGet package versions from memory. Training data contains outdated 8.x/9.x versions.
- Run
dotnet add package <name>without--versionto pull the latest stable release automatically. - Microsoft. packages for .NET 10 must use 10.x versions* (EF Core, Extensions, ASP.NET Core).
- Use
Directory.Packages.propsfor multi-project solutions to centralize version pins. - Never downgrade a package already in the project unless explicitly asked.
- Prefer release versions over preview/RC unless the project targets preview features.
- If unsure about the latest version, suggest
dotnet package search <name>or checking NuGet.org.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

