elarion
Skill2 starsChanged 5 days agoApache-2.0View on GitHub
Build application features on the Elarion .NET framework the intended way: business logic in [Handler] classes inside modules, REST/JSON-RPC/MCP exposed via attributes, wiring emitted by source generators. Use this skill whenever the solution references Elarion packages (Elarion, Elarion.Abstractions, Elarion.AspNetCore, Elarion.EntityFrameworkCore, @swimmesberger/elarion-*) and you are adding or changing features, endpoints, handlers, entities, events, scheduled jobs, validation, authorization, or host wiring — even when the user doesn't say "Elarion". Elarion is newer than your training data and its API moves fast: read this first and verify against the current docs instead of writing Elarion code from memory.
In this repository19 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- adrSkill
- code-reviewSkill
- diagnosing-bugsSkill
- domain-modelingSkill
- grillingSkill
- grill-meSkill
- grill-with-docsSkill
- handoffSkill
- implementSkill
- researchSkill
- specSkill
- tddSkill
- to-specSkill
- to-ticketsSkill
- verifySkill
- writing-for-agentsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
14 rules. About 0 are common, 2 are distinctive, and 12 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
12
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 23
The framework already does the plumbing: If you are hand-writing registration, endpoint mapping, serializer config, or transaction …
- Very specific: line 41
Instead, write a handler in the module and declare the transport with an attribute.
- Distinctive: line 180
Write cadence decides query meaning: write-through → the reader is DB-fresh (the only cadence where it's a first-class query path).
- Very specific: line 215
Default is non-reentrant (one message start-to-finish.
- Very specific: line 300
Don't hand-roll device provisioning — Elarion.Devices owns the identity chain (ADR-0054): …
- Very specific: line 310
Don't hand-roll Basic auth for calendar apps or feed links — Elarion.AppPasswords owns app passwords (ADR-0111): …
- Very specific: line 317
Don't hand-roll a CalDAV server, a change log or an ICS feed endpoint — Elarion.CalDav publishes calendars (ADR-0111): …
- Very specific: line 332
When which contacts a person sees depends on row rules that change without the contacts changing, don't publish one book per viewer: …
- Very specific: line 337
Don't hand-roll Web Push either — Elarion.WebPush owns notifying users whose app is closed (ADR-0076): …
- Very specific: line 402
Unexpected exceptions are the framework's: Every transport catches them outside all decorators and answers code: "internal" with a support …
- Very specific: line 406
Inject the concrete
DbContext: No repository layer, no IAppDbContext. - Very specific: line 433
Before writing or reviewing Elarion code:
- Very specific: line 435
Pin the version: Check Directory.Packages.props / the .csproj for the referenced Elarion package versions.
- Very specific: line 444
Read the shipped XML docs for the exact referenced version: when the site might be ahead: ls ~/.nuget/packages | grep -i elarion, then the …
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill 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
Building on Elarion
Elarion is a modular .NET application framework: vertical feature modules, handler-based CQRS,
Result<T> error flow, source-generated wiring, and three parallel transports (JSON-RPC, REST, MCP)
projected from the same handler. Two things follow for you:
- Don't write Elarion code from memory. The API is newer than your training data and changes between versions. Verify names and signatures against the docs/package the app actually references (see Research the current API).
- The framework already does the plumbing. If you are hand-writing registration, endpoint mapping, serializer config, or transaction management, you are usually duplicating (and fighting) generated code.
Where code goes
Business logic lives in handlers inside modules (typically an Application project). The
host/Api project owns only infrastructure: Program.cs composition, DB provider, auth middleware.
The most common agent mistake looks like this — don't do it:
// MyApp.Api/Program.cs (or an Endpoints/ folder in the host) — WRONG
app.MapPost("/clients", async (AppDbContext db, CreateClientDto dto) => {
// ...validation + business logic inline...
});Instead, write a handler in the module and declare the transport with an attribute. If a route
genuinely can't be expressed by [HttpEndpoint], use the module's MapEndpoints escape hatch
(below) — and even there the lambda stays thin and calls a handler.
A feature, end to end
A module is a class marked [AppModule]; everything under its namespace prefix belongs to it:
namespace MyApp.Application.Modules.Clients;
[AppModule("Clients")]
public static partial class ClientsModule { }A handler is the unit of work. One class serves JSON-RPC, MCP, and (opt-in) REST:
namespace MyApp.Application.Modules.Clients.Handlers;
[Handler("clients.get")] // JSON-RPC method + MCP tool (name optional: {module}.{operation})
[HttpEndpoint("clients/{id}")] // REST opt-in: GET inferred from IQuery, ICommand → POST
public sealed class GetClient(AppDbContext db)
: IHandler<GetClient.Query, Result<GetClient.Response>> {
public sealed record Query : IQuery {
public required Guid Id { get; init; }
}
public sealed record Response(Guid Id, string Name);
public async ValueTask<Result<Response>> HandleAsync(Query query, CancellationToken ct) {
var client = await db.Clients.FirstOrDefaultAsync(c => c.Id == query.Id, ct);
return client is null
? AppError.NotFound($"Client {query.Id} not found.") // implicit → Result<Response>
: new Response(client.Id, client.Name);
}
}Register nothing. Source generators discover handlers, services ([Service]), validators,
jobs, and event consumers, and gate all of it per module (Modules:{Name}:Enabled). If a handler
"isn't found" at runtime, the cause is its namespace not being under a module, the module being
disabled, or a build diagnostic you skipped — never a missing AddScoped.
For module-less infrastructure seams (N implementations of one contract composed into a dispatch
table at boot — packet bindings, codec catalogs, pipeline stages), don't wrap them in a fake module:
author a static partial IServiceCollection AddMyBindings(this IServiceCollection services);
extension method annotated [GenerateContractSetRegistration(typeof(IMyBinding))] — the generator
fills in the body with every implementation in the assembly — and call it from the host's
composition root, exactly once. It is unconditional (never config-gated) and
TryAddEnumerable-idempotent. See the services concept ("module services vs. contract sets") for
when to use which.
Host wiring is a few generated calls (copy the current form from the quickstart doc — these names
have evolved before). Project layout is your choice: the bootstrapper discovers handlers from
referenced module assemblies and from the host compilation itself, so a tiny app can be one
project (Program.cs + modules + the trigger — samples/LiveQuotes is that shape); prefer the
host + application split (samples/Billing) as the app grows:
[assembly: GenerateModuleBootstrapper] // once, in the host
builder.Services.AddElarion(builder.Configuration); // modules + canonical JSON
builder.Services.AddElarionJsonRpc(ElarionBootstrapper.RegisterHandlers);
app.MapElarionEndpoints(app.Configuration); // all [HttpEndpoint] routes, gated
app.MapElarionJsonRpc();MapElarionEndpoints returns the route group it mapped into, so .RequireAuthorization() on it guards every
Elarion route at once; routes of [AllowAnonymous] handlers carry .AllowAnonymous() and stay open — no
path-prefix exception lists.
Custom endpoints — the escape hatch
For routes [HttpEndpoint] can't express (streaming, SSE, file download, third-party webhooks),
the module declares hooks — never the host, so the routes stay module-owned and feature-gated:
[AppModule("Clients")]
public static partial class ClientsModule {
// Optional: one group (prefix/policy/conventions) for ALL module routes, generated + hand-written.
public static IEndpointRouteBuilder ConfigureEndpointGroup(IEndpointRouteBuilder endpoints) =>
endpoints.MapGroup("").RequireAuthorization();
// Hand-written minimal-API routes. Keep the lambda thin: resolve the handler, call it,
// translate the Result — the logic itself still lives in the handler.
public static void MapEndpoints(IEndpointRouteBuilder endpoints) {
endpoints.MapPost("clients/{id}/archive", async (
Guid id,
IHandler<ArchiveClient.Command, Result<ArchiveClient.Response>> handler,
CancellationToken ct) =>
ElarionHttpResults.ToResult(await handler.HandleAsync(new(id), ct)));
}
}ElarionHttpResults.ToResult / .ToNoContentResult / .ToProblem produce the same RFC 7807
responses as generated routes; .ProducesElarionErrors() adds the OpenAPI failure metadata.
Stateful in-memory work — actors
Handlers are stateless. Default to the database for concurrency — optimistic concurrency (version
column), constraints, [Idempotent]/inbox, and scheduled jobs solve classical web-app races; most apps
need zero actors, and an actor is never the fix for "two requests raced on a row". An actor is justified
only when the unit of consistency is a live in-memory thing, in exactly three shapes: (1) it owns a
stateful external resource that must be accessed single-flight/ordered (a TCP device session, a
per-tenant API client, an OAuth token refresh); (2) hot, ephemeral, loss-tolerant state where DB
round-trips are pure overhead (live telemetry/device data, presence, live progress, write-behind
buffers — no snapshot needed); (3) a long-lived event-driven coordinator that must act exactly once
(the snapshot + single-homing shape). Rule of thumb: if the solution sketches as a table with a version
column, use the table. When one of those shapes fits, don't hand-roll a Channel + loop or a
lock-guarded singleton — that's Elarion.Actors:
[Actor] // requires [assembly: GenerateActors] (or [UseElarion])
public sealed class OrderFulfillmentActor(IActorContext<Guid> context, IEmailSender email) {
private FulfillmentState _state; // plain fields, never locked
public async Task<Result<Unit>> Ship(ShipmentInfo info, CancellationToken ct) { ... }
}
// callers — usually a handler; the handler stays the transport-facing/authorization gate:
var order = actors.Get<IOrderFulfillment>(orderId); // IActorSystem; facade is generated
var result = await order.Ship(info, ct); // mailbox-serialized, no locks- The
IActorContext<TKey>constructor parameter makes the actor keyed (one activation per key, activated on first message, passivated after ~5 min idle — in-memory state drops). No context parameter → process singleton. - Durable state: declare an
IActorState<TState>constructor parameter — the snapshot loads beforeOnActivateAsync,state.Stateis the in-memory copy (nulluntil assigned when no snapshot exists), and only explicitstate.WriteStateAsync(ct)persists (passivation never flushes;ClearStateAsyncdeletes,RecordExistsreports — the members mirror Orleans'IPersistentState<T>). DesignTStateas the query contract (mandatory): constants, derived flags, and pure transition methods live ON the record (it's shared — the actor,IActorStateReaderqueries on other instances, and SQL all deserialize the same type); actor methods only apply a transition,WriteStateAsync, then side effects (after the write — the write is the commit point). Evolve the shape with optional/defaulted properties on the record, never by migrating inOnActivateAsync. Write cadence decides query meaning: write-through → the reader is DB-fresh (the only cadence where it's a first-class query path); periodic checkpointing → the reader is bounded-stale (warm-restart mechanism, never a "live" view). Real-time views of hot in-memory state are push — the actor publishes client events from its home and the Postgres fan-out reaches every instance's browsers — neverIActorStateReaderpolling. On a concurrent snapshot change the stale activation passivates and the turn transparently re-runs once on the reloaded snapshot (so write turns as reapplyable mutations; side effects before the write are at-least-once); only sustained conflicts surface asActorSnapshotConcurrencyException. Backend: referenceElarion.Actors.PostgreSql, put[GenerateElarionActorSnapshots]on the[GenerateDbSets]context, and callservices.AddElarionPostgreSqlActorSnapshots<AppDbContext>(); registerTStatein the module'sJsonSerializerContext. Manual load/flush viaIActorLifecycle.OnActivateAsync/OnDeactivateAsyncremains the escape hatch for storage the seam doesn't fit. - The generated facade is
I{ClassName-minus-Actor}; methods must returnTask/Task<T>/ValueTask/ValueTask<T>/IAsyncEnumerable<T>(ELACT002 otherwise). Actors are module-scoped like handlers — outside a module they warn (ELACT003) and are not registered. - Ordered streams (ADR-0052) — when a consumer needs every element in order with completion/resume
(not latest-wins): the actor owns an
Elarion.Streams.StreamHub<T>field, publishes inside turns, and exposesIAsyncEnumerable<StreamItem<T>> Watch(long? resumeAfter) => _hub.SubscribeSequenced(new() { ResumeAfterSequence = resumeAfter })— a facade stream (attach = mailbox turn, enumeration off-mailbox). NoCancellationTokenparam, no[ConsumeEvent]on stream methods (ELACT012). A live enumeration retains the activation against idle passivation (refCount lifetime); snapshot-conflict and shutdown passivations ignore retention — so still complete the hub inOnDeactivateAsync(re-activation = new hub = new sequence epoch). Serve it withapp.MapElarionStream<T>(route, (ctx, after) => …)— SSE withid:= sequence,Last-Event-ID/?after=resume. Client events stay the default push tier; a stream needs a single live producer per key (route it to the actor home). - Data-rate shaping (ADR-0055) — don't hand-roll batching/throttling between "samples arrive" and
"database/UI consume":
Elarion.Buffering(inElarioncore, BCL-only, no DI) shipsWriteBehindBuffer<T>(Add(item); flushes batches via your async delegate — naturallyExecuteInsertAsync— onMaxItemsorFlushInterval, whichever first; bounded drop-oldest, single-flight,FlushAsync+ flush-on-dispose; passonFlushErrorto observe dropped batches) andKeyedConflater<TKey,TValue>(Post(key, value)latest-wins; at most one emit per key perMinIntervalvia your delegate — naturallyIClientEventPublisher.PublishAsync; leading emit immediate, trailing emit so a quiet key never ends stale; idle keys retire). Typical owner: the actor holds both as activation state and disposes them inOnDeactivateAsync. Loss-tolerant by contract — transactional data goes through handlers + outbox, not these. - Default is non-reentrant (one message start-to-finish; an actor→actor call cycle fails with a
TimeoutExceptionafter ~30 s — that's the deadlock backstop, treat it as a design smell).[Reentrant]opts into Orleans-style interleaving at await points (never parallel); don't useConfigureAwait(false)inside a reentrant actor. - Single-node by design: in-memory activations on N nodes are N independent states (with
IActorStatethey share one ETag-guarded snapshot row — safe, but optimistic). For one authoritative activation app-wide, mark it[Actor(Placement = ActorPlacementMode.SingleHome)]and register the home lease (AddElarionPostgreSqlActorHome<AppDbContext>()+[GenerateElarionRoleLeases]on the context — the home is the"actors"role of the genericIRoleLeaseleader-election primitive inElarion.Coordination.PostgreSql): one instance is elected home, calls elsewhere fail withActorNotHomedException(for HTTP endpoints, bridge with the role-holder proxy —app.UseElarionRoleHolderProxy("actors", "/live-prefixes…")before routing +AddElarionInstanceAddress()on every instance; installs nothing without a lease, and the prefix list is the future ingress rule), and event delivery follows the lease automatically: each generated actor-consumer outbox target group records the"actors"target role, so only the holder claims it (plainAddElarionOutbox<T>(), no gate to wire). Keyed actors that need spread instead usePlacement = ActorPlacementMode.VirtualShards+AddElarionPostgreSqlActorSharding<AppDbContext>()(fixedactors:partition-Nrole leases, ADR-0061). Reads from any instance useIActorStateReader.ReadAsync<TState>(key)(snapshot, no activation). For true placement/forwarding move to Orleans/Akka.NET/Proto.Actor instead of bending this. Stateless parallelism never belongs in actors — that's handlers +Task.WhenAll.
Long-lived connections — device gateways and interactive clients
Server→client facts are client events (SSE; at-most-once hints, client re-queries), ordered outputs
are streams, client→server calls are handlers. Reach for Elarion.Connections only when the
conversation itself is stateful or latency-interactive: a physical device holding a socket, live
collaborative input, or server→client RPC. The kernel (AddElarionConnections()) gives you the
node-local IClientConnectionRegistry, lifecycle observers, and a bridge that serves client-event
subscriptions over the connection with the exact same topic catalog + fail-closed auth as SSE.
The WebSocket endpoint means you write two things — an authenticator and a codec:
public sealed class GatewayHandler(...) : WebSocketConnectionHandler { // factory: one session per link
public override ValueTask<WebSocketConnectionSession?> CreateSessionAsync(
HttpContext context, CancellationToken ct) => ...new GatewaySession(...); // null = reject (403)
}
public sealed class GatewaySession(...) : WebSocketConnectionSession { // per-connection state lives here
public override async ValueTask<ClientConnectionTicket?> AuthenticateAsync(
WebSocketHandshakeContext handshake, CancellationToken ct) { ... } // null = reject
public override IClientConnectionProtocol CreateProtocol(WebSocketClientConnection c) =>
new GatewayCodec(c, ...); // parses frames, routes to the twin actor
}
// host: services.AddSingleton<GatewayHandler>(); app.UseWebSockets();
// app.MapElarionConnectionSocket<GatewayHandler>("/gateway/ws");Set PrincipalId to the device id — a device's parallel channels all register under it
(registry.GetForPrincipal(deviceId)), and a digital-twin actor keyed by device id serializes the
shared state across channels and user-triggered commands. Facts still travel as client events, even
over a connection; the sink (SendAsync/InvokeAsync) is for conversation traffic only.
Raw TCP devices use Elarion.Connections.Tcp — same authenticator/codec seams over
AddElarionTcpConnectionListener/Dialer<THandler> (or TcpConnectionEndpoints.Apply* for
bindings-as-data), plus a required Framer because TCP has no message boundaries. What the adapter owns
so you don't: optional TLS before framing (o.Tls = new TcpServerTlsOptions/TcpClientTlsOptions { … }
— fresh BCL options per connection, fail-closed validation, no plaintext fallback), late
authentication (register the ticket anonymous, then registry.PromoteAsync(connectionId, identity) —
one-way, exactly once, authenticated tickets always need a PrincipalId; client-event subscriptions drop
so the peer resubscribes), bounded backpressure (MaxPendingSends admission throws
TcpSendQueueFullException at capacity; a completed send means the frame was physically written; FIFO by
admission order, so "reply, then follow-ups" is just admitting them in order from one codec/actor turn),
and deterministic shutdown (ShutdownGracePeriod, then abort — no leaked connection tasks). For
request/reply into the device, correlate with
ConnectionPendingRequests.SendAndWaitAsync(key, sendCt => connection.SendBinaryAsync(frame, sendCt)) —
registration before send, withdrawal when the send fails. Dispatch decoded commands through a
per-connection new ConnectionHandlerInvoker(services, connection) —
invoker.InvokeAsync(decoded, ct) infers both generic arguments when the request carries a self-typed
marker (ICommand<TSelf, TResponse>/IQuery<TSelf, TResponse>); marker-free requests use
invoker.InvokeAsync<TRequest, TResponse>, named traffic invoker.InvokeNamedAsync(dispatcher, name,
request, ct) (full pipeline per message; named routes need HandlerTransports.Connection). Test codecs
socket-free with InMemoryTcpLink. High-rate connections (game-server tier) opt into the
low-allocation profile (ADR-0066), each piece independent: construct the invoker with
new ConnectionHandlerInvokerOptions { ScopeMode = ConnectionDispatchScopeMode.PerConnection } (one
reused dispatch scope + cached chain; sequential dispatch; await invoker.DisposeAsync() on close;
transaction/idempotency pipelines warn — they assume per-message scoping), declare hot handlers
[Handler(Scope = ServiceScope.Singleton)] (compile-time verified, ELSG011–013: all ctor deps provably
singleton, no scope-dependent pipeline features) and [HandlerTelemetry(HandlerTelemetryMode.None)]
(also on the module class or assembly, nearest wins), and serialize outbound payloads straight into the
framed buffer with connection.SendBinaryAsync(state, static (s, output) => …, ct) (identical
backpressure; custom TcpMessageFramers implement BeginMessage/CompleteMessage). The full profile
dispatches at 0 B/op; inbound OnBinaryAsync memory is pooled and call-scoped on every adapter — copy
it if the codec defers work. Hot value-type requests use the explicit-generic InvokeAsync overload
(the marker overload boxes a struct request).
Don't hand-roll device provisioning — Elarion.Devices owns the identity chain (ADR-0054):
AddElarionDeviceIdentityEntityFrameworkCore<TDbContext>() + [GenerateElarionDeviceIdentity] on the
context gives you IDevicePairingService (issue a single-use CSPRNG pairing code — device id
pre-assigned at issue; redeem atomically mints the per-device key; codes stored hashed) and
HmacChallengeVerifier for the in-socket handshake: CreateNonce() → send → device answers
HMAC-SHA256(key, nonce) → VerifyAsync(deviceId, nonce, mac) returns the device ClaimsPrincipal
(constant-time; null = reject) → build the ticket with PrincipalId = deviceId. The redeem endpoint is
app-owned and must be rate-limited; sweep expired codes with a [ScheduledJob] calling
IPairingCodeStore.DeleteExpiredAsync.
Don't hand-roll Basic auth for calendar apps or feed links — Elarion.AppPasswords owns app passwords (ADR-0111):
AddElarionAppPasswordsEntityFrameworkCore<TDbContext>(section) + [GenerateElarionAppPasswords] on the context, your own
own-account handlers calling IAppPasswords.CreateAsync(user.UserId, name, AppPasswordScope.Dav, ct) (secret returned
once), ListAsync and RevokeAsync, and AddAuthentication().AddElarionAppPasswordAuthentication() with
AddElarionIdentityAppPasswordPrincipals<TUser>() or o.Events.OnCreatePrincipal. Name the scheme only on the DAV
routes, never as the default. An app with its own credential table keeps it behind o.Events.OnVerifyCredential.
Don't hand-roll a CalDAV server, a change log or an ICS feed endpoint — Elarion.CalDav publishes calendars
(ADR-0111): AddElarionWebDavEntityFrameworkCore<TDbContext>(section) + [GenerateElarionDavStore],
AddElarionCalDav(section), app.MapElarionDav(). Who sees which calendar is a query handler of an
ICalDavSource<TSelf> request (static SourceName; [RequirePermission]/resource rules apply), registered with
AddElarionCalDavSource<TQuery>() in the module's ConfigureServices; the handler that changes the data calls
ICalDavPublisher.PublishAsync(new CalDavAddress(source, key), calendarEvent, ct) in its transaction (items need
Timestamp/LastModified). Feeds: an app password with AppPasswordScope.CalendarFeed(address), URL from
CalDavLinks.FeedUrl. Syncing an external calendar: CalDavClient.DiscoverAsync/SyncAsync(calendar, state); store the
returned state string and schedule the steps yourself.
Address books work the same way — Elarion.CardDav (ADR-0113): AddElarionCardDav(section) beside the same store and
MapElarionDav(); an ICardDavSource<TSelf> query handler registered with AddElarionCardDavSource<TQuery>() decides
who sees which address book, and the handler that changes the data calls
ICardDavPublisher.PublishAsync(new CardDavAddress(source, key), contact, ct) (the Contact needs Uid and a name).
Apple clients use one address book per account: publish one per user for them, with groups (ContactKind.Group, Members = [ContactMember.FromUid(uid)]) for subsets. No feeds or client.
When which contacts a person sees depends on row rules that change without the contacts changing, don't publish one
book per viewer: register a live source, AddElarionCardDavLiveSource<TQuery, TBooks>(), whose scoped
ICardDavLiveAddressBooks lists (name, ETag) and returns Contacts (or the card's own property list) per request with
WhereAuthorized (CTag only, no sync token); an application with only live books registers no DAV store. Keep URLs of a replaced server with PublishedAddressBookInfo.Segment / PublishedCalendarInfo.Segment.
Don't hand-roll Web Push either — Elarion.WebPush owns notifying users whose app is closed (ADR-0076):
AddElarionWebPushEntityFrameworkCore<TDbContext>(o => o.Subject = "mailto:…") + [GenerateElarionWebPush]
on the context, three [Handler]s delegating to WebPushSubscriptionService (subscribe, unsubscribe, public key — so your
pipeline applies) that app.MapElarionWebPush() binds over HTTP (or call them from JSON-RPC), plus AddElarionSettingsDataProtection()
(the VAPID private key is protected at rest),
then IWebPushSender.SendToUsersAsync(userIds, new WebPushMessage { Title, Body, Url, Tag }, ct) from the
consumer/job that owns the trigger — dead subscriptions are cleaned up for you. Browser side:
@swimmesberger/elarion-webpush (pushAvailability(), enablePush(api) straight from the click handler,
refreshOnStart(api)) and registerWebPushHandlers(self) from its /sw export in the service worker. Live
updates for users who have the app open stay client events.
The installable-app shell is @swimmesberger/elarion-pwa (ADR-0083), not a hand-written public/sw.js:
registerShellRouter(self, { cacheName, serverPrefixes: [...ELARION_SERVER_PREFIXES, …], navigation }) from its /sw
export in the same worker as registerWebPushHandlers (network-only navigations for server-rendered pages with
personal data, network-first for an SPA shell), registerServiceWorker('/sw.js'), createInstallPrompt() at module
load, and createUpdateWatcher({ currentVersion }) wired to the router's resolved navigations — it reloads into a new
deploy only on a path change with no dialog open or field focused, never on a foreground return. Behind an
authenticating proxy (Cloudflare Access, IAP, oauth2-proxy) pass createSessionRenewal()'s fetch to the generated
JSON-RPC client and its eventSource to the generated events client: an expired proxy session then renews with one
reload instead of failing as a CORS error — don't hand-roll an X-Requested-With/reload-on-401 wrapper.
Rules that don't change
- Errors are values. Return
Result<T>; fail withAppError.Validation / NotFound / Conflict / Forbidden / Unauthorized / BusinessRule / Internal. Implicit conversions accept both the response and the error. Exceptions are for bugs; every transport translatesAppErroritself. Declare the codes a handler returns with[ProducesError]so the schema and TS client type them (Development logs undeclared ones): shared kind-default codes go once on the assembly or[AppModule]class, and a failure a decorator adds goes on the decorator. - Validation is two-tier. Standard
System.ComponentModel.DataAnnotationson the request DTO (enforced at runtime and exported to OpenAPI/JSON-RPC/Zod schemas). Cross-field, async, or DB checks belong in the handler, inside its transaction. No FluentValidation, no pre-handler async validator — on .NET 11 that includesAsyncValidationAttributeandIAsyncValidatableObject: they run in Elarion's validation decorator, before the transaction, so a uniqueness or existence check there is a race (ELVAL003). - C# 15 (net11 projects only). Unions (
union Pet(Cat, Dog)),closedclasses,[with(...), ..]collection arguments, extension indexers, and labeledbreak/continueare newer than most training data; they exist only when the project targetsnet11.0(C# 14 onnet10.0). Useclosedrecords and unions for domain logic and actor state — prefer anullarm over_when switching on a union, since adefaultunion holdsnull. Do not use a union as a handler's return type instead ofResult<T>. Union-typed DTO properties are supported (schemaanyOf, TypeScript/Zod unions, validation of the active case), but a union with two or more object cases needs[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]and a distinguishing property per case, or System.Text.Json cannot deserialize it; noElarionFileinside a union. - Authorization sits on the handler.
[RequirePermission("resource", "verb")],[RequireRole],[RequirePolicy],[FeatureGate]— class-level, enforced identically on every transport. When the permission depends on a request member (one handler serving several record kinds), use[RequirePermissionFor(nameof(Query.Kind), Verbs.Read, AnyOf = [...])]with[PermissionResource("…")]on each enum member — never an unguarded handler that checks inside. A[FeatureGate]name must be a declared flag:[FeatureFlag]on anIFeatureFlagResolverclass (code-defined) or[BackendFeatureFlag](owned by the host's backend), withExposeToClientfor the session snapshot — there is no[ClientFeatures]. ASP.NET[Authorize]/policies are host-level extras (middleware orConfigureEndpointGroup), never the business gate. A cross-cutting rule that keys off a handler marker is anIGlobalAuthorizationRulereadingcontext.GetHandlerAttribute<T>(), not an app decorator. - Row visibility is declared once.
[ResourceFilter<T>](withBypassPermissionfor admins — it lifts owner and sharing rules, never the tenant scope) filters lists; data that belongs to a record (notes, files) usesWhereAuthorizedVia(...)on its owner's filter; extra rules are composed withQueryAuthorizers.AnyOf/AllOf; a hidden record's point check is[RequireResource(..., DenyAs = ResourceDenial.NotFound)]— never a hand-copied visibility predicate per table. - The UI reads requirements from the contract. The schema exports each method's
requires,readOnlyand[ClientTag]hints; gate actions withcanCall(rpcMethodInfo[method], capabilities)instead of repeating permission names at call sites (pass{ params }for a member-scoped permission). - Values the client needs are declared, never copied (ADR-0100). Show limits from
rpcLimitsor, by member path,rpcLimitsOf(method, path)(it mirrors the DataAnnotations, pattern and not-blank included); declare an upload's size and types with[UploadLimits]on theUploadedFilemember (the pipeline enforces them, the client checks before uploading); declare a list's quick filters as[RequestPreset]static readonly fields of the handler and count with the same field; export shared values with[ClientConstants]on a static class of the module. Never hand-writeUPLOAD_LIMIT = 50in the frontend. - Unexpected exceptions are the framework's. Every transport catches them outside all decorators and answers
code: "internal"with a supportreference; word it withConfigureElarionUnexpectedErrors, never with an exception decorator orIExceptionHandler. "Not blank" is[Required]on the string (exported as a not-blank pattern), not a custom attribute. - Inject the concrete
DbContext. No repository layer, noIAppDbContext. Entities pair anIEntityTypeConfiguration<T>marked[EntityConfiguration]with[GenerateDbSets]on the DbContext. Commands already run in a framework transaction — don't open your own. When a rule needs a lock, usedb.LockRowAsync<TEntity>(id, RowLockMode…)ordb.AdvisoryLockAsync(scope, key)inside that transaction, never hand-writtenFOR UPDATE/pg_advisory_xact_lockSQL (one key scheme,elarion.scopes reserved). - References between records stay in the database. Modules share one schema, so data owned by one module (notes,
files) keeps a real foreign key to another module's record and is removed by
ON DELETE CASCADE. For data attached to several kinds of records, use an exclusive arc (one nullable FK per kind plusCHECK (num_nonnulls(...) = 1)) or a shared identity table, never an(OwnerKind, OwnerId)pair cleaned up in application code. - In-process calls are typed. Inject
IHandler<TReq, Result<TRes>>(orIHandlerSender) so a rename is a compile error; never dispatch by string name. A request declared with a self-typed marker (Query : IQuery<Query, Response>) gets fully inferred dispatch —sender.SendAsync(new Query(id), ct)with no generic arguments. Cross-module calls go through a[ModuleContract]— the analyzer (ELMOD002) flags reaching into another module's internals. - Two event planes. Same-transaction reaction → domain event (inline, a failure rolls the command back). After-commit side effect → integration event (outbox, retried, deduped). Pub/sub only — no request/reply over the bus.
- One canonical serializer. JSON comes from source-generated contexts composed via
ConfigureElarionJson; never register a bareJsonSerializerOptionsin DI. Reflection serialization is off by default — a "type not supported" JSON error means a missing[JsonSerializable]context entry, not a reason to enable reflection. - Frontend calls the generated client.
rpc-schema.json(exported at build) →@swimmesberger/elarion-jsonrpc-client-generator→ typed client with Zod validation. Don't hand-write fetch wrappers for RPC methods.
Research the current API — don't guess
Before writing or reviewing Elarion code:
- Pin the version. Check
Directory.Packages.props/ the.csprojfor the referenced Elarion package versions. - Read the docs — they are LLM-friendly.
- Index of all pages: https://elarion.wimmesberger.dev/llms.txt
- Whole docs in one file: https://elarion.wimmesberger.dev/llms-full.txt
- Single page as raw markdown:
https://elarion.wimmesberger.dev/llms.mdx/docs/<path>/content.md, e.g./llms.mdx/docs/concepts/handlers/content.md - Source of truth is
docs/in https://github.com/swimmesberger/Elarion (ADRs underdocs/decisions/explain the why); a local checkout may exist — worth a quick look.
- Read the shipped XML docs for the exact referenced version when the site might be ahead:
ls ~/.nuget/packages | grep -i elarion, then the.xmlbeside the dll. - Build early and trust the diagnostics.
dotnet buildsurfacesEL*diagnostics (ELHTTP*, ELRPC*, ELVAL*, ELAUTH*, ELMOD002, …) — the generators enforcing these conventions. Look the id up inreference/diagnosticsand fix the cause; never suppress.
High-value pages (paths under /docs/, same layout in the repo's docs/):
| Topic | Page |
| Host wiring, first feature | getting-started/quickstart, getting-started/project-structure |
| Handlers, pipeline, services | concepts/handlers, concepts/decorator-pipelines, concepts/services |
| Modules, hooks, gating | concepts/modules, capabilities/hosting |
| REST / JSON-RPC / MCP / OpenAPI | capabilities/transports/ |
| Validation / authorization | concepts/validation, concepts/authorization, concepts/resource-authorization |
| EF, transactions, pagination, rules in queries | capabilities/entity-framework, concepts/persistence-and-transactions, capabilities/pagination, concepts/rules |
| Bulk insert (imports, backfills) | capabilities/bulk-operations |
| Preview before commit (imports, bulk changes) | concepts/previewable-commands |
| Events, outbox, idempotency | capabilities/events/, concepts/idempotency |
| Client events (live browser updates / SSE) | capabilities/events/client-events |
| Web Push (notify closed apps / PWAs) | capabilities/web-push |
| Errors | concepts/results-and-errors |
| Actors (stateful in-memory) | concepts/actors |
| Attribute / diagnostic / package tables | reference/attributes, reference/diagnostics, reference/packages |
| TS client, frontend modules | capabilities/transports/typescript-client, concepts/frontend-modules |
You're off the rails if…
- an
Endpoints//Controllers/folder or a fatMapPostlambda is growing in the host project; - you're writing
services.AddScoped<SomeHandler>(), MediatR/IRequestHandler, or any manual handler registration; - a repository interface,
IAppDbContext, or hand-rolled unit-of-work is wrapping EF; - an
ExpressionVisitorthat substitutes lambda parameters,Expression.New(…GetConstructor…)projections, or LINQKit appear in the application — a rule shared by queries and memory is aRule<,>withExpand(); - a
*.previewhandler repeats the decision of a commit handler instead of oneIPreviewableRequesthandler; - a singleton service is growing locks/
SemaphoreSlim/Channelplumbing around mutable state — that's an[Actor]; - FluentValidation just appeared in a
.csproj; - a handler carries
[Authorize]instead of[RequirePermission]; - a
try/catchreturns an error DTO instead of a failedResult<T>.
Each of these has a framework-intended counterpart described above — use it, and check the docs page from the table when the exact signature matters.
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.

