agentleFS
codewithmukeshcodewithmukesh/dotnet-agent-kit/.cursor/rules/dotnet-rules.md

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

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
  1. Very specific:

    Modules meet only through <Module>.Contracts: Never reference another module's implementation project or its tables.

    line 16
  2. Very specific:

    internal by default inside a module: Only the module class and request/response records are public.

    line 17
  3. Very specific:

    Never new HttpClient() per call: Use IHttpClientFactory or typed clients.

    line 125
  4. Very specific:

    Never put secrets in source, appsettings files or commits: Use dotnet user-secrets locally and Key Vault or environment variables when …

    line 147
  5. Distinctive:

    Never mock code you own: Use the real implementation or a small fake.

    line 172

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
dotnet-rules.md

.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 run python3 .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 IEndpoint per feature, found by discovery. Hosts call builder.AddModule<TModule>() and app.MapModules() (or app.MapEndpoints() in a single project). Never map endpoints inline in Program.cs or add per-resource MapGroup/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. DbContext already is both; a wrapper hides change tracking, ExecuteUpdateAsync and 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.
  • internal by 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 = field assignments. The parameter is the field.
  • Records for DTOs, requests, responses and value objects. Immutability and value equality for free.
  • sealed unless designed for inheritance; internal unless something outside the project needs it. Smaller API surface, and the JIT can devirtualize.
  • Collection expressions ([1, 2, 3]) over new List<T> { } / Array.Empty<T>(). Shorter and the compiler picks the best construction.
  • Switch expressions and is patterns over if-else chains on type or value. Exhaustiveness checks catch missed cases.
  • Async suffix on every method returning Task/ValueTask. Makes a missing await visible at the call site.
  • var when 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 TypedResults union such as Results<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) or Problems.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 code extension: <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 Exception only at the outermost boundary; never catch-and-rethrow without adding context; never leave a catch empty. 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 package or dotnet package search <name>.
  • Match Microsoft.*, System.* and EF Core majors to the target framework, as an exact version (never a floating 10.*). On net10.0, pin to the latest 10.x: plain dotnet add package now resolves 11.x, which requires net11.0 and fails restore. Third-party packages: latest stable that supports your TFM.
  • Multi-project solutions use Directory.Packages.props with ManagePackageVersionsCentrally; .csproj files then carry no Version=. 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 memory

Performance Rules

  • Pass CancellationToken through every async call. A dropped token keeps cancelled requests burning the database and thread pool.
  • Inject TimeProvider; never call DateTime.Now / DateTime.UtcNow directly. Time becomes testable and consistent.
  • Never new HttpClient() per call. Use IHttpClientFactory or typed clients; direct instances exhaust sockets and ignore DNS changes.
  • HybridCache over IMemoryCache / IDistributedCache. Stampede protection, L1 + L2 and tag invalidation come built in.
  • Read-only queries project with Select or use AsNoTracking(); set-based changes use ExecuteUpdateAsync / 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, ValueTask or 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-secrets locally 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; ExecuteSqlRaw with + is not.
  • Every endpoint states its auth explicitly (RequirePermission(...), RequireAuthorization(...) or AllowAnonymous()). 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 UseInMemoryDatabase or 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_graph before 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 build and dotnet test green, or /verify. Pipe test output through hooks/post-test-analyze.sh when 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.