The operative rules for every contributor and every AI agent, whatever the tool. Every rule in this file is binding; MUST and NEVER mark the ones most often broken. The reasoning, examples and history behind each rule are in the frozen engineering handbook (the pre-2026-09-25 CLAUDE.md); "handbook: X" below names its section. Where this file and the handbook disagree, this file wins.
- Encina is pre-1.0. There is no backward compatibility, no migration support and no existing user. Breaking changes are acceptable and encouraged when they improve the design. The library is renamed after 1.0.
- .NET 10 only (LTS, supported through November 2028); NEVER .NET 9 or older. Use the latest C# 14 features (extension members, the
fieldkeyword, user-defined compound assignment, null-conditional assignment, partial constructors and events, file-based apps). .NET 10 breaking changes are acceptable. Nullable reference types are enabled everywhere. - Design principles: best solution first, never a compromise for compatibility; clean architecture (no legacy, deprecated or obsolete code); pay-for-what-you-use (every feature opt-in); provider-agnostic abstractions (EF Core, Dapper, ADO.NET, MongoDB).
- Before starting work, read the plan for your area in
docs/plans/and continue from where it stopped. The active plans are listed inCLAUDE.md("Active Plans"). The 1.0 scope is SPEC-000. - .NET 10 changes to know:
dotnet new slncreates.slnx;dotnet restoreaudits transitive packages; OpenAPI 3.1 removedOpenApiSchema.Nullable(useJsonSchemaType.Null);WebHostBuilder/IWebHostare obsolete (use minimal hosting);WithOpenApiis deprecated; default container images use Ubuntu.
- MUST script only in PowerShell (
pwsh) or C# 14 file-based apps (dotnet run file.cs, no.csproj). CLI tools (dotnet,git,gh,docker) are invoked directly. - NEVER use
python/python3; bash constructs (for/do/done,if/then/fi, pipes|, subshells$(...)); here-docs (<< 'EOF');sh -c/bash -c; or Unix commands through Git Bash:grep,find,cat,ls,sed,awk,head,tail,wc,sort,xargs,curl,tee,cut,paste,shuf,unzip,basename,xxd,dd. - Equivalents:
grep→Select-String;find→Get-ChildItem -Recurse;cat→Get-Content;head/tail→Select-Object -First/-Last;curl→Invoke-RestMethod;jq→ConvertFrom-Json;kill→Stop-Process;wc -l→(Get-Content f).Count. Full table and the policy's rationale: handbook "Scripting & Tooling Policy".
- NEVER add
[Obsolete], legacy code, compatibility aliases, migration helpers or compatibility layers. If something must change, change it completely. Every line serves a current purpose. - Time comes from
TimeProvider. Production code NEVER readsDateTime.UtcNoworDateTimeOffset.UtcNow; it takesTimeProviderby injection (an optional parameter defaulting toTimeProvider.Systemwhere a default is needed). Every store and repository supports it. (why: #543, #667) - An options class with a password, connection string, token or key MUST mark that property
[JsonIgnore]and overrideToString()so logging, serialization and diagnostics cannot print it. (why: #851) - Database calls MUST be asynchronous with a
CancellationToken(OpenAsync,BeginTransactionAsync,ExecuteNonQueryAsyncand siblings); NEVER the synchronous overloads such asIDbConnection.Open(). (why: Sonar S6966, thread-pool starvation; #794, #897) - Registration completeness: an
AddEncina*method that adds a service, orchestrator or hosted service MUST also register every option type and dependency it resolves, proven by a DI test that builds the provider withValidateOnBuildandValidateScopes. A database store MUST win over an in-memory default in any registration order without overriding the application's own registration. (why: #1260, #1273, #1285, #1289; #1269, #1295) - Errors are NEVER swallowed in background infrastructure: a
LeftfromIEncina.Send/Publishor from a store inside a processor, adapter, orchestrator or job fails that operation (retry, dead-letter or exception per its semantics), never reports success. (why: #1150-#1153, #1184) - Background loops and timers never let an exception escape, and the reason differs per kind. A
System.Threading.TimerorTimeProvider.CreateTimercallback catches its failures and NEVER throws: with the system clock an unhandled exception on the thread-pool thread that runs the callback terminates the process. APeriodicTimerloop catches per iteration (anOperationCanceledExceptionfrom the stopping token still ends the loop, cancellation is not an error and propagates, as in ADR-052): an unhandled exception ends the loop silently or faults the hosted service (in aBackgroundServicethe default behavior then stops the host). The failure is handled by the same rule as any backgroundLeft: the operation fails visibly (retry, dead letter) and is not swallowed; a timer with no operation to retry logs and keeps running. It is logged by error code or throughForLogging()(exception type and stack trace, never its message, per theEncinaError.Messagerule of this section). (why: #2774) - Compliance and security gates fail closed: when context is missing (no
HttpContext, tenant or principal) or a lookup fails, the gate denies; the only opt-out is explicit and logged. (why: SPEC-002 DEC-006; #1143, #1145, #1148, #1155, #1161) EncinaError.MessageNEVER reaches logs, activity tags, health-check results or plaintext storage; record only the error code or the exception type. An exception passed to a logger goes throughForLogging()(its type and stack trace, never its message). (why: #1168, #1173, #1259, #1274)- Railway Oriented Programming: operations return
Either<EncinaError, T>; NEVER use exceptions for business logic; validation returnsEitherwith detailed errors. (why: ADR-001, ADR-006) - Every messaging pattern (Outbox: reliable at-least-once publishing; Inbox: idempotent exactly-once processing; Saga: orchestrated distributed transactions with compensation; Scheduling: delayed/recurring messages; Transactions: commit/rollback from the ROP result) is optional and disabled by default. A module MAY require other modules when its guarantees need them, per the closed list in ADR-050, enforced by auto-registration, startup validation or registration errors; opt-in remains the rule for everything a module does not need. Example:
config.UseOutbox = true;. (why: #2239, #2381; ADR-050) - The repository pattern is optional and NEVER forced. Default to
DbContext(already a unit of work) andDbSet<T>; consider a repository only for several DbContexts or databases, transactions with non-EF components, mocking, switching providers, or DDD aggregate repositories. Opt in per entity:services.AddEncinaRepository<Order, OrderId>();. - Provider coherence: abstractions (
IOutboxStore,IInboxStore, ...) and options live inEncina.Messaging; providers share the same interfaces and configuration and differ only in implementation, so switching provider means changing the DI registration. NEVER mix provider-specific code into abstractions. - Validation uses the orchestrator pattern:
IValidationProvider,ValidationOrchestrator,ValidationPipelineBehavior<,>,ValidationResultandValidationErrorlive in coreEncina.Validation; each validation package implements*ValidationProviderand its registration (AddEncinaFluentValidation(assembly),AddDataAnnotationsValidation(),AddMiniValidation()) registers provider, orchestrator and behavior. - Scheduling: Encina scheduling carries domain messages (commands, queries, notifications); Hangfire/Quartz run infrastructure jobs. They coexist; adapters to use them as scheduling backends are future work.
- Event-sourced compliance modules have no InMemory stores: unit tests mock
IAggregateRepository(NSubstitute) and integration tests run against Marten on PostgreSQL through Testcontainers. Marten projections take dependencies throughIDocumentOperationsand constructor injection, NEVERIServiceProvider; keep at least one test that registers each projection with a real store. (why: #777, #783, #784, #785, #949; ADR-019) - Pattern choice: Outbox for publishing domain events, Inbox for external messages (webhooks, queue consumers), Saga for cross-service transactions, Scheduling for delayed domain operations, Transactions for automatic commit/rollback.
- Entities:
OutboxMessage,InboxMessage,SagaState,ScheduledMessage(neverMessage,Saga,ScheduledCommand). - Properties:
RequestType/NotificationType(notMessageType);ErrorMessage(neverError, CA1716); UTC timestamps with theAtUtcsuffix (CreatedAtUtc,ProcessedAtUtc,ScheduledAtUtc; sagas:StartedAtUtc,LastUpdatedAtUtc,CompletedAtUtc);RetryCount,NextRetryAtUtc(notAttemptCount); descriptive identifiers (SagaId, notId, when implementing an interface). - Stores:
{Pattern}Store{Provider}(OutboxStoreEF,OutboxStoreDapper), never a bareStoreorRepository. - Feature-specific stores and helpers inside a provider package live in a folder named after the feature (
LawfulBasis/,Consent/), not after the package defining the abstraction (GDPR/). (why: #413)
Database: every provider-dependent feature MUST be implemented for all 10 providers. It applies to every store (outbox, inbox, saga, scheduled message, ...), repositories, unit of work, bulk operations, anything with database-specific SQL or connection types, and registrations in ServiceCollectionExtensions.
| Family | Providers |
|---|---|
| ADO.NET | SqlServer, PostgreSQL, MySQL |
| Dapper | SqlServer, PostgreSQL, MySQL |
| EF Core | SqlServer, PostgreSQL, MySQL |
| MongoDB | MongoDB |
SQL differences per database: SQL Server uses @param, TOP (@n), bit, native DateTime and GUID; PostgreSQL uses @param, LIMIT @n, true/false, case-sensitive identifiers; MySQL uses @param, LIMIT @n, 0/1, backtick identifiers.
Oracle (ADR-009, code in .backup/oracle/) and SQLite (ADR-024, packages in .backup/, not built, tested or guaranteed) are out of the matrix. Message brokers, caching and event sourcing (Marten) are excluded from the database rule; they follow their own category below.
Specialized categories: a feature that touches one MUST be consistent across every provider of that category.
| Category | Providers | 1.0 scope | Every provider MUST support |
|---|---|---|---|
| Caching (8) | Memory (L1), Hybrid (L1+L2), Redis, Valkey, Dragonfly, Garnet, KeyDB, Memcached (planned) | all 8 (SPEC-000 REQ-027, #277) | Get/Set/Remove; TTL/expiration; serialization abstraction; pub/sub backplane where applicable. Applies to ICacheProvider, IPubSubProvider, stampede protection, eager refresh, fail-safe, tag invalidation, read/write-through |
| Transports (10 + 6 planned) | RabbitMQ, AzureServiceBus, AmazonSQS, Kafka, NATS, Redis.PubSub, MQTT, InMemory, gRPC, GraphQL; planned for 1.0 (v0.19.0): GoogleCloudPubSub, AmazonEventBridge, Pulsar, Redis.Streams, ActiveMQ, Dapr | the 10 existing and the 6 planned are in 1.0 scope (SPEC-000 DEC-009); the cloud-tied ones are tested with local emulators | Send/Publish; subscription management; error handling and DLQ; metadata propagation. Applies to IMessageTransport, outbox publishing, inbox consumption, DLQ |
| Distributed locks | InMemory (testing), Redis (Redlock), SqlServer (sp_getapplock), PostgreSQL (pg_advisory_lock, #207), MySQL (GET_LOCK, #208), Azure Blob (#209), DynamoDB (#210); post-1.0: Consul, etcd, ZooKeeper |
exactly these 7 (SPEC-000 DEC-009); a lock feature is complete for 1.0 when they are covered; the cloud ones are tested with Azurite and LocalStack | TryAcquire with timeout; auto-release on timeout; CancellationToken. Applies to IDistributedLockProvider, leader election, resource coordination |
| Validation (3) | FluentValidation, DataAnnotations, MiniValidator | all 3 | integrate with ValidationOrchestrator; return ValidationResult; same ValidationPipelineBehavior. Applies to IValidationProvider and its registration |
| Cloud | AwsLambda, AzureFunctions; GoogleCloudFunctions (#205) | AWS + Azure; GCP is post-1.0 (SPEC-000 §6.1, REQ-028): note the GCP gap in the issue | consider the AWS/Azure/GCP triangle for any cloud-specific feature |
Other categories: Scheduling (built-in Encina.Messaging, Hangfire, Quartz; applies to IScheduledMessageStore and scheduler adapters); Event sourcing (Marten primary, EventStoreDB future; applies to aggregate repositories, projections, snapshots, crypto-shredding); Resilience (Polly, Extensions.Resilience, Extensions.Http.Resilience); Observability (OpenTelemetry; planned exporters AzureMonitor, AwsXRay, Prometheus); Testing packages (Encina.Testing, .Fakes, .Respawn, .WireMock, .Shouldly, .Verify, .Bogus, .FsCheck, .Architecture, .Testcontainers, .TUnit, .Pact).
Applicability matrix (✅ required; ◐ where applicable; empty: not applicable):
| Feature | Database (10) | Caching (8) | Transport | Lock | Validation (3) |
|---|---|---|---|---|---|
| Outbox / Inbox / Saga, Scheduled messages, Unit of Work, Audit trail | ✅ | ||||
| Query caching | ✅ | ||||
| Message publishing | ✅ | ||||
| Resource locking | ✅ | ||||
| Request validation | ✅ | ||||
| Multi-tenancy | ✅ | ◐ | ◐ |
Rule of thumb: if a feature touches provider-specific code, implement it consistently across ALL providers of that category (new cache pattern → 8 caches; transport-agnostic feature → all transports; coordination → all lock providers; validation pattern → all 3; cloud feature → the triangle).
Every feature that creates entities, stores, pipeline behaviors, background services or external integrations MUST be evaluated against all 12 functions. For each one record, in the plan or the PR: Integrate (implement now), Defer (open an issue and reference it) or Not applicable (one sentence why).
| # | Function | Question | Integration point |
|---|---|---|---|
| 1 | Caching | Reads data that benefits from caching? | ICacheProvider, decorator, [Cache] |
| 2 | OpenTelemetry | Operations worth tracing/metering? | ActivitySource, Meter, semantic attributes |
| 3 | Structured logging | Needs operational visibility? | Log.cs with [LoggerMessage], EventId range |
| 4 | Health checks | Has a checkable dependency? | IEncinaHealthCheck |
| 5 | Validation | Receives input? | IValidationProvider, pipeline behavior |
| 6 | Resilience | Calls external systems? | Polly retry, circuit breaker, timeout |
| 7 | Distributed locks | Concurrent access to shared state? | IDistributedLockProvider |
| 8 | Transactions | Needs atomic multi-operation guarantees? | IUnitOfWork, TransactionPipelineBehavior |
| 9 | Idempotency | Can receive duplicates? | InboxPipelineBehavior, deduplication key |
| 10 | Multi-tenancy | Stores/queries tenant data? | TenantId, ITenantContext |
| 11 | Module isolation | Needs module scoping? | ModuleId, IModuleContext |
| 12 | Audit trail | Compliance/security implications? | IOperationAuditStore, IEntityChangeAuditStore (today IAuditLogStore, #1778), IReadAuditStore (ADR-036), audit events |
Common misses: a new store or entity misses OpenTelemetry, TenantId, ModuleId, health check; a background service misses locks, leader election, logging; an external integration misses resilience, health check, OpenTelemetry; a pipeline behavior misses validation, idempotency, audit; a messaging pattern misses transactions, locks, multi-tenancy.
- NEVER use a
[LoggerMessage]EventId without first registering its range insrc/Encina/Diagnostics/EventIdRanges.cs(public static readonly (int Min, int Max) Name = (min, max);, discovered byEventIdRanges.GetAllRanges()), and NEVER assign an EventId outside your package's range. - Workflow: pick the next free 50 or 100 id slot in the current 1000 block of your area, in the 10000+ zone (below); register it and add its row to the block registry; write
Diagnostics/*LogMessages.cswith EventIds inside it; add the new field toPublicAPI.Unshipped.txt; add the assembly to theAssemblyRangesmap oftests/Encina.UnitTests/Testing/Architecture/EncinaEventIdAllocationTests.cs(the test fails otherwise); run the architecture tests. - Pack EventIds sequentially; NEVER sparse allocations (8400, 8410, 8420). Group them by functional area. Use the
[LoggerMessage]source generator, notLoggerMessage.Define, for new code; existingLoggerMessage.Definecalls need one literalnew EventId(<n>, ...)each, which the test scans (#1125). Add XML docs naming the range (/// Event IDs: 8120-8133 (see EventIdRanges.ComplianceGDPR)). EventIdUniquenessRule(Encina.Testing.Architecture) asserts every[LoggerMessage]has an EventId, every EventId is in a range mapped to its assembly, and no ranges overlap.- New blocks are born only in the 10000+ zone, one base per area, 1000 ids per block, each area owning ten blocks (base to base+9999): Core and messaging 10000, Database 20000, Caching (and distributed locks) 30000, Transports 40000, Security and compliance 50000, Observability and platform 60000, Testing and tooling 70000, Cloud and integration 80000; a new area takes the next base (90000) by amending the ADR table. When the area's current 1000 block is full, open its next one (14000-14999 for Core and messaging). The block registry is
docs/engineering/eventid-block-registry.md, the place to read free space of the 10000+ zone (there is no free-range list here); free gaps below 10000 are not listed in it and are not allocatable;tests/Encina.UnitTests/Testing/Architecture/EventIdRegistryAgreementTests.cskeeps it in agreement withEventIdRanges.cs. Ranges registered below 10000 stay where they are, and so do blocks already reserved there (statusreserved-pre-zone); their migration is #4007.EventIdUniquenessRulehas no upper bound. (why: #4006, ADR-021)
- Zero warnings. Every CA warning is fixed or suppressed with a justification: CA1848 may be suppressed when the LoggerMessage optimisation is future work; CA2263 when dynamic serialization needs the non-generic overload; CA1716 is fixed by renaming (
Error→ErrorMessage). - Public API is tracked by
PublicAPI.Shipped.txtandPublicAPI.Unshipped.txt: RS0016 → add the symbol to Unshipped; RS0017 → remove the stale line; RS0036/RS0037 → fix the nullable annotation. FormatNamespace.Type.Member(params) -> ReturnType, withstring!(non-null) andstring?(nullable). - XML comments on every public API, with examples when helpful. Each satellite package has its own README. Architectural decisions get an ADR in
docs/architecture/adr/. - The full
Encina.slnxbuilds; no.slnfneeded. Keep-maxcpucount:1 -nodeReuse:falseinDirectory.Build.rsp(parallel MSBuild triggers CLR error 0x80131506). Load tests are excluded from standard CI (a .NET 10 JIT bug); run them locally withDOTNET_JitObjectStackAllocationConditionalEscape=0. (why: #5, #496) - CI enforces: all tests pass, zero warnings, formatting, public API compatibility.
Coverage is per flag (unit, guard, contract, property, integration). Each flag MUST independently reach its own target from .github/coverage-manifest/{Package}.json; a line covered by one flag does not count for another, and each flag has its own coverable lines. There is no project-wide percentage; branch and method coverage are informational. .github/scripts/coverage-report.cs computes it; the coverage dashboard is the result. Check the manifest before starting, run dotnet test locally, and do NOT push or merge until every applicable flag reaches its target (CI Full takes ~40 minutes; do not trigger it with incomplete work). Details: coverage methodology.
- Obligations are justified: every new file, and every file a PR touches, under
src/has per-flag targets in its package manifest's per-file "targets" with one-sentence "justifications" (demanding and realistic; a 0 only with a reason). The PR reports the measured per-flag coverage of those files against them; reviewers check both. Measure from the repository root by running each flag's test project,dotnet test tests\Encina.<Flag>Tests --collect "XPlat Code Coverage" --results-directory artifacts\coverage\<Flag>Tests(UnitTests,GuardTests,ContractTests,PropertyTests,IntegrationTests: the project and folder namescoverage-report.csclassifies), thendotnet run --file .github/scripts/coverage-report.cs -- --input artifacts/coverage --output artifacts/coverage-report(its "Per-file targets" table is the measurement) anddotnet run --file .github/scripts/coverage-report.cs -- --check-justifications. (why: #1762) - Targets never go down (MUST). A pull request cannot lower a target in a package manifest of
.github/coverage-manifest/or remove one while its source file exists, unless it carries the labeltarget-change-approved, applied by the maintainer after reading the reason. The blockingtarget-ratchetjob (inci-result) compares the manifests with the base branch. Rule and mechanism: coverage methodology. (why: #2840, #2841, #2845) - Tests MUST execute real package code: instantiate and call implementations, factories and validators. Reflection-only tests (
typeof(I).GetMethod(...)) or type-only assertions cover zero lines; contract and property tests MUST instantiate real implementations. - Documentation NEVER types coverage figures by hand; it cites
cov:<Package>/<path>.cswith<!-- covref-table: glob -->/<!-- covref: id:field -->markers (SPEC-001). Mutation data is cited with<!-- mutref-table: mut:... -->/<!-- mutref: id:field -->; markers inside fenced code blocks are not expanded. - CRAP ≤ 10 on changed methods (MUST). A PR that touches
src/fails the blockingcrap-gatejob (inci-result) if any method it adds or changes hasCRAP = comp² × (1 − cov)³ + compabove 10 (comp = cyclomatic complexity; cov = line coverage combined across all flags). Reduce the complexity or add tests; methods the diff does not touch only count as backlog. The one exemption is a singleswitchor pattern match that answers one question, marked on the line above the declaration with// crap-exempt: single-question switch — <reason>. Known attribution limits: #1355, #1360. Details: coverage methodology, gate design. (why: #1346) - Mutation score is per file with no project-wide target (methodology, guide). Stryker.NET 5 runs with the MTP runner in project mode from
tests/Encina.UnitTests, with no per-shard test filter (the MTP runner ignorestest-case-filter). The matrix is theSHARDSarray of.github/workflows/mutation-tests.yml: each entry is a;-separated list of mutate globs (!excludes a file) sized to about 30 tested mutants (up to about 45 for measured shards), andTIMEOUTSstays in lock-step with it. When a folder outgrows its shard, give its biggest files their own shards and keep the folder glob minus those files as the last one, so every new file lands in a shard. The mutation scope is risk-based (ADR-056): a package enters when it meets the written criterion, the list only grows (removing a package needs a reviewed PR), and the scope is re-opened just before 1.0 to approach all packages. (why: #1440, #1441, #1682)
Test projects (consolidated, one per type, under tests/):
Encina.UnitTests: always required; one method in isolation, dependencies mocked, fast (<1 ms per test).Encina.GuardTests: every public method with parameters; null checks throwArgumentNullException(GuardClauses.xUnit).Encina.ContractTests: public interfaces and abstract classes keep their contract.Encina.PropertyTests: FsCheck invariants for complex logic and cross-provider behavior.Encina.IntegrationTests: real databases and externals via Docker/Testcontainers, full workflows,[Trait("Category", "Integration")].Encina.LoadTests(concurrent, performance-critical code) andEncina.BenchmarkTests(hot paths, BenchmarkDotNet).- Shared infrastructure in
Encina.TestInfrastructure; reference examples inEncina.Testing.Examples. - Tests of a provider-dependent feature MUST cover all 10 database providers.
Required test types by feature category:
| Test type | Database features | Non-database features |
|---|---|---|
| Unit, Guard | required | required |
| Property | required | if the logic is complex |
| Contract | required | if public API |
| Integration | required, real databases; NEVER a .md justification |
justify if skipped |
| Load | only concurrent features (implement for Unit of Work, multi-tenancy, read/write separation; justify for repository, specification, module isolation) | justify if skipped |
| Benchmark | only hot paths (implement for read/write separation; maybe specification; justify for repository, UoW, multi-tenancy, module isolation) | justify if skipped |
Justification files: when a test type is legitimately skipped, write {TestProject}/{Provider or Feature}/{Feature}.md with: title # {Test Type} - {Provider} {Feature}, ## Status: Not Implemented, ## Justification with numbered reasons, "Adequate Coverage from Other Test Types" (unit, guard, property, contract), "Recommended Alternative", ## Related Files, ## Date: and ## Issue:. Allowed for benchmarks and load tests of thin or non-concurrent code; NEVER for unit, guard or contract tests, nor for integration tests of database features. A folder with neither .cs tests nor a .md justification means the coverage was not evaluated.
Integration test fixtures (shared containers, ~23 instead of ~71):
- Every integration test class MUST use a shared
[Collection("<Family>-<Database>")]fixture; NEVER create a per-class fixture for database tests. The template also marks the class[Trait("Category", "Integration")]and[Trait("Database", "<Db>")]. - Collections:
ADO-,Dapper-×SqlServer/PostgreSQL/MySQLuseSqlServerFixture,PostgreSqlFixture,MySqlFixture;EFCore-SqlServer/-PostgreSQL/-MySQLuseEFCoreSqlServerFixture,EFCorePostgreSqlFixture,EFCoreMySqlFixture(defined inCollections.csfiles). - NEVER use
IClassFixture<T>for database fixtures; NEVERnew SqlServerFixture()or_fixture = new(); NEVER call the fixture'sDisposeAsync()from a test (the collection owns the lifecycle). - Inject the fixture through the constructor, call
_fixture.ClearAllDataAsync()inInitializeAsync(), use_fixture.CreateConnection()for shared connections. Details: integration tests. - Local services:
docker compose --profile core|databases|messaging|caching|cloud|observability|full up -d(Docker guide); run the suite withdotnet run --file .github/scripts/run-integration-tests.cs.
Test quality:
- Descriptive names (no
Test1), Arrange-Act-Assert, one behavior per test, independent (no shared state), deterministic, resources cleaned up. - NEVER skip a test without justification, ignore a flaky test (fix or delete it), test implementation details, use
Thread.Sleep, or hard-code paths, dates or GUIDs when avoidable. - Build test data with builders.
- A test never swallows an exception thrown by the code it drives (for example out of
FakeTimeProvider.Advance); it fixes the throwing code. The fake-clock case and its observed behavior are in the "Timer callbacks must not throw" section of the testing guide. (why: #2774) - Assertions use Shouldly through
Encina.Testing.Shouldly; NEVER FluentAssertions (commercial licence). Test projects reference theEncina.Testing.*wrappers (Shouldly, Bogus, FsCheck, Verify, WireMock, Testcontainers, Fakes), not the raw libraries. (why: #429, #495, #1023)
Workflow: unit tests first, then the feature, then the other types by risk; before committing run dotnet test Encina.slnx --configuration Release (optionally --collect "XPlat Code Coverage" and dotnet run --file .github/scripts/run-stryker.cs). Balance thoroughness with velocity: test critical paths, complex logic and public APIs.
Outputs go under artifacts/, never the repository root:
artifacts/test-results/(dotnet test --results-directory artifacts/test-results),artifacts/coverage/(collectors--output artifacts/coverage),artifacts/performance/,artifacts/load-metrics/,artifacts/mutation/.runsettingsfiles and scripts write toartifacts/subdirectories.- NEVER create
TestResults/,test-results.log,coverage-*orBenchmarkDotNet.Artifacts/at the root.
BenchmarkDotNet (why: #564):
- Use
BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config), NEVERBenchmarkRunner.Run<T>()(it ignores--filter). - NEVER return
IQueryable<T>from a benchmark; materialize with.ToList(). - Verify the filter with
--list flat --filter "..."before a full run; use--job shortor--job dryfor quick validation. - Benchmark entities MUST match the operations (only
AddIncludeexisting navigation properties); results go toartifacts/performance/.
- The maintainer writes in Spanish; answer the maintainer in Spanish. Code, comments, documentation and commit messages are English only; translate to English any Spanish comment you encounter in code while editing.
- NEVER force-push
main/master. Commit messages are clear, descriptive English. - NEVER add AI attribution: no
Co-Authored-By: Claude..., no "Generated with ..." lines, no reference to AI assistance in commits or PRs. Commits appear authored solely by the repository owner. - GitHub Actions
permissions:are declared per job, never at workflow level. (why: Sonar S8264, #896)
- Every bug, feature and debt item is a GitHub issue (https://github.com/dlrivada/Encina/issues). NEVER leave an identified problem unresolved or unrecorded: fix it now, or, when fixing would derail the current work, open an issue and continue; list the issues you opened in your summary. NEVER track issues or known problems in
AGENTS.md/CLAUDE.md. - Use the matching template of
.github/ISSUE_TEMPLATE/:
| Template | Prefix | Default label | Use for |
|---|---|---|---|
bug_report.md |
[BUG] |
bug |
wrong behavior in Encina code, including failing tests caused by a code bug |
feature_request.md |
[FEATURE] |
enhancement |
new features or enhancements |
technical_debt.md |
[DEBT] |
technical-debt |
code that works but is messy, duplicated, incomplete or slow |
test_implementation.md |
[TEST] |
area-testing |
missing tests, a coverage flag below target, load tests, benchmarks |
architecture_spike.md |
[SPIKE] |
investigation |
time-boxed investigations, evaluations, architecture decisions |
epic.md |
[EPIC] |
epic |
a multi-issue initiative; create the child issues too |
refactoring.md |
[REFACTOR] |
enhancement |
restructuring without behavior change |
infrastructure.md |
[INFRA] |
area-ci-cd |
CI/CD, Docker, build system, developer tooling |
- Write clear, technical titles, concrete acceptance criteria and the same terminology in issue and PR, so linked-issue validation can judge the PR.
- Prefixes are normalized:
[TECH-DEBT]→[DEBT];[TESTING]→[TEST];[ARCHITECTURE]/[DECISION]/[REVIEW]→[SPIKE]; no[Phase N]prefixes (use milestones). - An issue body uses the headers of its template verbatim and in order, every section filled and the applicable checkboxes ticked (
[x]); read the template first.technical_debt: Type, Description, Location, Current Behavior, Expected Behavior, Root Cause, Proposed Fix, Priority, Effort Estimate, Related Issues.bug_report: Description, Steps to Reproduce, Expected Behavior, Actual Behavior, Environment, Code Sample, Stack Trace, Additional Context (plus Root Cause when known). House style: #1050 ([DEBT]), #949 ([BUG]). - A worker's issue is one pull request: one package or provider (or one declared identical sweep: the same mechanical change applied to every listed file across packages, with no new logic, declared as a sweep in the issue and the PR with its file list), at most 15 files and 1500 changed lines, with an exact file list, a measured baseline (with the command), per-file targets with a one-sentence justification (for
src/), and acceptance by command. An EPIC or an oversized issue is decomposed into such sub-issues before any worker is briefed; the brief statesSize: <files> files, <lines> lines, the spawn hook denies a brief over the limits and any[EPIC], and the blockingpr-sizejob fails any pull request over them (a worker's, a contributor's or a bot's) unless it carries the labelsize-exception-approved(the worker-brief skill describes the brief). (why: #2900, #2901, #2845, #3667) - A
[FEATURE]issue of any size is opened together with its implementation plan: right after the issue is created, the plan is written atdocs/plans/{feature}-implementation-plan-{issue}.mdwith the plan prompt (style:docs/plans/dsr-implementation-plan-404.md), delegated to the plan writer perCLAUDE.md, and its plan PR is opened in the same work step by whoever may open PRs (the orchestrator, or a lane under the own-PR protocol); the issue links that PR. The issue-opening step is not done until the plan PR exists. A plan may merge while its Dilemmas are still open: the recommendation is recorded,needs-decisionand the board gate stay for the maintainer, so opening the plan never pre-decides an alternative. A[FEATURE]issue that has neither a plan onmainnor an open plan PR 24 hours after creation fails the feature-plan check (tools/ai/issues/check-feature-plans.ps1; by default it covers[FEATURE]issues created on or after 2026-11-24, older open ones are the #3387 backlog, and-Sincemoves that cutoff). A worker that finds a follow-up[FEATURE]inside a plan or PR writes an issue file, and the orchestrator opens the issue together with its plan; otherwise the follow-up belongs inside the existing plan. (why: the 2026-11 plan backlog, #4255) - Workflow: issue → plan (features) → assign and move to In Progress → reference it in the commit or PR (
Fixes #123orCloses #123) → it closes on merge. - Changelog: NEVER edit the
[Unreleased]section ofCHANGELOG.mdby hand. A completed feature or other user-visible change addschangelog.d/<issue>-<slug>.<section>.md(section:added,changed,deprecated,removed,fixed,security; seechangelog.d/README.md). Releases fold fragments withdotnet run .github/scripts/changelog-fragments.cs -- --release <version> <yyyy-MM-dd> [title](maintainer only). - Other records:
ROADMAP.md(roadmap),docs/releases/vX.Y.Z/README.md(update after a major implementation phase),docs/architecture/adr/(after an architectural decision),docs/roadmap-documentacion.md(documentation roadmap).
| When | Read |
|---|---|
Writing or reviewing a page under docs/, a README or CONTRIBUTING |
.claude/skills/encina-docs/SKILL.md; .opencode/agents/encina-docs.md |
| Opening an issue | .claude/skills/open-issue/SKILL.md |
| Planning a feature | .claude/skills/implementation-plan/SKILL.md, the plan prompt |
| Checking provider coherence, cross-cutting functions, EventIds, the test workflow or a release | .opencode/skills/{provider-coherence, cross-cutting-check, eventid-allocation, test-workflow, release-checklist}/SKILL.md |
| Delegating to the local model | .claude/skills/local-ai-task/SKILL.md, docs/engineering/ai-task-routing.md |
| Scope of 1.0, regulatory readiness, citations, the closed-issue audit | SPEC-000, SPEC-002, SPEC-001, SPEC-003 in docs/specifications/ |
| A design decision already taken | docs/architecture/adr/index.md (ROP 001/006, providers 009/024, cross-cutting 018, Marten 019/027, EventIds 021, events 028, recoverability 029) |
| Tests and measurement | docs/testing/ (coverage, mutation, performance, integration tests, load baselines), docs/en/guides/TESTING.md |
| How the project is built and why | docs/engineering/HOW-ENCINA-IS-BUILT.md, docs/engineering/AI-DEVELOPMENT-MODEL.md, docs/engineering/PROJECT-HISTORY.md |
| The reasoning and examples behind a rule here | engineering handbook (frozen snapshot) |
| Claude Code specifics (agents, hooks, orchestration, CodeRabbit) | CLAUDE.md, .claude/agents/README.md |