dotnet-agent-kit / rules
Cursor rule853 starsChanged yesterdayMITView on GitHub
Auto-generated from the .claude/rules/ directory in dotnet-agent-kit. Do not edit this file directly. Update the rule files in .claude/rules/ and run python3 .github/scripts/generate_cursor_rules.py.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- codewithmukesh/dotnet-claude-kitword for word, first seen Nov 28, 2026
Other versions1 project uses a version of this.
Word for word · 1
- codewithmukesh/dotnet-claude-kit★ 853100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
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 4,263 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 repository38 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .codex/AGENTS.mdAGENTS.md
- .opencode/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- architecture-advisorSkill
- aspireSkill
- authenticationSkill
- build-fixSkill
- cachingSkill
- ci-cdSkill
- code-reviewSkill
- configurationSkill
- console-cliSkill
- dependency-injectionSkill
- desktop-mvvmSkill
- de-sloppifySkill
- dockerSkill
- doctorSkill
- dotnet-initSkill
- ef-coreSkill
- error-handlingSkill
- instinct-systemSkill
- loggingSkill
- messagingSkill
- migrateSkill
- minimal-apiSkill
- modern-csharpSkill
- modular-slicesSkill
- native-aotSkill
- openapiSkill
- opentelemetrySkill
- resilienceSkill
- scaffoldSkill
- specSkill
- tddSkill
- testingSkill
- verifySkill
- wrap-upSkill
The file
We split this dotnet-rules.md into the rules it gives an agent
5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Very specific: line 16
Modules meet only through
<Module>.Contracts: Never reference another module's implementation project or its tables. - Very specific: line 17
internalby default inside a module: Only the module class and request/response records are public. - Very specific: line 125
Never
new HttpClient()per call: Use IHttpClientFactory or typed clients. - Very specific: line 147
Never put secrets in source, appsettings files or commits: Use dotnet user-secrets locally and Key Vault or environment variables when …
- Distinctive: line 172
Never mock code you own: Use the real implementation or a small fake.
≈ “Common” is an estimate: at least 1 in 5 of the 7,111 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-agent-kit. Do not edit this file directly. Update the rule files in.claude/rules/and runpython3 .github/scripts/generate_cursor_rules.py.
Architecture Rules
- Recommend modular slices first for business applications (ADR-008), then confirm with the architecture-advisor skill. VSA, Clean Architecture and DDD stay options when the advisor's questions point to them. An existing codebase keeps its own conventions.
- Feature folders, not layer folders.
Features/PlaceOrder/holds the endpoint, handler, request, response and validator, so a change touches one folder. - One
IEndpointper feature, found by discovery. Hosts callbuilder.AddModule<TModule>()andapp.MapModules()(orapp.MapEndpoints()in a single project). Never map endpoints inline in Program.cs or add per-resourceMapGroup/Map*Endpoints()calls there; they drift and grow without bound. - Handlers are plain classes behind a marker
IHandler; no mediator by default. A direct call is easier to read, debug and test. - No repository or unit-of-work over EF Core.
DbContextalready is both; a wrapper hides change tracking,ExecuteUpdateAsyncand compiled queries. - Modules meet only through
<Module>.Contracts. Never reference another module's implementation project or its tables. Cross-module writes go through integration events on the module's outbox. internalby default inside a module. Only the module class and request/response records are public; architecture tests enforce it.- Dependencies point inward. Domain depends on nothing; never let it reference infrastructure.
- Shared projects hold contracts and plumbing, never business rules. Business logic in a shared project is hidden coupling.
// DO: one discovered endpoint per feature, DbContext used directly by the handler
internal sealed class PlaceOrderEndpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder endpoints) =>
endpoints.MapPost("/", (PlaceOrderRequest request, PlaceOrderHandler handler, CancellationToken ct) =>
handler.HandleAsync(request, ct)).RequirePermission(OrdersPermissions.Manage);
}
// DON'T
app.MapGroup("/api/orders").MapOrderEndpoints();
public interface IRepository<T> { Task<T?> GetByIdAsync(Guid id); }C# Coding Style
- File-scoped namespaces, one type per file, file name = type name. Less nesting, and a type is always where its name says.
- Primary constructors for DI; no
_field = fieldassignments. The parameter is the field. - Records for DTOs, requests, responses and value objects. Immutability and value equality for free.
sealedunless designed for inheritance;internalunless something outside the project needs it. Smaller API surface, and the JIT can devirtualize.- Collection expressions (
[1, 2, 3]) overnew List<T> { }/Array.Empty<T>(). Shorter and the compiler picks the best construction. - Switch expressions and
ispatterns over if-else chains on type or value. Exhaustiveness checks catch missed cases. Asyncsuffix on every method returningTask/ValueTask. Makes a missingawaitvisible at the call site.varwhen the right-hand side shows the type; explicit type when it doesn't.- Never block on async (
.Result,.Wait(),GetAwaiter().GetResult()). It starves the thread pool and deadlocks.
// DO
internal sealed class OrderService(AppDbContext db, TimeProvider clock)
{
public async Task<Order?> GetAsync(Guid id, CancellationToken ct) =>
await db.Orders.FindAsync([id], ct);
}
// DON'T
public class OrderService
{
private readonly AppDbContext _db;
public OrderService(AppDbContext db) { _db = db; }
public Order Get(Guid id) => _db.Orders.FindAsync(id).Result;
}Error Handling Rules
- Expected failures are return values. HTTP handlers return a
TypedResultsunion such asResults<Created<OrderResponse>, ProblemHttpResult>; the compiler checks every branch and OpenAPI documents each status code. - Never throw for not found, conflict or a broken business rule. Return
Problems.NotFound(),Problems.Conflict(code, detail)orProblems.RuleBroken(code, detail). Exceptions hide control flow. - Use
Result<T>only outside HTTP handlers (shared domain services, background jobs, libraries) where callers can't consume HTTP result types. - Every error response is ProblemDetails (RFC 9457) with a stable
codeextension:<module>.<reason>in kebab case for business errors (orders.already-cancelled), a general code otherwise (not-found,validation-failed). Clients switch on codes; detail text changes. - Every web host has
app.UseExceptionHandler()+AddProblemDetails(). Without it, unhandled exceptions leak stack traces. - Catch
Exceptiononly at the outermost boundary; never catch-and-rethrow without adding context; never leave acatchempty. Broad or empty catches swallow bugs. - Validate at the edges (request bodies, external responses, config), not again inside internal methods.
// DO
internal sealed class CancelOrderHandler(OrdersDbContext db) : IHandler
{
public async Task<Results<NoContent, ProblemHttpResult>> HandleAsync(Guid id, CancellationToken ct)
{
var order = await db.Orders.FindAsync([id], ct);
if (order is null) return Problems.NotFound();
if (order.IsCancelled) return Problems.Conflict("orders.already-cancelled", "Order is already cancelled.");
order.Cancel();
await db.SaveChangesAsync(ct);
return TypedResults.NoContent();
}
}
// DON'T
if (order is null) throw new NotFoundException($"Order {id} not found");Package Management Rules
- Never write a package version from memory. Training data holds old 8.x/9.x versions. Resolve versions with
dotnet add packageordotnet package search <name>. - Match
Microsoft.*,System.*and EF Core majors to the target framework, as an exact version (never a floating10.*). Onnet10.0, pin to the latest 10.x: plaindotnet add packagenow resolves 11.x, which requiresnet11.0and fails restore. Third-party packages: latest stable that supports your TFM. - Multi-project solutions use
Directory.Packages.propswithManagePackageVersionsCentrally;.csprojfiles then carry noVersion=. One place to change, no drift. - Never downgrade a package or switch to a preview without a stated reason.
- Check licences before adding: MediatR v13+, AutoMapper v15+, MassTransit v9+ and FluentAssertions v8+ are commercial or dual-licensed.
# DO: net10.0 project, keep EF Core on 10.x with an exact version
dotnet package search Microsoft.EntityFrameworkCore --exact-match # note the newest 10.0.x
dotnet add package Microsoft.EntityFrameworkCore --version <newest 10.0.x>
dotnet add package Serilog.AspNetCore # third-party: latest stable
# DON'T
dotnet add package Microsoft.EntityFrameworkCore # on net10.0 this pulls 11.x
dotnet add package Microsoft.EntityFrameworkCore --version "10.0.*" # floating, non-reproducible
dotnet add package Serilog.AspNetCore --version 8.0.0 # version from memoryPerformance Rules
- Pass
CancellationTokenthrough every async call. A dropped token keeps cancelled requests burning the database and thread pool. - Inject
TimeProvider; never callDateTime.Now/DateTime.UtcNowdirectly. Time becomes testable and consistent. - Never
new HttpClient()per call. UseIHttpClientFactoryor typed clients; direct instances exhaust sockets and ignore DNS changes. HybridCacheoverIMemoryCache/IDistributedCache. Stampede protection, L1 + L2 and tag invalidation come built in.- Read-only queries project with
Selector useAsNoTracking(); set-based changes useExecuteUpdateAsync/ExecuteDeleteAsync. Tracking and load-then-save cost memory and round trips. - Never query inside a loop (N+1). Load what you need in one query.
- Measure before optimizing hot paths (BenchmarkDotNet,
dotnet-counters); then reach for compiled queries,ValueTaskor pooled buffers.
// DO
public Task<OrderSummary?> GetAsync(Guid id, CancellationToken ct) =>
db.Orders.Where(o => o.Id == id)
.Select(o => new OrderSummary(o.Id, o.Total))
.FirstOrDefaultAsync(ct);
// DON'T
var order = await db.Orders.Include(o => o.Lines).FirstOrDefaultAsync(o => o.Id == id); // no token, tracked
order.CreatedAt = DateTime.UtcNow;Security Rules
- Never put secrets in source, appsettings files or commits. Use
dotnet user-secretslocally and Key Vault or environment variables when deployed. Git history keeps secrets forever. - Never build SQL by string concatenation. EF Core LINQ and
SqlQuery($"...")interpolation are parameterized;ExecuteSqlRawwith+is not. - Every endpoint states its auth explicitly (
RequirePermission(...),RequireAuthorization(...)orAllowAnonymous()). Relying on a global default hides who can call what. - HTTPS everywhere:
UseHsts()+UseHttpsRedirection()in production. - CORS lists explicit origins; never
AllowAnyOrigin()in production. - Never log PII or tokens at Information or above. Log aggregators are widely readable; use IDs instead of emails and names.
- Use the Data Protection API for encrypting data at rest; never write your own crypto.
- Validate all external input at the boundary (FluentValidation or built-in validation) before it reaches handlers.
// DO
var conn = builder.Configuration.GetConnectionString("Default");
var orders = await db.Database.SqlQuery<Order>($"SELECT * FROM orders WHERE id = {id}").ToListAsync(ct);
// DON'T
var conn = "Server=prod;Password=hunter2";
db.Database.ExecuteSqlRaw("SELECT * FROM orders WHERE id = '" + id + "'");Testing Rules
- Integration tests first:
WebApplicationFactory+ Testcontainers against the real database engine. They catch serialization, middleware, DI and query bugs that unit tests miss. - Never use
UseInMemoryDatabaseor SQLite-in-memory to stand in for the real provider. No constraints, transactions or real SQL translation. - Never mock code you own. Use the real implementation or a small fake; mocks couple tests to internals. Mock only third-party boundaries.
- Share expensive fixtures (containers, factories) with
IClassFixture<T>/ICollectionFixture<T>; never start a container per test. - Assert observable behaviour (HTTP response, database state, published event), never which internal methods were called.
- Name tests
MethodName_Scenario_ExpectedResult; Arrange / Act / Assert separated by blank lines; one behaviour per test. - Never disable, skip or weaken a failing test to get green. Fix the code or ask.
// DO (xUnit v3: IAsyncLifetime uses ValueTask)
public sealed class DatabaseFixture : IAsyncLifetime
{
private readonly PostgreSqlContainer container = new PostgreSqlBuilder("postgres:17").Build();
public string ConnectionString => container.GetConnectionString();
public async ValueTask InitializeAsync() => await container.StartAsync();
public ValueTask DisposeAsync() => container.DisposeAsync();
}
// DON'T
options.UseInMemoryDatabase("TestDb");
[Fact(Skip = "flaky")]Workflow Rules
- Use the cwm-roslyn-navigator MCP tools before reading files (
find_symbol,find_references,get_symbol_detail,get_project_graph). A symbol lookup costs a fraction of a 500-line file. - Check
get_project_graphbefore adding projects or project references. Prevents cycles and modules reaching into each other. - Load the matching skill before starting a task; check AGENTS.md if unsure which. Skills carry the patterns and anti-patterns.
- Never call work done without proof:
dotnet buildanddotnet testgreen, or/verify. Pipe test output throughhooks/post-test-analyze.shwhen available. - Conventional commits (
feat:,fix:,refactor:,test:,docs:,chore:), one logical change per commit, tests in the same commit as the code. The body explains why. - Never skip hooks (
--no-verify) and never force-push main. Fix what the hook reports; force-push rewrites shared history. - Accept post-edit formatter changes; never revert them.
- Model tiers in configs are aliases (
fable,opus,sonnet,haiku), never pinned IDs. Sonnet for routine edits and tests, Opus for design reviews, Fable for high-stakes architecture.
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.

